Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JavaScript Object Definition

Ways to Define a JavaScript Object:

  • Using an Object Literal
  • Using the new Keyword
  • Using an Object Constructor

JavaScript Object Literal

An object literal is a collection of name:value pairs enclosed in curly braces {}.

{firstName:“John”, lastName:“Doe”, age:50, eyeColor:“blue”}

Note: Name-value pairs are also referred to as key-value pairs.

Object literals are also known as object initializers.

Creating a JavaScript Object

These examples define a JavaScript object with 4 properties:

Example

// Create an Object
const person = {firstName:“John”, lastName:“Doe”, age:50, eyeColor:“blue”};

Spaces and line breaks do not affect the functionality. An object initializer can extend across multiple lines.

// Create an Object
const person = {
  firstName: “John”,
  lastName: “Doe”,
  age: 50,
  eyeColor: “blue”
};

This example initializes an empty JavaScript object and then assigns it 4 properties.

// Create an Object
const person = {};

// Add Properties
person.firstName = “John”;
person.lastName = “Doe”;
person.age = 50;
person.eyeColor = “blue”;

Using the new Keyword

This example creates a new JavaScript object using new Object(), and then assigns it 4 properties.

Example

// Create an Object
const person = new Object();

// Add Properties
person.firstName = “John”;
person.lastName = “Doe”;
person.age = 50;
person.eyeColor = “blue”;

Note: The examples above achieve the same result.

However, using new Object() is unnecessary.

For better readability, simplicity, and faster execution, prefer using the object literal syntax.