Javascript Tutorial
Javascript Tutorial Introduction to Javascript JavaScript Code Editors & IDE JavaScript Hello World Example Javascript Syntax and Rules syntax_rules javascript_identifiers JavaScript Keywords & Reserved Words javascript_variables JavaScript Const JavaScript let vs var vs const Data Types in JavaScript JavaScript String Template Literals & String interpolation in JavaScript Tagged Templates in JavaScript String to Number in JavaScript Number Data Type in JavaScript NaN in JavaScript JavaScript Number Min & Max & Safe Values JavaScript EPSILON & Floating point precision Infinity in JavaScript JavaScript Bigint BigInt Vs Number in JavaScript Boolean Data Type in JavaScript Undefined in JavaScript Null in JavaScript Null vs Undefined in JavaScript JavaScript Operators Arithmetic Operators in JavaScript Unary plus & minus operators in JavaScript Increment & Decrement Operators in JavaScript Comparison or Relational operators in JavaScript Strict Equality (==) Loose Equality (===) in JavaScript Ternary Conditional Operator in JavaScript Logical Operators in JavaScript Bitwise Operators in JavaScript Assignment Operators in JavaScript Nullish Coalescing Operator in JavaScript Comma Operator in JavaScript Typeof JavaScript Operator Precedence in JavaScript JavaScript if, else & nested if statement Switch Statement in JavaScript While & Do While Loops in JavaScript For Loop in JavaScript Break statement in JavaScript Continue Statement in JavaScript Arrays in JavaScript Array Constructor in Javascript Sparse Array Vs Dense Array in JavaScript How to merge Arrays in JavaScript Array Methods in JavaScript Functions in JavaScript Function Parameters & Arguments in JavaScript JavaScript Default Parameters Pass by Value and Pass by Reference in Javascript Function Expression in Javascript Nested Functions in JavaScript Immediately-invoked Function Expressions (IIFE) JavaScript Callback Functions Arrow Functions in JavaScript Arguments Object In JavaScript Rest Parameters in JavaScript Objects in Javascript Create Objects in JavaScript JavaScript Object Properties Computed Property Names in JavaScript Object Literal in JavaScript Constructor Function & New Operator in JavaScript Delete Operator in JavaScript hasOwnProperty in JavaScript Using Getters and Setters in Javascript DefineProperty in JavaScript JavaScript Property Descriptors Enumerable, Writable & Configurable Object Destructuring in JavaScript Variable Scope in JavaScript Hoisting in JavaScript Lexical Scope & Closures in JavaScript This in JavaScript Global Object, Window & Globalthis in JavaScript Call function in Javascript Prototype In Javascript Prototype Inheritance in JavaScript Instanceof Operator in JavaScript Spread Operator in JavaScript

JavaScript Object Properties

In this tutorial. we will learn more about the Properties of Javascript objects. We will how to create a Property, how to add a Property, how to access it and how to delete it.

What is a Property

Object in JavaScript is an unordered collection of Key-Value pairs. Each key-value pair is known as Property. Where key is the name of the Property. JavaScript uses it to search for the Property in the collection.

You can also think of property as a variable attached to the JavaScript object. They are similar to a regular variable but attached to the Object.

The Javascript objects can have any number of properties. You can also create an empty object without any properties.

The key or name of the property must be unique. The property name must be a string. (But can also be a symbol type). No two properties can have the same name.

We can assign value to the Property, just like we assign value to a regular variable. The value of the Property can be a primitive value, object, function, or special getters and setters methods.

There are two kinds of Properties. Data Property & Data PropertyAccessor Property

Data Property

If the value of the property is a primitive value, object, or function then the property is Data Property.

Note that when the value of a property is a function, then we call the property a method.

Accessor Property

If the value of the property is a primitive value, object, or function then the property is Data Property.

Note that when the value of a property is a function, then we call the property a method.

Creating Object Property

We usually create a Property when we create a Javascript object. JavaScript also allows us to add or delete properties even after the creation of the object.

There are many ways in which you can create a Javascript object. For Example, the following code creates the person object consist of three properties firstName, lastName & age using the object literalsyntax

        
var person = { 
    firstName: "Allie",      //FirstName Property
    lastName: "Grater",      //lastName Property
    age: 50                  //age Property
};
  

        
    

You can read more about Object Literal in JavaScript.

Adding a new Property

You can add a new property just by assigning a value. In the following example, we assign value to the mobile property. Since the mobile property does not exist in the person object, JavaScript creates it and attaches it to the object.

        
person.mobile = "999111999"
person.city= "New York"
    
        
    

If the Property already exists the second property overwrites the first. In the example, we declare firstName again and it overwrites the previous value of the firstName.

        
var person = { 
    firstName: "Allie",   
    lastName: "Grater",   
    age: 50 ,             
    firstName:"test"
};
 
 
console.log(person.firstName)  //test
    
        
    

defineProperty

You can also add a new Property using the defineProperty method.

The Syntax for creating a new Property is as shown below.

        
Object.defineProperty(obj, prop, descriptor)
    
        
    

Where obj: The object on which to define the property. prop: The name or Symbol of the property to be defined or modified. descriptor: The descriptor for the property being defined or modified

The following example creates a new empty object person. We then add a new property firstName to it using the defineProperty method.

