8

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?

5 Answers 5

7

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

Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

2

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.

Comments

0

No magic, proper coding is required. AFAIK

  • document is loaded and parsed, functions are 'loaded'. The the script is being executed. So far no problem _a() _ is found.
  • no function is 'maped'. The script si executed line by line. It tries to call a() and THEN assign function to a global variable a

Comments

-1

Functions are defined global. But if you assign a function to a variable, as you do in the second case, the scope rules for variables come into effect: You can not call the function before its variable was defined.

1 Comment

Functions are not defined global - they are defined within the current scope. Take function a() { function b() {} } for example: b() is not available outside the a()-context. It's not a question about global or not global it's a question between declaration stage and execution stage.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.