skip to Main Content

I am new to JavaScript and going through some of objects example, can some please explain below code…

const car = {type:"Fiat", model:"500", color:"white"};
const {type} = car;
console.log(type)

On running the above code in node terminal I am getting undefined with each output.

enter image description here

I have 2 questions with above code:

  1. how does the assignment works here in const {type} = car;
  2. Why is ‘undefined’ coming up in each of the output.

2

Answers


  1. 1. The assignment there is known as Destructuring in Javascript.

    The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables

    The destructuring assignment uses similar syntax of the object, but on the left-hand side of the assignment to define what values to unpack from the sourced variable.

    In your case:

    const car = {type:"Fiat", model:"500", color:"white"};
    const { type, model } = car;
    // is equivalent to:
    // const type = car.type;
    // const model = car.model;
    
    

    You can read more about Destructuring on the official MDN docs: MDN: Destructuring assignment

    2. The ‘undefined’ coming up in each of the output.

    In most javascript console, when you execute a statement or expression it prints the output/return value of the statement or expression. This is a way for the console to indicate that the statement was executed

    But if it doesn’t return a specific value, the console often displays "undefined" as the result. However, not all statements or expressions will return "undefined".

    Login or Signup to reply.
  2. 2.) Undefined is returned when making variable declarations – this includes when doing shorthand assignment declarations.

    const car = {type: "Fiat"}
    let car2 = {type: "Priaz"}
    

    When doing only assignment without declaration you’ll see the value is returned.

    car = {type: "Fiat", model: "500"}
    car2 = {type: "Priaz", model: "XW50"}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search