The third parameter of defineProperty method is the property descriptor object. We can use it to give a value to the property and also configure the property by setting its writable & enumerable & configurable flags.

        
var person = {};   // Creates a new object
 
 //Adding n new property using defineProperty
 Object.defineProperty(person, 'firstName', {
   value: "Bill",
   writable: true,
   enumerable: true,
   configurable: true
 });
  
 console.log(person)     //{firstName: "Bill"}
    
        
    

Accessing the Javascript Property

There are two ways to access a property in JavaScript

  1. Dot notation
  2. Bracket notation

Dot Property Accessor

This is the most common way to access the Property. The syntax for accessing the property using the dot notation is as follows

        
expression.property
    
        
    

Where

expression is the object or and expression that should evaluate to object.

identifier is the name of the property that you want to access. It must be a valid JavaScript identifier

For Example

        
var person = { 
    firstName: "Allie",   
    lastName: "Grater",   
    age: 50 ,             
};
 
 
person.firstName   //Allie
 
    
        
    

You can use dot notation only if the property name follows the rules of JavaScript identifiers

  1. Can contain only letters, $, _, and digits (0-9)
  2. Should not start with a digit.
  3. No Spacesn

Square Bracket Property Accessor

Square Brackets are another way to access the Property of a JavaScript Object. And It is the only way if the property name does not follow the rules of JavaScript identifiers. The Syntax is as shown below.

        
expression[property]
 
    
        
    

In the following example, full name property contains space. Space is not allowed as an identifier in JavaScript. But you can use it as the property name. But cannot access it using the dot notation. The only way to access it is using the Square Bracket

        
var person = { 
    "full name":"Allie Grater",   
};
 
person["full name"]   //Allie Grater
 
    
        
    

Setting Properties

You can use the assignment operator (=) to set the value of a property referred to via the dot notation or bracket notation. For example:

        
var person = { 
    age: 50 ,             
    "full name":"Allie Grater",   
};
 
 
person.age=60
person["full name"]="Hugo First"
 
 
console.log(person)   //{age: 60, full name: "Hugo First"}
 
    
        
    

When the property doesn’t exist, JavaScript will create it. Hence you need to be careful.

In the following example, we mistype full name as ful name. The JavaScript just creates a new property with that name and does not give any warning.

                            
var person = { 
    age: 50 ,             
    "full name":"Allie Grater",   
};
 
 
person.age=60
person["ful name"]="Hugo First"
 
console.log(person)  // {age: 60, full name: "Allie Grater", ful name: "Hugo First"}
 
  
    
        
    

The Second argument to object.create is a property descriptors.

                            
const person = {
  fullName: function() {
    console.log(this.firstName+' '+this.lastName);
  }
};
 
descriptors=  { firstName: { value: 'Alex' }, lastName: { value:'Ferguson' }}
 
const alex = Object.create(person,  descriptors);
alex.fullName()  
 
  
    
        
    

Property Names

You can use any valid string literal or Symbol as a Property Name.

We can even use the Reserved words as the property name. For Example, words like var & function etc are perfectly ok as Property Name (but not recommended)

The following example shows

        
var person = { 
    function: 50 ,                // function as property name      
    var:1000                      // keyword
};
 
 
console.log(person.function)        //50
console.log(person.var)             //1000
 
    
        
    

Creating a new object from Multiple Sources.

        
var src1 = { a: 10 };
var src2 = { b: 20 };
var src3 = { a: 1, c:30 };
var obj = Object.assign({}, src1,src2,src3);
 
console.log(obj )    //{a: 1, b: 20, c: 30}
 
    
        
    

You can also use any arbitrary string as Property Name. But we must use quotes around them. Also, you can access them only using bracket notation.

        
var obj = { 'not an identifier': 123 };
 
console.log(obj['not an identifier'])  //123
 
 
    
        
    

Computed Property Names

From ES6, you can use the expression inside the square brackets( []) to create computed property name. The JavaScript evaluates the expression and uses the return value as Property Name

        
var prefix='book_'
 
 book= {} 
 book[prefix+'title']="Eloquent JavaScript"
 book[prefix+'author']="Marijn Haverbeke"
  
  
 console.log(book.book_title)
 console.log(book.book_author)
  
 
 
    
        
    

You can refer to the Computed Property Names in JavaScript

Deleting the Javascript Property

The delete operator allows us to remove property from the object. It will remove the key-value pair from the object.

                        
obj = {
    foo:'1',
    boo:'2'
}
 
console.log(obj)  {foo: "1", boo: "2"}
 
delete obj.foo
 
console.log(obj)   {boo: "2"}                                
                                

Trying to access and property that does not exist returns undefined. Hence deleted Property returns undefined. But note that you can also set a property to undefined, the Property still exists but has the value undefined. Hence merely checking for undefined does not tell you whether the property does exist or not.

You can only delete the property owned by the object. You cannot delete the inherited properties (i.e. Prototype Properties)

You can read more about Deleting a Property in JavaScript

Read More

  1. JavaScript Tutorial
  2. Functions in JavaScript
  3. Function Arguments & Parameters
  4. Default Parameters
  5. Pass By Value & Pass By Reference
  6. Function Expression
  7. Nested Functions
  8. Immediately-invoked Function Expressions (IIFE)
  9. Callback functions
  10. Arrow functions
  11. Arguments Object
  12. Rest Parameters