All About JS Objects...

All About JS Objects...

Introduction

  • In this blog, we will discuss objects in Javascript.
  • Objects are javascript data structures which are used to store data in a key-value pair.
  • Objects are used very extensively in other languages also, and other use cases also like API request-response structures.

About Objects

  • Stores data as key-value pairs.
  • Objects are mutable.
  • keys of the objects need to be of primitive data type and unique.
  • values of an object can be numbers, strings, functions, arrays, symbols, another object etc.
  • keys of string type with spaces need to be in " " or ' '.
    let obj = { "street name": "Olive Street, Bangalore" };
    console.log(obj["street name"]); // Olive Street, Bangalore
    
  • Can check if a variable is an object using constructor.
    let obj = new Object();
    console.log(obj.constructor === Object); // true
    

Creating and accessing an Object

  • An empty object can be created by assigning { } to a variable.
    let obj = { };
    
  • Creating an object using the new keyword (Object constructor).
    let obj = new Object();
    
  • Creating an object with data
    let obj = new Object({num: 45});
    console.log(obj); // { num: 45}
    
  • Accessing an object property using dot operator.
    let obj = new Object({num: 45});
    console.log(obj.num); // 45
    
  • Accessing an object property using [ ].
    let obj = new Object({num: 45});
    console.log(obj["num"]); // 45
    

Adding and deleting properties from an object

  • can add a property using the dot operator or using a property accessor([ ]).
    let user = {};
    user.id = 123456;
    user["name"] = "John Doe";
    console.log( user );  // { id: 123456, name: 'John Doe' }
    
  • can remove a property from an object using delete keyword.
    delete user.name;
    console.log(user); // { id: 123456 }
    

Object methods

  • assign()
  • create()
  • entries()
  • fromEntries()
  • freeze()
  • isFrozen()
  • is()
  • preventExtensions()
  • isExtensible()
  • seal()
  • isSealed()

assign()

  • assign property is used to copy all properties from one object to another by value and not by reference.
    let obj1 = { a: 10, b: 20 };
    let obj2 = {};
    Object.assign(obj2, obj1);
    console.log(obj2); // { a: 10, b: 20 }
    

create()

  • create uses creates a new object using an existing object as a prototype.
    const objRef = {
    name: "John Doe",
    printName: function () {
    console.log(this.name);
    } }
    const obj = Object.create(objRef);
    obj.name = "Sam";
    obj.printName(); // 'Sam'
    // Prototype check
    console.log(objRef.isPrototypeOf(obj)) // true
    

entries()

  • entries method returns an array of arrays of size 2, which are a key-value pair.
    const obj = {firstName: "John", lastName:  "Doe", city: "New york" };
    console.log(Object.entries(obj));
    /* Output: 
    [Array(2), Array(2), Array(2)]
    0: (2) ['firstName', 'John']
    1: (2) ['lastName', 'Doe']
    2: (2) ['city', 'New york']
    */
    

fromEntries()

  • fromEntries is used to convert a list of key-value pairs to an object.
    const objList = [ [ "firstName", "John"], [ "lastName", "Doe" ] ];
    console.log(Object.fromEntries(objList)); 
    //output: {firstName: 'John', lastName: 'Doe'}
    

freeze() and isFrozen()

  • freeze method enables us to freeze an object and does not allow the user to overwrite any properties of the object.
  • isFrozen is a way to find out whether an object is in a frozen state or not.
    const obj = { name: "John" };
    Object.freeze(obj);
    obj.name = "Jane"; // throws an error in a strict mode
    console.log(obj); // { name: 'John' }
    console.log(Object.isFrozen(obj)); // true
    

is()

  • is is a method that takes 2 parameters and returns true if both the values are same.
    const obj1 = { name: "John" };
    const obj2 = obj1;
    const obj3 = { name: "John" };
    console.log(Object.is(obj1 === obj2)); // true
    console.log(Object.is(obj1 === obj3); // false
    

preventExtensions() and isExtensible()

  • preventExtensions is used to prevent adding properties to an object in future.
  • isExtensible is used to check whether a user can add new properties to an object or not.
    const obj = { firstName: "John" };
    Object.preventExtensions(obj);
    obj.lastName = "Doe";
    console.log(obj); // { firstName: 'John' }
    obj.firstName = "Jane";
    console.log(obj); // { firstName: 'Jane' }
    console.log(Object.isExtensible(obj)); // false
    

seal() and isSealed()

  • seal method is used to prevent adding new properties to an object and delete any existing properties of the object, but values of existing attributes can be changed.
  • isSealed is a method used to find whether the object is in the sealed state or not.
    const obj = { name: "John" };
    Object.seal(obj);
    obj.name = "Jane";
    console.log(obj); // { name: 'Jane' }
    console.log(Object.isSealed(obj)); // true
    

Fun facts about JS:

  • structuredClone is a native API used make a deep clone of an object
  • There isn't any method in an Object itself to delete its own properties.
  • Do you know typeof null is an object.
  • [object Object] is a string version of an object instance.
  • NaN is of type number.
  • The initial version of JavaScript took just 10 days to develop.