0
0
JavascriptHow-ToBeginner · 3 min read

How to Create Object in JavaScript: Simple Syntax and Examples

In JavaScript, you can create an object using {} to define an object literal or by using the new Object() constructor. Objects store data as key-value pairs and can be created simply by assigning properties inside curly braces.
📐

Syntax

You can create an object in JavaScript using two common ways:

  • Object literal: Use curly braces {} with key-value pairs inside.
  • Object constructor: Use new Object() and then add properties.

Keys are property names and values can be any data type.

javascript
const objLiteral = { key1: 'value1', key2: 42 };
const objConstructor = new Object();
objConstructor.key1 = 'value1';
objConstructor.key2 = 42;
💻

Example

This example shows how to create an object using the object literal syntax and access its properties.

javascript
const person = {
  name: 'Alice',
  age: 30,
  greet() {
    return `Hello, my name is ${this.name}`;
  }
};

console.log(person.name);
console.log(person.age);
console.log(person.greet());
Output
Alice 30 Hello, my name is Alice
⚠️

Common Pitfalls

Common mistakes when creating objects include:

  • Forgetting commas between properties in object literals.
  • Using reserved words as keys without quotes.
  • Trying to access properties before they exist.

Also, using new Object() is less common and more verbose than object literals.

javascript
/* Wrong: Missing comma between properties */
const wrongObj = {
  name: 'Bob',
  age: 25
};

/* Right: Comma added */
const rightObj = {
  name: 'Bob',
  age: 25
};
📊

Quick Reference

MethodSyntaxDescription
Object Literal{ key: value }Simple and common way to create objects.
Object Constructornew Object()Creates an empty object to add properties later.
Object.create()Object.create(proto)Creates a new object with specified prototype.

Key Takeaways

Use object literals with curly braces {} for simple and clear object creation.
Objects store data as key-value pairs accessible by dot notation or brackets.
Always separate properties with commas in object literals to avoid syntax errors.
The new Object() syntax works but is less common and more verbose.
Use Object.create() to create objects with a specific prototype if needed.