Programming with JavaScript

⌘K
  1. Home
  2. Docs
  3. Programming with JavaScri...
  4. Introduction to JavaScrip...
  5. JavaScript Objects

JavaScript Objects

JavaScript Objects

  • An object is a collection of keys – value pairs, where each key represents a property, and each value represents the corresponding data associated with that property.
  • A property key can only be a string or a symbol
  • Method is a property that has function as a value
  • Object is a function
    • In Java Script there is a default variable called Object and this variable is a function and each function in JavaScript is Object
  • Objects in JavaScript are dynamic and flexible, allowing to add, modify or remove properties and their values at run time
  • New empty object is an instance of Object

Objects are a fundamental data type that allows you to store and organize collections of key – value pairs. Objects are versatile and flexible allowing you to represent complex data structures and define custom behaviors.

Overview

  • Creating objects
  • Object Constructor
  • Accessing Object Properties
  • Modifying object properties
  • Adding and Removing Object Properties

Creating Objects

Two ways of creating object,

  • Object literal notation { }
  • Object Constructor Object( )

Object Literal

Objects can be created using object literal notation, which involves defining key – value pairs within curly braces ‘{ }’

Syntax

const object_name = {
key1 : value1
key2: value2
}

An object object_name is defined with key value pairs. Each key value pair is separated by commas and enclosed in curly braces { }.

Example

let person = {
  fname: "ABC",
  age: 18,
  dept: "CSE",
};

console.log(person);

Output

Object Constructor

 Objects can also be created using the ‘Object’ Constructor function.

Example

let person1 = new Object();
person1.fname = "CAD";
person1.age = 19;
person1["dept"] = "CSE";

console.log(person1);

Output

Accessing Object Properties

Object Properties can be accessed using dot notation or bracket notation.

Dot notation

  • It is the most common way to access object the properties of objects.
  • It uses dot (.) followed by property name.

Object_name.property_name;

Example

let person = {
  name: "Raji",
  course: "Java Script",
  num_Students: 60,
};

console.log("Name : \t" + person.name);
console.log("Course: \t" + person.course);
console.log("Number of Students: \t" + person.num_Students);

Output

Bracket notation

  • It involves using square brackets (‘[ ]’) to access object properties.
  • Inside brackets a variable, a string literal or an expression that evaluates to a string representing the property name.

Syntax

Object_name[property_name];
  • Bracket notation allows to access object.
  • It is useful when the property name is not known in advance or to access a property with a special character or a name that is not a valid identifier.

Example

let person = {
  name: "Raji",
  age: 30,
  branch: "AIML",
  "staff-id": 12345,
};

const newAge = "age"; //using variable

const newbranch = "br" + "an" + "ch"; // expression

console.log("Name: \t" + person["name"]);
console.log("Age: \t" + person[newAge]);
console.log("Branch: \t" + person[newbranch]);
console.log("Staff ID: \t" + person["staff-id"]);

//console.log(person.staff - id); //ReferenceError: id is not defined

In the code above, ‘newAge’ variable contains the string ‘age’ and person[newAge] uses bracket notation to access the ‘age’ property of the person object

Also, the ‘newbranch’ variable is created by concatenating the string “br” , “an” and “ch” resulting in ‘branch’. Using person[newbranch], one can dynamically access the “branch” property of the person object.

Output

Modifying Object Properties

Object Properties can be modified by assigning a new value to them.

Syntax

Object_name[property_name] = newValue;

Object_name.property_name = newValue;

Example

let student = {
  name: "ABC",
  age: 15,
  marks: [100, 99, 85, 92, 91],
  address: {
    city: "Chennai",
    state: "TamilNadu",
  },
};

console.log("Print Object");
console.log(student);

console.log("Mark1 of Student:\t" + student.marks[0]);

// change the value of mark1 to 78
student.marks[0] = 78; // same as student["marks"][0] = 78;

//change the age to 16
student.age = 16; // same as student["age"] = 16

//change the city to Trichy
student.address.city = "Trichy"; // student["address"]["city"] = "Trichy";

console.log("After Modification Print Object");
console.log(student);

Output

In the example above, the object student has the properties name, age, marks and address. The marks is an array containing multiple values. The property array can be accessed using the dot notation student.marks or bracket notation student[“marks”]. Both will give the array as the value of the property.

To access specific elements within the array, one can use the index inside the square brackets. For example: student.marks[0] accesses the first element of the marks array, which is 100. Similarly, student[‘marks’][1] accesses the second element 99.

One can access the properties within an object and retrieve specific elements based on their index.

Adding new Properties

A new property can be added to an object by simply assigning a value to a new key. The syntax is given as:

Object_name[new_property_name] = Value;

Object_name.new_property_name = Value;

Example

const person = {
  name: "ABC",
  age: 28,
};

person.address = "123 Main Road"; // using dot notation

person["gender"] = "Female"; // using bracket notation

person.hobby = ["gardening", "cycling"]; // adding array as property

person["hobby"][2] = "Reading"; // adding one more value for hobby array property

const prop_name = "city"; // create a variable for city property
person[prop_name] = "Trichy"; // Dynamically adding the property
// person["hobby"][1] = "cooking"; // Modifying

console.log(person);

In this example, a new property called “address” to the “person” object is created by assigning the value ‘123 Main Road’ to it.

Similarly, a new property called “gender” to the “person” object is created using bracket notation and value of “Female” is assigned.

