Is there any difference between
function MyFunc() { // code... }
and
var MyFunc = function() { // code... };
in JavaScript?
A variable is something, which stores data. A function is a bunch of code, which can be executed, if you call.
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.
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.
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).
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With