myaddresstoday
myaddresstoday

Reputation: 69

Javascript syntax with functions

I'm not sure what this means or how to word the question correctly.

In the first example I could put the variable before the function "numbers1.forEach(...)" but in the second example I could not "num.square()"?

function forEach(array, action) {
  for (var i = 0; i < array.length; i++)
    action(array[i]);
}

var numbers2 = [1, 2, 3, 4, 5], sum = 0;
forEach(numbers2, function(number) {
  sum += number;
});
console.log(sum);
// → 15

var numbers1 = [1, 2, 3, 4, 5], sum = 0;
numbers1.forEach(function(number) {
  sum += number;
});
console.log(sum);
// → 15
// this works!

But this does not work

var square = function(x) {
  return x * x;
};

var num = 12;
console.log(square(num));
// → 144

console.log(num.square());
// → TypeError: undefined is not a function (line 9)
// does not work?

Thanks!

Upvotes: 1

Views: 51

Answers (3)

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107606

Syntax-wise, there's no "magic" happening here. You're describing two very different things.

In your first example, you're passing an Array to your own defined forEach method. In the second example, the forEach you're calling is actually a built-in method on Arrays (see MDN). If you changed your forEach to not invoke action, you'll see that yours breaks and the second one still works.

You can achieve this functionality yourself. You could add a function to Number to make your second example work (although this is not a recommended practice, as it could collide with future JavaScript features [and many other reasons] or break existing functionality):

Number.prototype.square = function() {
      return this * this;
};

var num = 12;
var squared = num.square();

alert(squared);

Upvotes: 2

Andre Pena
Andre Pena

Reputation: 59446

The example with the array works because Array in JavaScript (ECMAScript5) defines a forEach function.

The example with the number doesn't work because Number doesn't define a square function. You can extend Number to include the square function like this:

Number.prototype.square = function(x) {
  return this * this;
};

Upvotes: 0

unobf
unobf

Reputation: 7254

If you remove the forEach function from your first example, it will still work, that is because the Array type has a builtin forEach function.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Alternatively try to change your forEach function to each and you will see that it will no longer work.

What you are trying to do is add a new method to an existing type. This is not good practice in JavaScript.

Upvotes: 0

Related Questions