Exploring JavaScript Objects: From Basics to Advanced Techniques

Welcome to our comprehensive JavaScript tutorial on objects. In this tutorial, we'll dive deep into the world of JavaScript objects, covering everything from the fundamentals to advanced concepts. We believe that mastering objects in JavaScript is crucial, as it forms the cornerstone of understanding the language itself.

Understanding Objects in JavaScript

In JavaScript, objects reign supreme. If you comprehend objects, you comprehend JavaScript. At its core, an object is a collection of key-value pairs, where each key is a unique identifier (a string), linked to a value, which can be of any JavaScript data type. Objects serve the purpose of grouping related data and functions, simplifying the organization and manipulation of data within your code. If you prefer video tutorials, you can also watch our accompanying Video Tutorial to reinforce your learning.

Now, let's get to the essence of objects in JavaScript.

Creating Objects

There are several ways to create objects in JavaScript. We'll explore a few of them:

  1. Object Literals

    Object literals are the most straightforward way to create objects in JavaScript. They use curly braces {} to enclose the object, with properties and their corresponding values defined inside.

const mySymbol = Symbol('forObjectKey')
const mySymbol2 = Symbol('forObjectKey')

const person = {

    firstName: "John",
    secondName:"smilga",
    "age": 22,
    isStudentHavingAnyBack : false,
// 👉using symbol inside a object, important for interviews 
    [mySymbol] : "THIS IS A SYMBOL VALUE 1",
    [mySymbol2]:"THIS IS A SYMBOL VALUE 2",

    sayHello(){
        console.log(`helo my name is${this.firstName}`)
    }

}
  1. Constructor Functions

    Constructor functions are handy when you need to create objects with similar structures. You define a constructor function and then instantiate objects from it using the new keyword.

function Person(firstName, lastName, age) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.age = age;
}

const person = new Person("Piyush ", "Tyagi", 30);
  • function Person(...): This declares a constructor function named Person that takes parameters for initializing object properties.

  • this.firstName, this.lastName, this.age: Within the constructor function, this refers to the newly created object, allowing us to set its properties.

  • const person = new Person(...): This line creates an instance of the Person object using new, passing arguments to initialize its properties.

  1. class Keyword (ES6)

    ES6 introduces the class keyword, providing a more structured approach to creating objects with constructor functions

class Person {
  constructor(firstName, lastName, age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
  }
}

const person = new Person("Piyush", "Tyagi", 30);
  • class Person { ... }: This declares a class named Person. Inside the class, you define the constructor method, responsible for initializing the object's properties.

  • constructor(...): This is a special method within a class, called when you create a new instance using new.

  • this.firstName, this.lastName, this.age: As with constructor functions, this is used to set the properties of the newly created object.

  • const person = new Person(...): This line instantiates the Person class, initializing it with values.

Accessing Object Properties

You can access object properties using either dot notation or bracket notation

  1. Dot Notation

    Syntax: objectName.keyName

    • 🔎objectName refers to the name of the object you want to access a property from.

    • 🔎keyName is the name of the property you want to access, and you specify it using dot notation.

 console.log(person.age) // output 22
 console.log(person.secondName)  //output smilga
  1. Bracket Notation

Syntax: objectName["keyName"]

🚀Bracket notation is typically used when you need to access object properties with dynamic or non-standard keys, such as Symbols. Symbols are unique and non-enumerable, which means they cannot be accessed using dot notation, but they can be accessed using bracket notation.

console.log(person["lastName"]); // Output: "Doe"

👉When you use Symbols as property keys in JavaScript objects, you can only access them using bracket notation.

//🫡you do not need to enclose the Symbol in quotes. 
//Symbols themselves act as unique property keys and should be used
// directly within the square brackets.
console.log(person[mySymbol]) 
console.log(person[mySymbol2])

Accessing all keys of an Object.

  1. Using object.Keys() method

    The Object.keys() method returns an array of a given object's own enumerable property keys.

    
     const obj = {
       name: 'piyush',
       age: 30,
       city: 'New York'
     };
    
     const keys = Object.keys(obj);
     console.log(keys); // Outputs: ['name', 'age', 'city']
    

Using a for...in loop

You can iterate over the object's keys using a for...in loop. This method also includes inherited properties, so you should use it carefully, especially if you're working with objects that may have prototype chain properties



const obj = {
  name: 'piyush',
  age: 30,
  city: 'New York'
};

for (const key in obj) {
  console.log(key); // Outputs: 'name', 'age', 'city'
}

Adding and Modifying Properties

You can add or modify object properties by simply assigning values to them.

const obj = {
  name: 'piyush',
  age: 30,
  city: 'New York'
};

//for adding property 
person.email = "john@example.com"; // Adding a new property
person.age = 31; // Modifying an existing property

Object.freeze()❄️

In JavaScript, Object. freeze() is a method that is used to make an object immutable. When an object is frozen, it cannot be modified in any way.

This includes adding or removing properties, and changing the values of existing properties. It essentially locks the object down, preventing any further alterations.

Here's how you can use Object.freeze():

const obj = {
  prop1: 10,
  prop2: "Hello",
};

// Freeze the object
Object.freeze(obj);

// 🫡Attempting to modify the object will have no effect 
//and may result in errors in strict mode

obj.prop1 = 20; // This will not change the value of obj.prop1
obj.prop3 = "World"; // This will not add a new property

console.log(obj); // Output: { prop1: 10, prop2: "Hello" }

Whether you're building web applications, working with data, or exploring the depths of JavaScript, mastering objects is a crucial step. We hope this guide has provided you with valuable insights and techniques to level up your JavaScript skills.

Remember, practice makes perfect, so don't hesitate to experiment and apply these concepts in your own projects. And if you prefer visual learning, be sure to check out our 🔖video tutorial for a hands-on demonstration of these concepts.

Happy coding!