I'm curious about this quizzed question? (JavaScript)

Can someone please explain to me, what is happened here: let {log} = console; log("10"); // output is same as console.log("10")

1/12/2020 8:04:57 AM

Djordje Labat 🇷🇸

3 Answers

New Answer


It's called destructuring assignment .This feature is introduced in ES6. Before this if you had to use individual methods , properties of object you had to use a verbose way. eg. let person={ name:"Lorem Ipsum", age : 27, skill:"Programming ", }; var name=person.name, age =person.age, skill =person.skill; that's extremely verbose especially when you need to unpack several properties and methods. ES6 provides concise syntax : let {name,age,skill}=person; //Done! I found it useful when using Methods of Math object. let {PI:pi, sin, cos}=Math; and all ready to use without dot or bracket notation. destructuring can be applied to arrays as well. Search on mdn and javascript.info for details.


Thanks Omkar for well explained answer. So, verbose way for my case is: let log = console.log()


Djordje Labat 🇷🇸 , Welcome ☺, Yes, Old syntax is not convenient to use. In your case it's just one method that you want to use. but suppose you wanted to unpack several methods like log(),clear(),assert(), dir(),error() then destructuring assignment is best suited. const {log, clear, assert, dir, error}=console;