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

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.

Related

[].slice.call() pattern in javascript [duplicate]

This question already has answers here:
Explanation of [].slice.call in javascript?
(9 answers)
Closed 1 year ago.
Bootstrap 5 Javascript examples sometimes show code like:
var collapseElementList = [].slice.call(document.querySelectorAll('.collapse'))
Why isn't this just:
var collapseElementList = document.querySelectorAll('.collapse')
What is [].slice.call() doing exactly? I don't understand why you'd slice on an empty array, and then I have no idea what call is doing there. What would be the problem with the obvious way to do this, the second way above?
querySelectorAll returns a NodeList, which is a collection, but not an array.
[].slice.call turns an array-like collection into an array proper. It will allow you to use array methodss on it, eg:
var collapseElementList = [].slice.call(document.querySelectorAll('.collapse'));
const textsOfCollapsedElements = collapseElementList.map(elm => elm.textContent);
Otherwise, if you don't convert it to an array first, you won't be able to use array methods on it.
It's probably most important for forEach. Newer browsers support NodeList.prototype.forEach, but it hasn't been with us that long. In contrast, Array.prototype.forEach has existed forever. So turning the collection into an array allows for forEach to be called on it, even on obsolete browsers that don't support NodeList.prototype.forEach.
It's an idiom for turning anything array-ish (in this case a DOM NodeList) into a real Array by exploiting the fact that Array::slice can work on anything that's iterable and has a .length property.
The modern idiom is Array.from(...).

What's the difference between using Array.of() compared with brackets [ ]? [duplicate]

This question already has answers here:
Array.of vs "[ ]". When to use Array.of over "[ ]"?
(3 answers)
What’s the difference between "Array()" and "[]" while declaring a JavaScript array?
(19 answers)
Closed 4 years ago.
For example,
let x = [1,2,3,5];
is equivalent to:
let x = Array.of(1,2,3,4,5);
(Unless I'm missing an important detail, which is why I'm asking the question)
You could also mix these with spread ... syntax and variables and thus other arrays. To me, it seems Array.of() has more overhead. Would Array.of() have to parse an arguments object into another array?
I know there's also new Array() as others have before questioned here, but that has a different semantic purpose, so I don't see this question as a duplicate to that.
As I see it now, Array.of() and [ ] seem redundant. The function's intent does seem more explicit on the former, but the latter's intent is simple enough to not be misunderstood.
So to summarize:
When is one preferable over the other?
Why does Array.of() exist when JavaScript survived without it for so long?
And, what're the differences of these two methods, if any? Would there be any needless overhead?

if I write code es6, what would be better? (let,const) [duplicate]

This question already has answers here:
What is the use case for var in ES6?
(5 answers)
Closed 6 years ago.
If I write ECMAScript 6 code, what will be better: to use only let and const or var too? I know the difference between them, but I want to know can I not use var at all? What is the best practice?
I wanted to ask about Code Style
Nice write-up by Eric Elliot on this topic: (Emphasis mine)
[...] I favor const over let in ES6. In JavaScript, const means that the identifier can’t be reassigned. (Not to be confused with immutable values. Unlike true immutable datatypes such as those produced by Immutable.js and Mori, a const object can have properties mutated.)
If I don’t need to reassign, const is my default choice over let because I want the usage to be as clear as possible in the code.
I use let when I need to reassign a variable. Because I use one variable to represent one thing, the use case for let tends to be for loops or mathematical algorithms.
I don’t use var in ES6. There is value in block scope for loops, but I can’t think of a situation where I’d prefer var over let.

Destructuring or assign operator [duplicate]

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);

Optimal way of determining array type [duplicate]

This question already has answers here:
JavaScript way to tell if an object is an Array [duplicate]
(6 answers)
Closed 7 years ago.
What is the best way to determining the object type is Array and why?.
var arr = [];
// Method #1
Array.isArray(arr);
// Method #2
toString.call(arr) == "[object Array]"
// Method #3
arr.constructor == Array
All three methods can be used to test if variable is of Array type. However, there are some nuances. I will start from the last to first.
Method #3. Will not work if variable in question came from other winndow/frame. In this case, constructor will point the the different Array object and this check will return false. For the same reason, arr instanceof Array is not bullet-proof. So it's not 100% reliable.
Method #2. This is the method that has been traditionally used to verify array type. In fact, Array.isArray polyfill is based on this method. The only disadvantage is that it's cumbersome and verbose.
Method #1. Is the one from ES5 that should finally be used to test array type, no matter what realm array comes from (like iframe). This is is the best in the list.
The prefered method is to use Array.isArray. This is present in the ES5 language specification and quite well supported by the browsers.
If you plan to support old browsers, You can find a polyfill on MDN. The polyfill is basically your second option.
The last option will not work if you play with iframes.
var arr = myIframe.contentWindow.myArray;
console.log(obj.constructor === Array); //false
The reason is that the Array constructor is diffferent for each window object. Using this to detect arrays will work 99% of the time but will suddenly fail one day.

Categories