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

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.

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 is the technical definition of a Javascript iterable and how do you test for it?

I've been implementing a useful subclass of the ES6 Set object. For many of my new methods, I want to accept an argument that can be either another Set or an Array, or really anything that I can iterate. I've been calling that an "iterable" in my interface and just use .forEach() on it (which works fine for a Set or an Array. Example code:
// remove items in this set that are in the otherIterable
// returns a count of number of items removed
remove(otherIterable) {
let cnt = 0;
otherIterable.forEach(item => {
if (this.delete(item)) {
++cnt;
}
});
return cnt;
}
Or
// add all items from some other iterable to this set
addTo(iterable) {
iterable.forEach(item => {
this.add(item);
});
}
But, I suspect I may be not really supporting any iterable in the way that ES6 defines it so I'm interested in what the real definition of a Javascript iterable is using the term as the ES6 specification does?
How do you test for it in ES6 Javascript?
How should you iterate a generic iterable?
I've found phrases like this in the ES6 specification:
If the parameter iterable is present, it is expected to be an object
that implements an ##iterator method that returns an iterator object
that produces a two element array-like object whose first element is a
value that will be used as a WeakMap key and whose second element is
the value to associate with that key.
But, that refers to an ##iterator method which I don't seem to be able to access via that property name.
What is the real definition of a Javascript iterable using the term as the ES6 specification does?
§25.1.1.1 defines "The Iterable Interface".
They're objects with a Symbol.iterator-keyed method that returns a valid Iterator (which in turn is an object expected to behave as it should according to §25.1.1.2).
How do you test for it in ES6 Javascript?
We cannot test what the ##iterator method returns without calling it, and we cannot test whether the result conforms to the Iterator interface without trying to run it. The best bet would be to do
function looksIterable(o) {
return typeof o[Symbol.iterator] == "function";
}
however I wouldn't usually test for this but simply let it fail with an exception when it's not iterable.
How should you iterate a generic iterable?
Don't use forEach. (In fact, never use forEach anywhere in ES6).
The proper way to iterate is a for (… of …) loop. It does all the checking for iterability (using the abstract GetIterator operation and running (and even closing) the iterator, and throws appropriate TypeErrors when used on non-iterable values.
There's a special property on the Symbol constructor, Symbol.iterator, whose value is that, uhh, I guess you'd say "conceptual" property name "##iterator". So you can create an iterator method for an object like this:
object[Symbol.iterator] = function* () {
// do something that makes sense
};
You can also test to see if some object is an iterator by doing
if (Symbol.iterator in object)
(and maybe also checking to see if it's a function). Now those iterator functions (the value of the Symbol.iterator property) are generator functions (not the * that I edited into the example). Thus you start them and get values by first calling the function and saving the returned object, and then calling .next(). That'll get you an object with value and done properties.
You can alternatively let for ... of or the "spread" ... operator worry about the iterator function.

Array of Objects - Select Subset of Array Where Obj.Prop IN Array of Values

I have an array of objects. For example's sake, let's say these objects have an id and a name:
var myObjectArray = [{id:1, name:'objOne'}, {id:2, name:'objTwo'}];
I would like to select a subset of this array, only containing objects where object id is in a an array of acceptable ids. So like this:
var subsetArray = _.where(myObjectArray , {id:1});
Except instead of the obj.id=1 condition, I want to say object id is IN [3,4,5]
Is there a clean way to do this? (anything like lodash, underscore, or raw javascript work). Or do I forget underscore/lodash/etc adn just iterate through every element?
You can do this in vanilla JS with filter and indexOf.
var results = myObjectArray.filter(o => ~[3,4,5].indexOf(o.id));
filter accepts a callback, which gets called with each item in the array. If the callback returns true, it includes that item and not if otherwise.
indexOf accepts a value and looks for the zero-based index of the value in the array if it exists in the array, or -1 if otherwise.
~ is a bitwise operator that turns -1 to 0 (among the other things it does), making -1 a falsy value for use in our filter callback.
In the above example, filter is accepting a callback in the form of an arrow function. To the left of => is o, which is the value from the array at each iteration. To the right of => is an expression. Arrow allow implicit return of the expression value. Parens are also optional for single-valued arrow functions.
A more verbose equivalent would be:
var results = myObjectArray.filter(function(o){
return [3,4,5].indexOf(o.id) !== -1;
});

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 does slice not work directly on arguments? [duplicate]

This question already has answers here:
How to get a slice from "arguments"
(9 answers)
Closed 9 years ago.
Tested it out on this fiddle after looking at underscore.
This seems like a hack to call slice on arguments when it is not on the prototype chain.
Why is it not on the prototype chain when it obviously works on arguments.
var slice = Array.prototype.slice;
function test () {
return slice.call(arguments,1);
// return arguments.slice(1)
}
var foo = test(1,2,3,4);
_.each(foo, function(val){
console.log(val)
});
>>> Object.prototype.toString.call(arguments)
<<< "[object Arguments]"
>>> Array.isArray(arguments) //is not an array
<<< false
>>> arguments instanceof Array //does not inherit from the Array prototype either
<<< false
arguments is not an Array object, that is, it does not inherit from the Array prototype. However, it contains an array-like structure (numeric keys and a length property), thus Array.prototype.slice can be applied to it. This is called duck typing.
Oh and of course, Array.prototype.slice always returns an array, hence it can be used to convert array-like objects / collections to a new Array. (ref: MDN Array slice method - Array-like objects)
arguments is not a "real" array.
The arguments object is a local variable available within all
functions; arguments as a property of Function can no longer be used.
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.
You could do:
var args = Array.prototype.slice.call(arguments);
Arguments is not an Array. It's an Arguments object.
Fortunately, slice only requires an Array-like object, and since Arguments has length and numerically-indexed properties, slice.call(arguments) still works.
It is a hack, but it's safe everywhere.
Referring to MDN: »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:«
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments
In order to call slice, you have to get the slicefunction, from the Array-prototype.

Categories