JavaScript Objects: A Complete Explanation

Nandini BajajNandini Bajaj
4 min read

*Objects are all about Properties and methods.

Properties such as color, name, age, etc., are attributes, whereas Methods are functions within an object.

Syntax:

  • Represent data as: Key & Value pairs

  • In JavaScript, objects are defined using curly braces {}.

  • A colon :separates each key-value pair, and commas ,separate multiple pairs.

The key is always a string(symbol), and the value can be of any data type: numbers, strings, other objects, arrays, functions, etc.

const student = {//object name= student
 fname: 'Hitesh',//key:value
 lname:'Chaudhary',//string
 rollno: 24,//number
 isStudent: true,//boolean
arr:[1,4,7]//array
 address: {//another object
   city: 'Punjab',
   },
 fullname: function() {//method
   console.log('Hitesh Chaudhary');
   }
};
  • Access these properties:

    Using Dot notation or Square brackets -

  1. Dot notation is used when you know the property name in advance:
console.log(student.fname); // 'Hitesh'
console.log(student.lname); // 'Chaudhary'
console.log(student.rollno);//24
console.log(student.arr); //[1,4,7]
console.log(student.address.city); // 'Punjab'
student.fullname(); // 'Hitesh Chaudhary'
  1. Square bracket notation is used when the property name is dynamic or contains special characters:
const student_Name = 'name';
console.log(student[student_Name]); // 'Hitesh'
  • We can modify, add & delete object properties

    by simply assigning values to them-

//Modification
student.rollno = 34;
student.isStudent = false;

//addition
student.id = 2213129;

//delete
delete student.isStudent;

Methods:

  • Objects have methods - functions defined within the object.

  • These methods can perform actions or calculations using the object’s properties:

      const calculate = {
          x:1,
          y:2,
      add: function(){
      return this.x + this.y;
      }
      };
      console.log(calculate.add()) //OUTPUT: 3
    

Iteration:

To iterate over the properties of an object using loops like for…in or Object.keys(), Object.values(), or Object.entries() methods.

for(let key  in student){
console.log(key, student[key]);
}
//output: all keys with values
const keys = Object.keys(student);
keys.forEach(key => console.log(key, student[key]));
const values = Object.values(student);
values.forEach(value => console.log(value));
// output: all values
const entries = Object.entries(student); 
entries.forEach(([key, value]) => console.log(key, value));

2 Important Concepts:

  • Pass by Value

  • Pass by Reference

  1. Pass by Value:

    While calling a function, we are passing values directly inside the function as an argument.

     function Greet(name){
         console.log(`Hello ${name}!`);
     }
     // function calling
     greet("Hitesh");// passing value as an argument
     // Output:  Hello Histesh!
    
  2. Pass by Reference:

    While calling a function, we will pass a reference to a constant or a variable instead of a value directly inside a function as an argument.

function Greet(name){
    console.log(`Hello ${name}!`);
}
const name = "Hitesh";
greet(name); //passing a reference of a constant called name ='hitesh'
// Hello Hitesh!

#NOTE: In JavaScript,

  • While working with primitive data types, we copy their value.

EG: string, number, boolean, symbol, undefined, null.

  • While working with non-primitive data types, we copy their reference.

EG: arrays, objects, functions

Memory used:

Concepts:

  1. Garbage Collection:

  1. Memory Leaks:

Copying Objects & Arrays:

  • Shallow Copy

  • Deep Copy

  1. Shallow Copy:

    A shallow copy creates a new object or array,

    but it only copies the top-level properties.

    : For primitive values (like numbers, strings, booleans), the value itself is copied.

    : For nested objects/arrays, only the references to those nested structures are copied.

    i.e., both the original and the shallow-copied object/array will point to the same nested objects/arrays in memory.

    Example:

const obj = {
name: 'Version 1',
additionalInfo: { version: 1 } 
};
const shallowCopy = { ...obj };
shallowCopy.name = 'Version 2';
shallowCopy.additionalInfo.version = 2;

console.log(obj);// { name: 'Version 1', additionalInfo: { version: 2 } }
console.log(shallowCopy1); // { name: 'Version 2', additionalInfo: { version: 2 } }

Spread operator {...originalObject} for objects,

[...originalArray] for arrays.

  1. Deep Copy:

    A deep copy creates a completely independent copy of an object /array, including all nested objects and arrays.

    : The new copy does not share any references with the original.

const obj = {
name: 'Version 1',
additionalInfo: { version: 1 } 
};
const DeeCopy = JSON.parse(JSON.stringify(obj));
DeepCopy.name = 'Version 2';
DeepCopy.additionalInfo.version = 2;

console.log(obj);// { name: 'Version 1', additionalInfo: { version: 1 } }
console.log(DeepCopy); // { name: 'Version 2', additionalInfo: { version: 2 } }

Conclusion:

With the ability to store data in a structured manner and encapsulate related properties and methods, objects bring a sense of organization and efficiency to our JavaScript programs.

We explored different ways to create objects, including object literals, constructor functions, and the ES6 class syntax.

Whether it's adding or deleting properties, iterating over object properties, or leveraging object-oriented programming principles, JavaScript objects empower us to build complex and sophisticated applications. By understanding the fundamentals of objects, we can unlock the full potential of JavaScript and create elegant solutions to real-world problems.

Thank you, for joining me on this journey through JavaScript objects. Embrace the possibilities they offer, continue exploring their depths, and unleash your creativity to create extraordinary digital experiences.

Happy coding!😊

2
Subscribe to my newsletter

Read articles from Nandini Bajaj directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Nandini Bajaj
Nandini Bajaj

Passionate IT student with strong Java and Data Structures & Algorithms skills, actively enhancing coding proficiency via LeetCode. Excited by fast-paced, creative environments and looking to participate in hackathons to gain real-world exposure, build innovative solutions, and grow as a developer through teamwork and iteration.