Skip to content

JavaScript Objects

Aakash Goplani edited this page Mar 3, 2020 · 18 revisions

Topics Covered


Object Literals

  • In JavaScript you can define objects without them having specific blueprint (like class). Below code defines object using literal syntax:

    let person = {
       firstName: 'aakash',
       lastName: 'goplani'
    }
    // you can also define properties on fly
    person.age = 25;
    person.isAdult = function() { return this.age >= 18; }
    
    console.log(person); // {firstName: "aakash", lastName: "goplani", age: 25, isAdult: ƒ}
    console.log(person.isAdult()); // true
  • If you have a scenario to define multiple person objects you have to repeat above code multiple times, to save time you can use functions to define objects:

    function createPerson(firstName, lastName) {
       let person = {};
       person.firstName = firstName,
       person.lastName = lastName
       return person;
    }
    
    createPerson('aakash', 'goplani'); // aakash goplani
    createPerson('aakash2', 'goplani2'); // aakash2 goplani2
  • If property name and method parameters are same, we can omit R.H.S.

    function initializeObject(firstName, lastName) {
       let person = {
          this.firstName: firstName,
          this.lastName: lastName
       }
       console.log(person);
    }
    /* can be replaced with */
    function initializeObject(firstName, lastName) {
       let person = {
          firstName,
          lastName
       }
       console.log(person);
    }
  • Object == It is Not Type Safe

    • '42' == 42
    • 0 == false
    • null == undefined
    • '' == 0
    • [1,2] = '1,2'

Object Constructor functions

  • While creating objects with Constructor function, JavaScript adds special reserved variable this and created properties on this reference and returns the object. To make JavaScript engine aware that we are using Constructor function to create objects we have to make use of new keyword

    function Person(firstName, lastName) {
       // var this = {};
       this.firstName = firstName;
       this.lastName = lastName;
       // return this;
    }
    const person = new Person('aakash', 'goplani'); // function invocation as a Constructor
    const person = Person('aakash', 'goplani'); // regular function invocation => returns undefined
  • We cannot call a constructor function using regular function invocation. that will always return undefined. In constructor function, JavaScript assign this to all properties and then returns this. this happens only when you use new keyword. For regular function invocation you don't use new keyword, so nothing gets returned.

  • However we can call regular functions using constructor mode. JavaScript engine will by default insert this. But you're not using it anywhere in your code. You create your custom object and return that.

    function createPerson(firstName, lastName) {
       // var this = {}; 
       let person = {};
       person.firstName = firstName,
       person.lastName = lastName
       return person;
       // return this;
    }
    
    const person = new createPerson('aakash', 'goplani'); // aakash goplani

Object Properties

  • Dot Notation

    obj.abc = prq;
  • Bracket Notation

    obj['abc'] = prq;
    • Special Scenarios:
      • when you want to access properties with special characters. e.g.
        obj['hello world'] = abc;
      • when you want to access property at runtime
        const varName = 'hello world'
        obj[varName] = abc;
  • Object Descriptors:

    • Lets say we have an object"

      let person = {
         firstName: 'Aakash'
         lastName: 'Goplani'
      }
    • Every Object has 3 inbuilt descriptors:

      1. enumerable: this property allows object to be iterable. Defaults to true. If set to false, you cannot use object within loops.
      Object.defineProperty('person', 'firstName', {enumerable: false});
      for (var i in person) {
         console.log(i); // DOES NOT PRINTS firstName
      }
      1. writable: this property allows object to be modified i.e. we can perform write and update operations. Defaults to true. If set to false, you cannot update/add any property of this object.
        Object.defineProperty('person', 'firstName', {writable: false});
        person.firstName: 'XYZ' // ERROR
        person.firstName.name: 'XYZ' // SUCCESS - `firstName` is not writable, but properties within `firstName` are writable
      2. configurable: this property locks down the object so that user cannot modify the object as well as other two descriptors. Defaults to true. If set to false, you cannot use object within loops.
        Object.defineProperty('person', 'firstName', {configurable: false});
        Object.defineProperty('person', 'firstName', {enumerable: false}); // ERROR: cannot change after configurable: false
        Object.defineProperty('person', 'firstName', {configurable: true}); // ERROR: cannot change after configurable: false
        Object.defineProperty('person', 'firstName', {writable: false}); // SUCCESS: you can change writable after configurable: false
    • NOTE: You can change property attribute using Object.defineProperty(object_name, property_name, {attribute_to_modify: value})

Clone this wiki locally