Break down 1 liner javascript - javascript

I came across a JavaScript code that creates an array and fills it with numbers from 0-9.
The code is:
var arr = Array.apply(null, {length: 10}).map(Number.call, Number);
console.log(arr);
The code above creates an array and pushes numbers from 0-9 in it.
I do not understand how it is working. I know all the methods that are used in this like apply, map, and call but still don't understand how it is working.
Can anyone please explain the working of code by breaking it into chunks? Like how step-by-step code is being executed and how it is resulting in an array that has numbers from 0-9.

Firstly, your code creates an array of 10 elements, all of which being undefined using the below code:
Array.apply(null, {length: 10})
The above is like writing:
Array(undefined, undefined, undefined, undefined, ... 6 more times ...)
This works because the object {length: 10} is array-like as it has a length property. Usually the second argument to .apply() is an array of arguments that you want to call the function with. However, as you're passing an object in this case, JS takes the length property and calls the Array() function with 10 undefined arguments, as the keys of the {length: 10} object don't define values for properties 0 to 9.
Next, the array of 10 undefined values are mapped. When using .map(), the first argument is the mapping function and the second argument to the .map() method is the this argument, which indicates what this should refer to inside of the first mapping function. One way of looking at your map method is to rerwrite it like so:
.map((element, index, array) => Number.call(element, index, array))
The .map() method will iterate through all of your 10 undefined elements, and for each element your callback will be invoked with the index of that element. When using Number.call(), the this for the Number() function call is set to undefined (ie: element). This doesn't impact how the call to Number() behaves as it doesn't rely on any particular value for its execution. As a result, the above Number.call method is the same as using Number(index, array), where array is discarded, so it's simply performing Number(index).
The second argument to the .map() method is to define the this binding for the first mapping function that you pass into the .map() method. When you pass Number.call as the mapping function, you're passing a reference to the call method defined on Function.prototype.call. The call method only knows what function it should invoke based on its this value defined when calling the .call() method. As you're only passing the .map() method a reference to the call() function, and not invoking it with (), the this is lost, and so you need to explicitly define what the this value is. That can be done by passing through Number as the second argument to your map method call.

Related

Question about delay function source code [duplicate]

