Shortened syntax memory loss?

I found that a neat way to convert an object like an array (e.g. NodeList, Arguments) to a real array is to use:

Array.prototype.slice.call(...);

Then I thought about how to shorten this syntax:

[].slice.call(...);

Will the last method waste time and / or memory by creating a new array every time it is called? Should I avoid this syntax in complex applications with a significant degree of importance or should it optimize JavaScript engines?

+3
source share
2 answers

I would have thought that a note []should probably be avoided. If you want to save space, why not just do:

// Once in JS
var slice = Array.prototype.slice.call;

// Many places in JS
slice(...);
+3

. ( ), . , . , 5- ECMAScript Function.prototype.bind, , :

var sl = Function.prototype.call.bind(Array.prototype.slice);
var myArr = sl([1, 2, 3], 1);
//-> [ 2, 3 ]

, , bind .

/ Array.from :

// Array.from works with any iterable or array-like object
var myArr = Array.from(arrayLike);

// Spread operator works only with iterables:
var myArr = [ ...arrayLike ];

, Traceur Babel, .

+1

Source: https://habr.com/ru/post/1765065/


All Articles