How to make an object in JavaScript

Learn how to create an object in JavaScript with an example: constructors, functions, the "new" keyword, and more.

Creating an Object in JavaScript

Objects are one of the fundamental data structures in JavaScript. They allow you to store and access data in an organized and structured way. Objects are created using the Object constructor or the object literal syntax.

Creating an Object Using the Object Constructor

The Object constructor is used to create an empty object. You can then add properties and methods to the object by using the dot notation.

// Create an empty object
let myObject = new Object();

// Add properties and methods
myObject.name = "John";
myObject.age = 45;
myObject.sayHello = function() {
  console.log("Hello!");
}

// Access properties and methods
console.log(myObject.name); // John
myObject.sayHello(); // Hello!

Creating an Object Using Object Literal Syntax

Object literal syntax is a convenient way to create an object. You can create an object with properties and methods in one line of code. The properties and methods are separated by commas.

// Create an object with properties and methods
let myObject = {
  name: "John",
  age: 45,
  sayHello: function() {
    console.log("Hello!");
  }
};

// Access properties and methods
console.log(myObject.name); // John
myObject.sayHello(); // Hello!

In summary, objects are a useful way to store and access data in JavaScript. You can create objects using the Object constructor or the object literal syntax.

Answers (0)