Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

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!

Answer*

Draft saved
Draft discarded
Cancel

lang-js

AltStyle によって変換されたページ (->オリジナル) /