Search code examples
javascriptprototypejs

Confusion about Object.create() vs Object Literals


I am currently completing the front-end web development course offered by Meta.

I am confused with the usage of Object.create() and Object Literals. Let's use the following code for the reference:

let bird = {
  hasWings: true,
  canFly: true,
  hasFeathers: true
};

let eagle = bird;
console.log("Eagle can fly: ", eagle.canFly); //"Eagle can fly: " true
eagle.canFly = false;
console.log("Eagle can fly: ", eagle.canFly); // "Eagle can fly: " false

let penguin = Object.create(bird);
penguin.canFly = false;
console.log("Penguin can fly: ", penguin.canFly); //"Penguin can fly: " false

If I can achieve the same results by simply using the object literals like in case of eagle, then what difference does using Object.create()` make in the case of penguin?

I tried to take help from ChatGPT, but it was confusing.


Solution

  • Using your code, I could rewrite something like this:

    let bird = {
      hasWings: true,
      canFly: true,
      hasFeathers: true
    };
    
    let eagle = bird;
    console.log("Eagle can fly: ", eagle.canFly); //"Eagle can fly: " true
    eagle.canFly = false;
    console.log("Eagle can fly: ", eagle.canFly); // "Eagle can fly: " false
    
    // but you changed BIRD also!!!
    console.log("Bird can fly: ", bird.canFly); // Bird cannot fly :(
    bird.canFly = true;
    console.log("Bird can fly: ", bird.canFly); // Bird can fly again :)
    // but you changed EAGLE again!
    console.log("Eagle can fly: ", eagle.canFly); // Eagle can fly again, even if you set false before
    

    To avoid those problems, Object.create() will give you a new object without any references from other objects.

    let eagle = Object.create(bird);

    Something like that.