Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you use a function that is defined below its usage?

Tags:

javascript

I always thought that function a(){} is identical to a = function(){};

However, these two snippets behave differently:

a();
function a() {
  alert("Booya");
}

Prints Booya.

a();
a = function() {
  alert("Booya");
}

Fails with an exception, which makes sense, since a is really not defined when called.

So - what kind of 'magic' lets the first snippet work, even though a() is defined below its point of usage?

like image 347
ripper234 Avatar asked Oct 05 '11 10:10

ripper234


3 Answers

This is the difference between function declaration and function expression. This difference described well for example here.

like image 198
bjornd Avatar answered Oct 18 '22 20:10

bjornd


In JavaScript all the declarations are hoisted. Means the variable can be used before it has been declared and function can be used before its declared. It’s JavaScript’s default behaviour to move all the declarations at top of the current script.

But this feature may lead to bugs in application so we use strict mode directive to avoid bugs. Strict mode does not allow to use variables without declaration.

more info at here

like image 41
Tushar Girase Avatar answered Oct 18 '22 20:10

Tushar Girase


See this article for an explanation: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting

Function declarations and variable declarations are always moved ("hoisted") invisibly to the top of their containing scope by the JavaScript interpreter.

like image 26
Daniel Brockman Avatar answered Oct 18 '22 19:10

Daniel Brockman