
Join the Conversation!
Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.
In this lesson, you'll learn about the keyword in JavaScript, which is crucial for creating objects and understanding how JavaScript handles object-oriented programming.
The keyword in JavaScript is used to create a new object. At its core, the keyword performs a simple yet powerful function: it creates a new object. Let's explore this with some code examples.
When you use the keyword, you create an empty object. Here's how you can create an object using the keyword:
const person = new Object();
This line of code creates an empty object called . It's equivalent to writing . You can add properties to this object just like any other object:
person.lastname = "John";
console.log(person.lastname); // prints "John"
You can also check the type of the object:
console.log(typeof person); // prints "object"
The function is a built-in constructor in JavaScript that allows you to create objects. You can also define your own constructor functions to create objects of a specific type.
Here's how you can create a custom constructor function:
function Person(name, age, profession) {
this.name = name;
this.age = age;
this.profession = profession;
}
const john = new Person("John", 23, "Teacher");
console.log(john.name); // prints "John"
In this example, we created a constructor function and used the keyword to create an instance of .
The keyword binds to the new object being created. In the constructor function, refers to the new object.
function Person(name, age, profession) {
this.name = name;
this.age = age;
this.profession = profession;
}
JavaScript provides several built-in constructors like Date, Array, Number, etc. When you use the new keyword with these constructors, you create objects with built-in methods.
const myDate = new Date('August 11, 2025');
console.log(myDate.getFullYear()); // prints 2025
These constructors provide methods that you can use on the objects they create. For example, arrays have methods like pop, push, slice, and splice.
JavaScript also provides literal syntax for creating objects and arrays, which is a shorthand for using the new keyword.
const names = ['wes', 'kait'];
console.log(typeof names); // prints "object"
console.log(names instanceof Array); // prints true
The literal syntax is a more concise way to create objects and arrays, but under the hood, they are still objects with methods.
Understanding the new keyword and how it interacts with constructors and the this keyword is essential for mastering object-oriented programming in JavaScript.
"Please login to view comments"
Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.