Q:

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!

A:

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);

