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:
- how does the assignment works here in
const {type} = car;
- Why is ‘undefined’ coming up in each of the output.
2
Answers
1. The assignment there is known as Destructuring in Javascript.
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:
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".
2.) Undefined is returned when making variable declarations – this includes when doing shorthand assignment declarations.
When doing only assignment without declaration you’ll see the value is returned.