A array property called hobby is created to include array of values. Later on, the third hobby of the person is included as person[“hobby”][2] and a value of Reading is assigned.

Also, a property can be added dynamically using bracket notation, especially when the property name is stored in a variable or needs to be generated programmatically. For example, prop_name variable is created to store the property “city” and then using bracket notation value is assigned to the property. Adding properties to an object is flexible in JavaScript that allows to expand and modify objects as needed during runtime.

Output

Removing Object Properties

Existing properties can be removed using the ‘delete’ operator.

delete Object_name.property_name;

delete Object_name[property_name];

Example

const person = {
  name: "abc",
  age: 14,
  marks: {
    m1: 90,
    m2: 89,
    m3: 78,
  },
  subject: ["Tamil", "English", "Maths"],
  gender: "male",
};
console.log(person);

delete person.age; // removes the property age
console.log("After removing age");
console.log(person);

delete person.marks.m1; // Delete m1

delete person["marks"]["m2"]; // Delete m2
console.log("After removing mark");
console.log(person);

delete person.subject[0];

console.log("After removing subject");
console.log(person);

Output

Reading the property that does not exist

Any attempt to read the property that does not exist results in undefined. For example, consider the object, obj which includes property pen and pencil with values 10 and 2 respectively. When tried to log the value for eraser it results in undefined as eraser is not the property of obj.

Example

const obj = {
  pen: 10,
  pencil: 2,
};

console.log(obj.eraser);

Output

Object Methods

Objects can also contain functions as property values, which are known as object methods. These methods can be invoked using dot notation and can operate on the object’s properties. In other words, Methods represent the properties with function as a property value

Example

let person = {
    name:"ABC",
    age: 25,
    greet:function(){
        console.log("Hi, welcome " + this.name);
    }
};

person.greet(); // Output: Hi, Welcome ABC

Output

Object Iteration

One can iterate over an object’s properties using a “for… in” loop

Code

let student = {
  name: "ABC",
  age: 15,
  marks: [100, 99, 85, 92, 91],
};

for (let key in student) {
  console.log(key + ":" + student[key]);
}

Output

Nested Objects

An object may contain another object. Example consider the code below:

/**
 *  Illustration of Nested Object
 */
let student = {
  name: "Raji",
  age: 18,
  dept: "AIML",
  mark: {
    Tamil: 96,
    Eng: 98,
  },
};

console.log("Print Object");
console.log(student);

console.log("Student Name: \t" + student.name);
console.log("Age: \t", student.age);
console.log("dept:" + student.dept);
console.log("Student Mark : \t" + student.mark);
console.log("Mark in tamil:\t" + student.mark.Tamil);
console.log("Mark in English:\t" + student.mark.Eng);
// Using bracket notation
// without "" inside bracket for property name displays ReferenceError: mark is not defined
console.log("Mark in tamil:\t" + student["mark"]["Tamil"]);

// To modify the value
student.age = 15;

student.mark.Tamil = 91;
student["mark"]["Eng"] = 89;

console.log("After Modification");
console.log("Age: \t", student.age);
console.log("Student Mark : \t" + student.mark.Tamil);
console.log("Mark in tamil:\t" + student.mark.Eng);

Output

Iteration in Nested Object

// Example nested object
var data = {
  name: "John",
  age: 30,
  address: {
    street: "123 Main St",
    city: "New York",
    country: "USA",
  },
};
function iterateNestedObject(obj) {
  for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (typeof obj[key] === "object") {
        // If the value is an object, recursively call the function
        iterateNestedObject(obj[key]);
      } else {
        // Access the key-value pair
        console.log(key + ": " + obj[key]);
      }
    }
  }
}
// Call the function to iterate over the nested object
iterateNestedObject(data);

Output

If an object is declared as const in Java script, is it possible to change the value for property

If an object is declared as ‘const’ in JavaScript, one cannot reassign the entire object to a different value. ‘const’ keyword does not make objects or their properties immutable. It only means that the variable itself cannot be reassigned.

While the object itself is not reassigned, one can still modify the properties of the object declared as ‘const’ as long as those properties are mutable.

Example

const a = { age: 20, name: "Abc", dept: "cse" };

console.log(a);

// Adding properties
a.gender = "Male";
console.log("After adding property");
console.log(a);

//deleting property
delete a.dept;
console.log("After deleting property");
console.log(a);

//Assign an object with another value
a = { isWorking: true };
console.log("Not possible for assignment");

console.log(a);

Output

Global Objects

There are two global objects Window and Global. Window is the global object in Web browser and Global is the global object in node.js. These objects contain list of properties, and some properties may contain nested Object.

console is one of the properties of Window. Open console and type node Then type global

Console is also the property of global

Console.log is also available for global object

As console is one of the property of global, the below way of accessing is syntactically meaningful.

The document property is the key property of the window object. It refers to the Document object which represents the web page loaded in the current window or frame.

Good to Know
  • JavaScript Objects are dynamic, i.e., one can add, modify or remove properties at run time. They provide a powerful way to organize and manipulate data, and they serve as the building blocks for more complex data structures in Java Script.
  • When the statements are executed in console browser, we will see undefined.
  • Never manually assign undefined as a value of any variable or property of an object. Use “Null” instead
  • Property is called Method if it holds function as a value.

Loading

Views: 18

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments