Objects in JavaScript

Objects in JavaScript

An objects in JavaScript is like a class in object-orientated languages.

An Object is a collection of properties. A property is an association between a name (or key) and a value.

For example, a person has a name, age, city, etc. These are the properties of the person.

KeyValue
firstNameSurya
lastNameSingam
age25

Creating an Object:

let employee = {
  firstName: "John",
  lastName: "Cena",
  age: 35,
};

console.log(employee); 
Object {firstName: "John", lastName: "Cena", age: 35}

Note: An identifier name must follow some rules they are

  • It can contain alphanumeric characters, _ and $. (_firstName, $age)
  • It cannot start with a number. (3firstName, age 5 )

How to Accessing Object Properties ?

We can access Object Properties by using

  • Dot Notation &
  • Bracket Notation

Dot Notation:

let employee = {
  firstName: "John",
  lastName: "Cena",
  age: 35,
};

console.log(employee.firstName); 
console.log(employee.age);
John
35

Bracket Notation:

let employee = {
  firstName: "John",
  lastName: "Cena",
  age: 35,
};

console.log(employee[firstName]); 
ReferenceError{"age is not defined"}

Note:: Bracket notation works only for invalid identifiers

Example:

let employee = {
  firstName: "John",
  lastName: "Cena",
  "age-": 35,
};

console.log(employee["age-"]); 
35

Other Accessing Methods:

Object Destructuring:

let employee = {
  firstName: "John",
  lastName: "Cena",
  age: 35,
};

let {firstName, age} = employee
console.log(firstName);
John

Using Variable as a Key:

let employee = {
  firstName: "John",
  lastName: "Cena",
  age: 35,
};

let name = "firstName"
console.log(employee[name]);
John

We can add new property to an object:

For example if i want to add employee id to the employee object

Dot Notation

let employee = {
  firstName: "John",
  lastName: "Cena",
  age: 35,
};

employee.id = "SG1280"

console.log(employee);
Object {firstName: "John", lastName: "Cena", age: 35, id: "SG1280"}

Bracket Notation:

let employee = {
  firstName: "John",
  lastName: "Cena",
  age: 35,
};

employee["id"] = "SG1280"

console.log(employee);
Object {firstName: "John", lastName: "Cena", age: 35, id: "SG1280"}

What is the use of object in JavaScript?

Main reason they are a good way to organize information, especially if you are working on larger applications.