Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why JavaScript function declaration (and expression)?

Tags:

javascript

I've seen others using the following pattern.

var bar = function foo(){};
console.log(bar); // foo()
console.log(foo); // ReferenceError: foo is not defined

But why? I can see the point if both were declared, but they're not. Why is the reason?

like image 260
98374598347934875 Avatar asked Mar 12 '12 12:03

98374598347934875


People also ask

Why do we need JavaScript function expressions?

Function Expression allows us to create an anonymous function which doesn't have any function name which is the main difference between Function Expression and Function Declaration. A function expression can be used as an IIFE (Immediately Invoked Function Expression)which runs as soon as it is defined.

What is function expression and function declaration in JavaScript?

The main difference between a function expression and a function declaration is the function name, which can be omitted in function expressions to create anonymous functions. A function expression can be used as an IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined.

What is declaration and expression?

Declarations are loaded before any code can run. function foo() { return 5; } Function declarations load before any code is executed while Function expressions load only when the interpreter reaches that line of code. Similar to the var statement, function declarations are hoisted to the top of other code.

Why is a function call an expression in JavaScript?

A function call expression is used to execute a specified function with the provided arguments. If the function being called is overloaded, the compiler will attempt to match the argument types with the function parameter types. If there are no matching function declarations, a compile-time error will be raised.


1 Answers

As mentioned by others, using the first form in your example (a named function expression) can help with debugging, although with the recent improvements in built-in developer tools in browsers, this argument is becoming less persuasive. The other reason for using a named function expression is that you can use the function name as a variable within the body of the function rather than the now-deprecated in ES5 arguments.callee.

However, named function expressions are incorrectly and problematically implemented in Internet Explorer < 9 and should generally be avoided when you're targeting those browsers. See Juriy Zaytsev's excellent article on the subject for more information.

like image 166
Tim Down Avatar answered Oct 24 '22 07:10

Tim Down