Javascript new keyword
The new
keyword in JavaScript!
The new
keyword is used to create a new object from a constructor function. When you use new
with a function, it does several things:
- Creates a new object:
new
creates a new, empty object that is a prototype of the constructor function. - Calls the constructor function:
new
calls the constructor function, passing the new object as thethis
context. - Sets the
this
context: Thethis
context is set to the new object, allowing the constructor function to access and modify its properties. - Returns the new object: The
new
keyword returns the new object created by the constructor function.
Here's an example:
function Person(name, age) {
this.name = name;
this.age = age;
}
const person = new Person('John', 30);
console.log(person); // Output: { name: "John", age: 30 }
In this example, new
creates a new object person
and calls the Person
constructor function, passing John
and 30
as arguments. The constructor function sets the name
and age
properties on the new object, and new
returns the new object.
Why use new
?
Using new
with a constructor function has several benefits:
- Creates a new object:
new
ensures that each time you create an object, it's a brand new, independent object. - Sets the
this
context:new
sets thethis
context to the new object, making it easier to access and modify its properties. - Returns the new object:
new
returns the new object, making it easy to assign it to a variable or use it in your code.
Common mistakes
Here are some common mistakes to avoid when using new
:
- Forgetting
new
: If you forget to usenew
with a constructor function, it will return the constructor function's return value instead of creating a new object. - Not using
new
with a constructor function: If you usenew
with a non-constructor function, it will throw an error.
Best practices
Here are some best practices to keep in mind when using new
:
- Use
new
with constructor functions: Only usenew
with functions that are intended to be constructors. - Check the return value: Make sure to check the return value of the constructor function to ensure it's the new object you expect.
- Use
new
consistently: Usenew
consistently throughout your code to ensure that objects are created correctly.