Destructuring or assign operator [duplicate] - javascript

This question already has answers here:
Is it possible to destructure onto an existing object? (Javascript ES6)
(16 answers)
Closed 7 years ago.
How can I write the following using new ES6 features:
this.currentPlayer = values.currentPlayer;
this.gameOver = values.gameOver;
this.inCheck = values.inCheck;
I believe I should either use destructuring operator or Object.assign function or both

AFAIK there's no way to usefully simplify that code, unless those three fields are the only ones present in values.
If (and only if) that is the case, you can just use:
Object.assign(this, values);
There is a destructuring version, but IMHO it's not worth using because it's barely any shorter than individual explicit assignments:
({currentPlayer: this.currentPlayer,
gameOver: this.gameOver,
inCheck: this.inCheck} = values);

Related

What is the difference between Array.from(Object) and [...Object]? [duplicate]

This question already has answers here:
Array.from() vs spread syntax
(6 answers)
Closed 3 years ago.
There are these two ES6-methods of creating an array from an array-like or iterable object:
Array.from(): let arr = Array.from(Object);
Spread syntax: let arr = [...Object];
Here are both in action doing exactly the same:
let string = 'foobar';
console.log( [...string] );
console.log( Array.from(string) );
What is the difference between the two and which one should I use preferably to convert a HTMLCollection to an array?
Update for 2022
Most of us don't have to support IE anymore, and it matters a lot less which one you use than it used to because there's less potential for the kind of bug I describe below to slip through to production.
Original answer
There isn't much difference in terms of what each does (except in a few contrived scenarios), but you should almost certainly use the spread syntax. The reason is that syntax will automatically be converted by babel, the Typescript compiler, etc. but you'll need to add a polyfill for Array.from unless you just don't care about older browsers. In general prefer compile/build-time solutions to run-time solutions.
Spread syntax only works with objects that implement the iterator method (Symbol.iterator()).
Array.from() on the other hand will also work on array-like objects(indexed elements) which do not implement the iterable method.
Array.from() can be used for HTML collections because of the readability as the results for both will be same in this case.

Why are't Object related methods inside the Object prototype? [duplicate]

This question already has answers here:
Why were ES5 Object methods not added to Object.prototype?
(2 answers)
Why is it Object.defineProperty() rather than this.defineProperty() (for objects)?
(3 answers)
Closed 3 years ago.
There are methods like Object.values fo Object.keys, but why aren't these methods inside the object's prototype? Is there a good reason for this?
Example:
const user = { name: 'John', role: 'admin' };
const keys = user.keys() // instead of Object.keys(user);
const values = user.values() // instead of Object.values(user);
Because everything is an object in JavaScript. If you add a method to the Object's prototype, it would be inherited to everything, it can't (or shouldn't, as it then hides the original method) be used as a name of a custom method. That means that if the Object.prototype would get polluted with a lot of methods, it would make the choice of property names more difficult:
1..keys() // Did you expect this to work?

What does ‘...’ in JavaScript do? [duplicate]

This question already has answers here:
What "..." means in Javascript (ES6)? [duplicate]
(1 answer)
Spread Syntax vs Rest Parameter in ES2015 / ES6
(11 answers)
Closed 4 years ago.
I’m new to coding and slef teaching JavaScript.
My task I was set was to identify the largest value in an array.
My soloition works, but I needed the ‘...’ for it to work properly.
My question is, what does the ‘...’ in the last line actually mean/do?
function createAnArr(){
let myArr = prompt("Enter your numbers separated by commas:").split(",");
return myArr;
}
console.log(Math.max(...createAnArr()));
'...' it means it will be able to take any number of arguments of the respective scope
'...': The spread operator is used for array construction and destructuring, and to fill function arguments from an array on invocation. A case when the operator spreads the array (or iterable object) elements.
more details you can see here

ES6 object with keys as parameter of arrow function [duplicate]

This question already has an answer here:
Where can I get info on the object parameter syntax for JavaScript functions?
(1 answer)
Closed 4 years ago.
This:
x = ({ title, description }) => { console.log(title, description) }
Works like this: (at least in terms of accessing the variables)
x = (title, description) => { console.log(title, description) }
It was quite surprising to me. First the first method describes the passed parameter as an object with certain keys title and description, but what is even more surprising, one can then access the values as normal variables.
Is it some syntactic sugar? Where is it mentioned in specification? This new JS is quite confusing.
That is ES6's Destructuring assignment
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Is there any reason that a one would use .propertyName to access a property vs. ["propertyName"] when accessing a property of an object? [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 4 years ago.
Say I have an array of objects like this:
function obj (name) {
this.name = name
}
let x = {
'foo': new obj('foo');
'bar': new obj('bar');
}
Is there an advantage to using x['foo'].name over x['foo']['name]?
I recognize that [] notation is a lot more versatile when it comes to adding things to an object or when looping through an object with for so is there any reason besides ease of use that one would choose to access it with .? Does it provide a speed increase or is it just for readability?
x.y is generally preferred as it is faster to write / nicer to use.
x["y"] is useful with obscure keys such as "d-2", "1.2" or other non-ascii characters.
In the first case, you can't do x.d-2 as this becomes x.d - 2 (completely different).

Categories