Working with objects in JavaScript

JavaScript object is a non-primitive data-type that allows you to store multiple collections of data.

Syntax

        
const object_name = {
   key1: value1,
   key2: value2
}
        
    

Object Declaration

We can define objects in one line also

        
const person = { name: 'John', age: 20 };
console.log(person);

// Output : Object { name: "John", age: 20 }        
    

If we have multiple properties then object can be defined using this way.

        
const person = {
    name: 'John',
    age: 20
};

console.log(typeof person); 

// Output :  Object            
    

Here, the student is an object that stores values such as strings and numbers. person objects have two properties name, and age with particular values john & 20 respectively. When an object has multiple properties, you use a comma (,) to separate them like in the above example.

Object Properties

In JavaScript, "key: value" pairs are called properties.

        
let person = { 
    name: 'John',
    age: 20
};
        
    

In the above example, name:’john’ & age:20 are properties of an object.

Accessing Object Properties

we can access the value of a property by using its key. Properties can be accessed using dot notation and bracket notation.

Dot notation

Syntax

        
objectName.key        
    
        
const person = { 
    name: 'John', 
    age: 20, 
};

// accessing property
console.log(person.name); 
// Output : John           
    

Bracket notation

Syntax

        
objectName["propertyName"]        
    
        
const person = { 
    name: 'John', 
    age: 20, 
};

// accessing property
console.log(person["name"]);

// Output : John          
    

Nested Objects

In javascript objects also contain another object.

        
// nested object
const person = { 
    name: 'John', 
    age: 30,
    job: {
        position: 'engineer',
        sallary: 5000
    }
}

// accessing property of student object
console.log(person.job); 	//Output : {science: 70, math: 75}

// accessing property of marks object
console.log(person.job.position);  //Output : 70

// Output : 
Object { position: "engineer", sallary: 5000 }
"Engineer"        
    
Posted in

Ankit Patel

Leave a Comment

Your email address will not be published.

Scroll to Top