Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Usual" functions vs function variables in JavaScript [duplicate]

Tags:

Is there any difference between

function MyFunc() {     // code... } 

and

var MyFunc = function() {     // code... }; 

in JavaScript?

like image 748
altso Avatar asked Aug 26 '09 10:08

altso


People also ask

What is the difference between functions and variables in JavaScript?

A variable is something, which stores data. A function is a bunch of code, which can be executed, if you call.

Are functions reusable in JavaScript?

Javascript functions are an important part of the Javascript standard. They allow you to create reusable blocks of code with specific names and behaviors so you don't have to repeat the same thing multiple times, which is extremely helpful for code readability and maintenance.

What is the difference between function declaration and function expression?

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.

Can a function and a variable have the same name JavaScript?

Variables and functions share the same namespace in JavaScript, so they override each other. if function name and variable name are same then JS Engine ignores the variable. With var a you create a new variable. The declaration is actually hoisted to the start of the current scope (before the function definition).


2 Answers

I know that a difference between them is that named functions work everywhere regardless you declare them, functions in variables don't.

a();//works    function a(){..} 

works

a();//error var a=function(){..} 

doesn't work but if you call it after the declaration it works

var a=function(){..} a();//works 
like image 90
mck89 Avatar answered Oct 22 '22 05:10

mck89


This article might answer your question : JavaScript function declaration ambiguity.

Only the first one is an actual function declaration, whereas the shorthand method is just a regular variable declaration with an anonymous function assigned to it as its value.

(look at the comments, too, which might get some useful informations too)

like image 42
Pascal MARTIN Avatar answered Oct 22 '22 05:10

Pascal MARTIN