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.
I have 2 questions with above code:
const {type} = car;
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".