4

I'm a total newbie in js, so please be gentle with me :)

I want to understand where can we use the dot operator on some variable (in this case - an array), and when we cannot. consider the following code:

//example 1
function f1(x) {
    return x*x;
}
console.log(map(f1, [1,2,3,4,5]));
console.log([1,2,3,4,5].map(f1));

//example 2
function f2(arr) {
    return arr;
}
console.log(f2([1,2,3,4,5]));
console.log([1,2,3,4,5].f2());

I know the examples are rather different, but still - in example 1 both prints work (and print the same) - even when using the array.function(..) syntax, while in example 2 the second print raises an error. basically, what is the difference between the two, and why does it work only in example 1?

and generally - can I apply this method over different variable types (numbers, booleans, etc.)?

GG.
  • 21,083
  • 14
  • 84
  • 130
noamgot
  • 3,962
  • 4
  • 24
  • 44
  • To complete other answers: https://stackoverflow.com/questions/948358/adding-custom-functions-into-array-prototype – GG. Jan 24 '17 at 15:33

3 Answers3

3

In the first example your are using the Array.prototype.map() function.

This function can be called in 2 different ways (See the docs)

[1,2,3].map(function(x){ ... }): //In your case the callback function is *f1()*

OR

arr.map(callback, [1,2,3]);

The second example is not working because the class Array has not function called f2()

Weedoze
  • 13,683
  • 1
  • 33
  • 63
1

[1,2,3,4,5] is an instance of Array "class", and that "class" has map method, that's why the following is a valid code:

[1,2,3,4,5].map(f1)

map method can accept any function as a parameter, and you're passing in your f1 function. It will be executed inside map function and it's executed as a standalone function.

Array "class" doesn't have f2 method, that's why this is invalid code:

[1,2,3,4,5].f2()

Here, f2 is executed immediately and is a part of [1,2,3,4,5] object

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
0

In the first case, map is defined as both a global function and public function of the Array. You can therefore call it via map(arr) or arr.map(..)

In the second case, as you only defined f2 as a global function which means the array can't access it.

Antony
  • 1,253
  • 11
  • 19