DEV Community

Cover image for JavaScript Objects Part:1
Kiran Raj R
Kiran Raj R

Posted on • Edited on

JavaScript Objects Part:1

Objects are general building blocks of JavaScript. They can be string, number, Boolean, null, undefined or object. JavaScript objects are collection of properties, each property is a key value pair i.e. each property will contain a key and a value associated to the key. The key can be string(anything that can be converted into string) or a symbol, value can be anything that is permitted in JavaScript. An empty string can also be a key. If the value of a property is a function then the property is called a method. Object names and property names are case sensitive admin is not equal to Admin.

Creating an empty object

Method 1: let Admin = {}
Method 2: let Admin = new Object()

We can add properties after creating a object, an example is shown below.

let obj = {};       // creating an empty object
obj.name = "kiran"; // adding properties to object
obj.title = "Mr."

// output of console.log(obj) is given below
{
    "name": "kiran",
    "title": "Mr."
} 
Enter fullscreen mode Exit fullscreen mode

We can declare an object with properties in one step using object literal notation.

let admin = {
    name: "kiran raj",
    admin: true,
    greet: function(){
        console.log(`Hello ${this. name}`);
    }
}
Enter fullscreen mode Exit fullscreen mode

The object properties can be accessed using dot notation or using the bracket notation. Dot notation is most widely used one, as it is easy to use. If the key is a string with multiple words or starts with a number or have a hyphen, the property can only be accessed using the bracket notation. In bracket notation the key should be in quotes. A code snippet related to the property accessing is given below.

let admin = {
    "full name": "kiran raj",
     name:"kiran raj",
     admin: true,
     greet: function(){
       console.log(`Hello ${this. name}`);
     }
}

// Dot notation
console.log(admin.'full name'); //this will create error
console.log(admin.name);        //kirn raj
console.log(admin.admin);       //true

// Bracket notation
console.log(admin['full name']); //kiran raj
console.log(admin['name']);      //kiran raj
console.log(admin['admin']);     //true
Enter fullscreen mode Exit fullscreen mode

Add a property: objectName.newPropertyKey = value.
Delete a property: delete objectname.propertyKey

let obj = {};
obj.name = "kiran";
obj.title = "Mr.";
obj.newKey = "test";
console.log(obj.newKey);    //test       

delete obj.newKey;
console.log(obj.newKey);    //undefined 
Enter fullscreen mode Exit fullscreen mode

Undefined is assigned to unassigned object properties.

Part 2: Dot vs Bracket
Part 3: In operator and for in statement
Part 4: Constructors and this
Part 5: Object duplication

Top comments (0)