0

In JavaScript I've discovered that a function can be declared after it is called but only if it is declared as a function not as a variable.

This works:

alerter('this is an alert');

function alerter(text) {
  alert(text);
}

But this doesn't

alerter('this is an alert');

var alerter = function(text) {
  alert(text);
}

Can someone explain to me why these are treated differently and maybe give a brief explanation of how JavaScript compiles.

Chris Starling
  • 305
  • 3
  • 15
  • First one is a function declaration, second one is function expression. Look for differences between them on SO. – kind user Feb 23 '17 at 16:08
  • Its called Function hoisting. All functions are moved to the top by the interpreter. The first one is a function, the second however is the value of a variable. Variables are not hoiseted. They can be set to many values throughout the life of a program. it could be a string, an object, etc. it could be one function at one point or another later. So hoisting them would not make sense. – PEWColina Feb 23 '17 at 16:16

0 Answers0