DEV Community

Raja B
Raja B

Posted on

JavaScript Object

What is an Object?

A JavaScript object is a collection of properties (key-value pairs) that stores related data and functions

Simple: Like a real object (e.g., a car)
has properties (color, model, speed)
and
actions (drive, stop)

Basic Structure:

const person = {
    name: "Raja",      
    age: 27,           
    city: "Madurai"    
};
Enter fullscreen mode Exit fullscreen mode

Syntax breakdown:


- {} = curly braces (object literal)

- key: value = property (key-value pair)

- : = separates key and value

- , = separates properties


Enter fullscreen mode Exit fullscreen mode

Key Concepts

1. Properties (Key-Value Pairs)

Term Meaning
Key Property name (e.g., name, age)
Value Property data (e.g., "Raja", 27)
Property Full key-value pair together

Example:

const student = {
    name: "Bala",    // name = key, "Bala" = value
    roll: 101,       // roll = key, 101 = value
    passed: true     // passed = key, true = value
};
Enter fullscreen mode Exit fullscreen mode

Values can be ANY data type:

const data = {
    string: "hello",      // string
    number: 42,           // number
    boolean: true,        // boolean
    null: null,           // null
    array: [1, 2, 3],     // array
    object: { x: 10 },    // another object
    function: function() { console.log("hi"); }  // function
};
Enter fullscreen mode Exit fullscreen mode

2. Methods (Functions as Properties)

When a property value is a function, it's called a method

Example:

meth


Creating Objects (6 Ways)

1. Object Literal (Best/Most Common)

const person = {
    name: "Raja",
    age: 20
};
Enter fullscreen mode Exit fullscreen mode

Best for: Readability, simplicity, speed

2. Using new Object()

const person = new Object();
person.name = "Raja";
person.age = 20;
Enter fullscreen mode Exit fullscreen mode

3. Object Constructor

function Person(name, age) {
    this.name = name;
    this.age = age;
}

const p1 = new Person("Raja", 20);
Enter fullscreen mode Exit fullscreen mode

4. Using Object.create()

const personTemplate = {
    greet() { console.log("Hello!"); }
};

const person = Object.create(personTemplate);
person.name = "Raja";
Enter fullscreen mode Exit fullscreen mode

5. Using Object.assign()

const person = Object.assign(
    {}, 
    { name: "Raja" }, 
    { age: 20 }
);
Enter fullscreen mode Exit fullscreen mode

6. Using Object.fromEntries()

const person = Object.fromEntries([
    ["name", "Raja"],
    ["age", 20]
]);
Enter fullscreen mode Exit fullscreen mode
Reference:

Top comments (0)