I know it is used to make arguments a real Array, but I don‘t understand what happens when using Array.prototype.slice.call(arguments);.
What happens under the hood is that when .slice() is called normally, this is an Array, and then it just iterates over that Array, and does its work.
How is this in the .slice() function an Array? Because when you do:
object.method();
...the object automatically becomes the value of this in the method(). So with:
[1,2,3].slice()
...the [1,2,3] Array is set as the value of this in .slice().
But what if you could substitute something else as the this value? As long as whatever you substitute has a numeric .length property, and a bunch of properties that are numeric indices, it should work. This type of object is often called an array-like object.
The .call() and .apply() methods let you manually set the value of this in a function. So if we set the value of this in .slice() to an array-like object, .slice() will just assume it's working with an Array, and will do its thing.
Take this plain object as an example.
var my_object = {
'0': 'zero',
'1': 'one',
'2': 'two',
'3': 'three',
'4': 'four',
length: 5
};
This is obviously not an Array, but if you can set it as the this value of .slice(), then it will just work, because it looks enough like an Array for .slice() to work properly.
var sliced = Array.prototype.slice.call( my_object, 3 );
Example: http://jsfiddle.net/wSvkv/
As you can see in the console, the result is what we expect:
['three','four'];
So this is what happens when you set an arguments object as the this value of .slice(). Because arguments has a .length property and a bunch of numeric indices, .slice() just goes about its work as if it were working on a real Array.
The arguments object is not actually an instance of an Array, and does not have any of the Array methods. So, arguments.slice(...) will not work because the arguments object does not have the slice method.
Arrays do have this method, and because the arguments object is very similar to an array, the two are compatible. This means that we can use array methods with the arguments object. And since array methods were built with arrays in mind, they will return arrays rather than other argument objects.
So why use Array.prototype? The Array is the object which we create new arrays from (new Array()), and these new arrays are passed methods and properties, like slice. These methods are stored in the [Class].prototype object. So, for efficiency sake, instead of accessing the slice method by (new Array()).slice.call() or [].slice.call(), we just get it straight from the prototype. This is so we don't have to initialise a new array.
But why do we have to do this in the first place? Well, as you said, it converts an arguments object into an Array instance. The reason why we use slice, however, is more of a "hack" than anything. The slice method will take a, you guessed it, slice of an array and return that slice as a new array. Passing no arguments to it (besides the arguments object as its context) causes the slice method to take a complete chunk of the passed "array" (in this case, the arguments object) and return it as a new array.
Normally, calling
var b = a.slice();
will copy the array a into b. However, we can’t do
var a = arguments.slice();
because arguments doesn’t have slice as a method (it’s not a real array).
Array.prototype.slice is the slice function for arrays. .call runs this slice function, with the this value set to arguments.
Array.prototype.slice.call(arguments) is the old-fashioned way to convert an arguments into an array.
In ECMAScript 2015, you can use Array.from or the spread operator:
let args = Array.from(arguments);
let args = [...arguments];
First, you should read how function invocation works in JavaScript. I suspect that alone is enough to answer your question. But here's a summary of what is happening:
Array.prototype.slice extracts the slice method from Array's prototype. But calling it directly won't work, as it's a method (not a function) and therefore requires a context (a calling object, this), otherwise it would throw Uncaught TypeError: Array.prototype.slice called on null or undefined.
The call() method allows you to specify a method's context, basically making these two calls equivalent:
someObject.slice(1, 2);
slice.call(someObject, 1, 2);
Except the former requires the slice method to exist in someObject's prototype chain (as it does for Array), whereas the latter allows the context (someObject) to be manually passed to the method.
Also, the latter is short for:
var slice = Array.prototype.slice;
slice.call(someObject, 1, 2);
Which is the same as:
Array.prototype.slice.call(someObject, 1, 2);
// We can apply `slice` from `Array.prototype`:
Array.prototype.slice.call([]); //-> []
// Since `slice` is available on an array's prototype chain,
'slice' in []; //-> true
[].slice === Array.prototype.slice; //-> true
// … we can just invoke it directly:
[].slice(); //-> []
// `arguments` has no `slice` method
'slice' in arguments; //-> false
// … but we can apply it the same way:
Array.prototype.slice.call(arguments); //-> […]
// In fact, though `slice` belongs to `Array.prototype`,
// it can operate on any array-like object:
Array.prototype.slice.call({0: 1, length: 1}); //-> [1]
Its because, as MDN notes
The arguments object is not an array. It is similar to an array, but
does not have any array properties except length. For example, it does
not have the pop method. However it can be converted to a real array:
Here we are calling slice on the native object Array and not on its implementation and thats why the extra .prototype
var args = Array.prototype.slice.call(arguments);
Dont forget, that a low-level basics of this behaviour is the type-casting that integrated in JS-engine entirely.
Slice just takes object (thanks to existing arguments.length property) and returns array-object casted after doing all operations on that.
The same logics you can test if you try to treat String-method with an INT-value:
String.prototype.bold.call(11); // returns "<b>11</b>"
And that explains statement above.
Array.prototype.slice=function(start,end){
let res=[];
start=start||0;
end=end||this.length
for(let i=start;i<end;i++){
res.push(this[i])
}
return res;
}
when you do:
Array.prototype.slice.call(arguments)
arguments becomes the value of this in slice ,and then slice returns an array
It uses the slice method arrays have and calls it with its this being the arguments object. This means it calls it as if you did arguments.slice() assuming arguments had such a method.
Creating a slice without any arguments will simply take all elements - so it simply copies the elements from arguments to an array.
Let's assume you have: function.apply(thisArg, argArray )
The apply method invokes a function, passing in the object that will be bound to this
and an optional array of arguments.
The slice() method selects a part of an array, and returns the new array.
So when you call Array.prototype.slice.apply(arguments, [0]) the array slice method is invoked (bind) on arguments.
when .slice() is called normally, this is an Array, and then it just iterates over that Array, and does its work.
//ARGUMENTS
function func(){
console.log(arguments);//[1, 2, 3, 4]
//var arrArguments = arguments.slice();//Uncaught TypeError: undefined is not a function
var arrArguments = [].slice.call(arguments);//cp array with explicity THIS
arrArguments.push('new');
console.log(arrArguments)
}
func(1,2,3,4)//[1, 2, 3, 4, "new"]
Maybe a bit late, but the answer to all of this mess is that call() is used in JS for inheritance.
If we compare this to Python or PHP, for example, call is used respectively as super().init() or parent::_construct().
This is an example of its usage that clarifies all:
function Teacher(first, last, age, gender, interests, subject) {
Person.call(this, first, last, age, gender, interests);
this.subject = subject;
}
Reference: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance
/*
arguments: get all args data include Length .
slice : clone Array
call: Convert Object which include Length to Array
Array.prototype.slice.call(arguments):
1. Convert arguments to Array
2. Clone Array arguments
*/
//normal
function abc1(a,b,c){
console.log(a);
}
//argument
function: function abc2(){
console.log(Array.prototype.slice.call(arguments,0,1))
}
abc1('a','b','c');
//a
abc2('a','b','c');
//a

What are the valid [].forEach.call function argument?

