Add Property to Object in JavaScript

Web Dev
Sponsored links

In this article, I will introduce how to add property to object in JavaScript.

What is Object?

The JavaScript object is a collection of data and processing.
The data in the object is called a property, and the processing in the object is called a method.

Below is an example of an object.
Inside this object, there are two properties (name, level). The method is levelUp.

let character = {
  name : 'Plantpot',
  level : 0,
  levelUp :  function(){ 
    this.level++;
  }
}
Sponsored links

What is Property?

Properties are the data in an object.
Set as a key / value pair to access the data.
Note that the case of the key is as distinct as the variable name.

name : 'Plantpot'

In this example, the key is "name" and the value is "Plantpot".

Sponsored links

Output the value

You can get the value by specifying the name of the key in the name of the object.
There are two ways to write the script.

console.log(character.name); 
console.log(character['name']);

Note that if the key name is stored in a variable, you can only specify it with [](bracket).

const keyName = 'name';
console.log(character[keyName]);
Sponsored links

Add property to object

Below is an example of adding the age property to the character object.
There are two ways to write the script.

 character.age = 20;
character['age'] = 20;