What are the valid [].forEach.call function argument? In the code below el appears to be a Nodelist or an element of the nodelist?
[].forEach.call(
document.getElementById('menu').querySelectorAll('.custom-can-transform'),
function(el){
el.classList.toggle('pure-menu-horizontal');
}
);
)
Function.prototype.call replaces the this variable of the function with its first argument, and then calls the function with all remaining arguments given to .call().
This means that the code above evaluates to this:
document.getElementById('menu').querySelectorAll('.custom-can-transform').forEach(function(el){
el.classList.toggle('pure-menu-horizontal');
});
Note that the this variable of forEach without use of the .call() method would be [], as it prefixes the forEach call.
As to what the arguments of forEach on an array are?
It only accepts 2 arguments. The first argument is the function callback that gets called for each element of the array. The second (optional) argument is used to inject a this variable into the function-body of the callback method. source
Many of the Array methods are generic by design. It means that their internal implementation doesn't rely in this to be Array instance. Basically, such implementation only requires this object to have numeric indexes and length property. Such objects are called "array-like objects".
There are many objects that conform this requirements. For example NodeList observed by you as document.getElementById('menu').querySelectorAll. This is array-like object because you can access individual Nodes by their indexes, and such node list have length property.
Any string is array-like object too. For example, string "hello world". you can access character "w" as str[t]. And str.length is equal to 11.
Requirement of numeric indexes and length property allows method implementation to iterate through all individual element of collection without need to know what this collection is actually is.
It also make it possible to use generic methods on different objects:
const obj = {0: 'one', 1: 'two', length: 2};
Array.prototype.forEach.call(obj, (el, index) => {
console.log(`${index}: ${el}`)
})
Or, the most common use for such "borrowed" other prototype methods is using array methods on non arrays, usually DOM elements:
const items = document.querySelector('ul > li')
const ids = [].map.call(items, li => li.id)
Here I should note, that spread operator from ES2015 spec, makes such borrowing methods less needed.

How JS 'arguments' object gets converted to array

Looking for more details on what exactly is happening when following is executed:
function useArray(){
var args = [].slice.call(arguments)
console.log(args)
}
How come slice being a function with 3 parameters (source array, start and end positions to copy) threats arguments correctly? Method call needs correct value of first argument as this but it seems arguments gets turned into Array object?
And why this doesn't work:
var args = [].slice(arguments)
We're using [].slice to get at the Array::slice method. arguments doesn't have a slice() of its own, but it is array-like.
Although it's a member of Array, slice() will work well enough on array-like objects -- things that have .length and can be indexed with [0..n].
slice() with no parameters returns a copy of the entire array. Its arguments are both optional.
So it's as if arguments had a slice() method, and we called arguments.slice() to get a copy of it (as an array).
[].slice(arguments) is just calling Array::slice() on an empty array, with arguments as the begin parameter, which makes no sense since begin (if present) should be a number.

arguments vs Array.prototype.slice.call(arguments,0)

What is the difference between using arguments and Array.prototype.slice.call(arguments,0) in a function?
I don't see there is any much difference between both, so How would I know when I am supposed to use which one?
function arr(){
return arguments; // or return Array.prototype.slice.call(arguments,0);
}
arr([1,2,3],[4,5,6]);
The difference is that arguments is an "array-like" object, not an array.
You can convert the arguments object to a real array by slicing it, like so
Array.prototype.slice.call(arguments, 0);
This gives you an array, with array properties like forEach, pop etc. which objects like arguments don't have (except length, which arguments do have).
It is generally (almost) never a good idea to slice the arguments object, MDN gives the warning
You should not slice on arguments because it prevents optimizations in
JavaScript engines (V8 for example). Instead, try constructing a new
array by iterating through the arguments object.
Also there should be no real need to pass arguments to a function, only to return them.
The arguments object is not a real array. It is a special type of object and does not have any Array properties except "length".
To make an array from the arguments object, use Array.prototype.slice.call(arguments, 0);
arguments variable is special kind of Object, and is not Array. So, you can't use .forEach, .map, '.push' and other array functions with it.
You have to convert arguments to Array and then you can work with value as array
function test(){
console.log(arguments.forEach); // undefined
var argsArray = Array.prototype.slice.call(arguments,0);
console.log(argsArray.forEach); // function
}
test();

Why can't I use Array.join.call in place of Array.prototype.join.call

function test()
{
alert(Array.join.call(arguments,'/')) //alerts /
alert(Array.prototype.join.call(arguments,'/')) //alerts Js/JScript
alert(Array.join(arguments,'/')) //alerts Js/JScript
}
test('Js','JScript');
Why is this difference? Why is it needed to reference prototype first ?
Also why does just Array.join gives required result even when join expects just a separator argument.
Array.join is a global function. When using call, what you pass as a first argument is the this object inside the body of the join function, then the arguments for the join function.
js> Array.join.call(null, [1, 2], "/")
"1/2"
Array.prototype.join is for instances of Array. Therefore, it expects this to be the actual array, which is why your second example works. Your second example amounts to calling Array.prototype.join with the this object being arguments, which is exactly arguments.join("/"). See MDN for an explanation.
This is necessary because the Arguments array isn't actually a real Array Object.. The specification refers to it as 'array-like', but it doesn't contain any of the methods usually associated with JavaScript Arrays, such as join.
Therefore what the above code is doing is calling the Array methods directly, using call, and passing the Arguments object as the scope of the method.
Essentially it causes the interpreter to treat the Arguments array as a real Array so that those methods can be executed on it.

Categories