- Coding Ground
- Corporate Training
- Trending Categories

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary

How can we assign a function to a variable in JavaScript?
In this tutorial, we will learn to assign a function to a variable in JavaScript. The function is the code block that we can reuse quickly, often just by making a function call. There are two ways to declare a function in JavaScript, one is a named function, and another is an anonymous function.
Most JavaScript programmers are familiar with the name function, and users can follow the below syntax to declare the named function.
In the above syntax, users can see that, we can create a function definition with the function keyword and following by function name.
Now, what if we want to assign the whole function to the variable as an expression? Here, we have 2 different ways to achieve our goal.
Creating the Anonymous Function
Creating the arrow function.
The anonymous function name suggests that we are declaring the function without its identity means its name.
It is the first way to assign the function to the variable.
Creating an anonymous function works as an expression and compiles when code execution reaches the function line, and the named function compiles at the start of the code execution.
Programmers can follow the below syntax to bind the anonymous function to the variable.
In the above syntax, users can see that we have assigned the expression of an anonymous function to the variable ‘a’. Furthermore, we can invoke the function using the variable ‘a’ and passed the parameters.
In the below example, we will create an anonymous function and assign it to the variable as an expression. After that, we will call the anonymous function using the variable. Also, we will learn to pass the parameters inside the anonymous function.
In the above output, users can see that it renders the result returned from the function call using variable ‘a’.
The second method to assign the function to the variable is the arrow function. It is similar to the above approach, but the difference is that we will create an anonymous function without using the ‘ function ’ keyword and use an arrow instead.
The arrow function is the shortest syntax to declare the function in JavaScript, and it makes programmers' tasks easy to write the function. It is the latest version of the anonymous function as introduced in the ES6 .
Programmers can create a single variable using the var, let, or const keywords and assign the function expression to that. However, creating a variable with the const keyword is recommended to assign the function as the function expression always remains constant.
Users can follow the below syntax to write the expression for the arrow function.
In the above syntax, users can see how we declared the arrow function expression without using the function keyword.
In the below example, we will create the arrow function with parameters. Also, we will assign it to the variable and invoke through the variable.
In the above output, users can see that it prints whatever result returns from the arrow function when we call it using the variable.
We have learned the two different ways to assign the function expression to the variable. The first approach is using the anonymous function, which is also possible in the ES5. In the ES6, the arrow function was introduced to create an anonymous function and assign it to the variable.
It is recommended to use the arrow function as it is the shorter version of the anonymous function.

0 Followers
- Related Articles
- Can we assign a reference to a variable in Python?
- How can we assign a bit value as a number to a user variable?
- How to assign a PHP variable to JavaScript?
- How can we use SET statement to assign a SELECT result to a MySQL user variable?
- How to assign a reference to a variable in C#
- How to define global variable in a JavaScript function?
- How can I check if a JavaScript variable is function type?
- How to assign multiple values to a same variable in Python?
- How do I assign a dictionary value to a variable in Python?
- Can we assign new property to an object using deconstruction in JavaScript?
- How can we use a JavaScript function as an object?
- How to execute a JavaScript function using its name in a variable?
- How to assign the result of a MySQL query into a variable?
- How to load a JavaScript function using the variable name?
- How can we store a value in user-defined variable?

- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
var functionName = function() {} vs function functionName() {}
I've recently started maintaining someone else's JavaScript code. I'm fixing bugs, adding features and also trying to tidy up the code and make it more consistent.
The previous developer used two ways of declaring functions and I can't work out if there is a reason behind it or not.
The two ways are:
What are the reasons for using these two different methods and what are the pros and cons of each? Is there anything that can be done with one method that can't be done with the other?
41 Answers 41
The difference is that functionOne is a function expression and so only defined when that line is reached, whereas functionTwo is a function declaration and is defined as soon as its surrounding function or script is executed (due to hoisting ).
For example, a function expression:
// TypeError: functionOne is not a function functionOne(); var functionOne = function() { console.log("Hello!"); };
And, a function declaration:
// Outputs: "Hello!" functionTwo(); function functionTwo() { console.log("Hello!"); }
Historically, function declarations defined within blocks were handled inconsistently between browsers. Strict mode (introduced in ES5) resolved this by scoping function declarations to their enclosing block.
'use strict'; { // note this block! function functionThree() { console.log("Hello!"); } } functionThree(); // ReferenceError

- Function definitions are executed when code enters the surrounding block, rather than when it enters the enclosing function. I don't know if things always worked that way, but it would be unavoidable if a block used let or const to define a variable that was closed over by a function within it, and applying that rule consistently is probably better than applying it only when unavoidable. – supercat Oct 26, 2020 at 21:37
- 37 The sentence "due to hoisting" might give a wrong impression that only the named function gets hoisted. In fact, both var functionOne as well as function functionTwo get hoisted to some degree - it's just that functionOne is set to undefined (you could call it half-hoisting, variables always get hoisted only to that degree) whereas function functionTwo is fully hoisted in that it's defined and declared. Invoking something that's undefined will of course then throw a typeError. – rails_has_elegance Dec 4, 2020 at 19:19
- 3 There is also a slight variation of var case, when one uses let functionFour = function () {...} . In this case declaration of let functionFour is hoisted. But it does not get initialized, not even with an undefined value. So it produces a slightly different error: Uncaught ReferenceError: Cannot access 'functionFour' before initialization The same holds for const . – Pavlo Maistrenko Jan 5, 2022 at 15:11
- @rails_has_elegance so what's the point of calling it "half hoisted" if it acts exactly the same as "not hoisted at all"? – vanowm Apr 2, 2022 at 19:57
- 2 @vanowm it doesn't act the same as "not hoisted at all" though. If it wasn't hoisted you'd get a ReferenceError. Since it's hoisted you get a TypeError. Compare these two statements in a console: 1. hoisted(); var hoisted = function() {} 2. notHoisted(); const notHoisted = function() {}. In the first case, it's a TypeError because you're trying to invoke undefined (it DID get hoisted though, that's why it's at least undefined, which is still more than nothing at all). In the second case, it's not even undefined, you just get a plain ReferenceError. – rails_has_elegance Apr 14, 2022 at 14:12
First I want to correct Greg: function abc(){} is scoped too — the name abc is defined in the scope where this definition is encountered. Example:
Secondly, it is possible to combine both styles:
xyz is going to be defined as usual, abc is undefined in all browsers but Internet Explorer — do not rely on it being defined. But it will be defined inside its body:
If you want to alias functions on all browsers, use this kind of declaration:
In this case, both xyz and abc are aliases of the same object:
One compelling reason to use the combined style is the "name" attribute of function objects ( not supported by Internet Explorer ). Basically when you define a function like
its name is automatically assigned. But when you define it like
its name is empty — we created an anonymous function and assigned it to some variable.
Another good reason to use the combined style is to use a short internal name to refer to itself, while providing a long non-conflicting name for external users:
In the example above we can do the same with an external name, but it'll be too unwieldy (and slower).
(Another way to refer to itself is to use arguments.callee , which is still relatively long, and not supported in the strict mode.)
Deep down, JavaScript treats both statements differently. This is a function declaration:
abc here is defined everywhere in the current scope:
Also, it hoisted through a return statement:
This is a function expression:
xyz here is defined from the point of assignment:
Function declaration vs. function expression is the real reason why there is a difference demonstrated by Greg.
Personally, I prefer the "function expression" declaration because this way I can control the visibility. When I define the function like
I know that I defined the function locally. When I define the function like
I know that I defined it globally providing that I didn't define abc anywhere in the chain of scopes. This style of definition is resilient even when used inside eval() . While the definition
depends on the context and may leave you guessing where it is actually defined, especially in the case of eval() — the answer is: It depends on the browser.

- var abc = function(){}; console.log(abc.name); // "abc" // from 2021 – lfx_cool Apr 3, 2021 at 16:27
- 3 Apparently, the JS runtime became smarter. Yet wrap it up and: var abc = (() => function(){})(); console.log(abc.name); // nothing – Eugene Lazutkin Apr 15, 2021 at 1:17
- @EugeneLazutkin you are executing the function and trying to read the name of the result. Remove the '();' part and yours example will e correct ;) – ikirachen Oct 7, 2021 at 16:51
- @EugeneLazutkin you are defining a function and immediately invoking (calling) it, also called an IIFE (Immediately Invoked Function Expression), which is one method of implementing lexical scoping (nothing from inside the IIFE will be accessible outside of it). So the value of abc is not the function itself but rather that function's return value. It makes sense for abc.name to be empty, because abc returns an unnamed function. @ikirachen mentioned removing the () because that is what is invoking the function. Without that, it's just wrapped in superfluous parentheses. – Sinjai Nov 16, 2021 at 23:43
- 1 To be clear, it's a way to implement tighter scoping in that variables declared within those parentheses using var will be function-scoped as usual, but that anonymous function is no longer accessible outside of the parentheses it's wrapped in. Thankfully these days we have let , which uses the block scoping the average (sane) person would expect. It's best to pretend var doesn't exist, in my opinion. – Sinjai Nov 16, 2021 at 23:48
Here's the rundown on the standard forms that create functions: (Originally written for another question, but adapted after being moved into the canonical question.)
- ES5 : ECMAScript 5th edition , 2009
- ES2015 : ECMAScript 2015 (also known as "ES6")
The quick list:
Function Declaration
"Anonymous" function Expression (which despite the term, sometimes create functions with names)
Named function Expression
Accessor function initializer (es5+).
Arrow Function Expression (ES2015+) (which, like anonymous function expressions, don't involve an explicit name, and yet can create functions with names)
Method Declaration in Object Initializer (ES2015+)
Constructor and method declarations in class (es2015+).
The first form is a function declaration , which looks like this:
A function declaration is a declaration ; it's not a statement or expression. As such, you don't follow it with a ; (although doing so is harmless).
A function declaration is processed when execution enters the context in which it appears, before any step-by-step code is executed. The function it creates is given a proper name ( x in the example above), and that name is put in the scope in which the declaration appears.
Because it's processed before any step-by-step code in the same context, you can do things like this:
Until ES2015, the spec didn't cover what a JavaScript engine should do if you put a function declaration inside a control structure like try , if , switch , while , etc., like this:
And since they're processed before step-by-step code is run, it's tricky to know what to do when they're in a control structure.
Although doing this wasn't specified until ES2015, it was an allowable extension to support function declarations in blocks. Unfortunately (and inevitably), different engines did different things.
As of ES2015, the specification says what to do. In fact, it gives three separate things to do:
- If in loose mode not on a web browser, the JavaScript engine is supposed to do one thing
- If in loose mode on a web browser, the JavaScript engine is supposed to do something else
- If in strict mode (browser or not), the JavaScript engine is supposed to do yet another thing
The rules for the loose modes are tricky, but in strict mode, function declarations in blocks are easy: They're local to the block (they have block scope , which is also new in ES2015), and they're hoisted to the top of the block. So:
"Anonymous" function Expression
The second common form is called an anonymous function expression :
Like all expressions, it's evaluated when it's reached in the step-by-step execution of the code.
In ES5, the function this creates has no name (it's anonymous). In ES2015, the function is assigned a name if possible by inferring it from context. In the example above, the name would be y . Something similar is done when the function is the value of a property initializer. (For details on when this happens and the rules, search for SetFunctionName in the the specification — it appears all over the place.)
The third form is a named function expression ("NFE"):
The function this creates has a proper name ( w in this case). Like all expressions, this is evaluated when it's reached in the step-by-step execution of the code. The name of the function is not added to the scope in which the expression appears; the name is in scope within the function itself:
Note that NFEs have frequently been a source of bugs for JavaScript implementations. IE8 and earlier, for instance, handle NFEs completely incorrectly , creating two different functions at two different times. Early versions of Safari had issues as well. The good news is that current versions of browsers (IE9 and up, current Safari) don't have those issues any more. (But as of this writing, sadly, IE8 remains in widespread use, and so using NFEs with code for the web in general is still problematic.)
Sometimes functions can sneak in largely unnoticed; that's the case with accessor functions . Here's an example:
Note that when I used the function, I didn't use () ! That's because it's an accessor function for a property. We get and set the property in the normal way, but behind the scenes, the function is called.
You can also create accessor functions with Object.defineProperty , Object.defineProperties , and the lesser-known second argument to Object.create .
Arrow Function Expression (ES2015+)
ES2015 brings us the arrow function . Here's one example:
See that n => n * 2 thing hiding in the map() call? That's a function.
A couple of things about arrow functions:
They don't have their own this . Instead, they close over the this of the context where they're defined. (They also close over arguments and, where relevant, super .) This means that the this within them is the same as the this where they're created, and cannot be changed.
As you'll have noticed with the above, you don't use the keyword function ; instead, you use => .
The n => n * 2 example above is one form of them. If you have multiple arguments to pass the function, you use parens:
(Remember that Array#map passes the entry as the first argument, and the index as the second.)
In both cases, the body of the function is just an expression; the function's return value will automatically be the result of that expression (you don't use an explicit return ).
If you're doing more than just a single expression, use {} and an explicit return (if you need to return a value), as normal:
The version without { ... } is called an arrow function with an expression body or concise body . (Also: A concise arrow function.) The one with { ... } defining the body is an arrow function with a function body . (Also: A verbose arrow function.)
ES2015 allows a shorter form of declaring a property that references a function called a method definition ; it looks like this:
the almost-equivalent in ES5 and earlier would be:
the difference (other than verbosity) is that a method can use super , but a function cannot. So for instance, if you had an object that defined (say) valueOf using method syntax, it could use super.valueOf() to get the value Object.prototype.valueOf would have returned (before presumably doing something else with it), whereas the ES5 version would have to do Object.prototype.valueOf.call(this) instead.
That also means that the method has a reference to the object it was defined on, so if that object is temporary (for instance, you're passing it into Object.assign as one of the source objects), method syntax could mean that the object is retained in memory when otherwise it could have been garbage collected (if the JavaScript engine doesn't detect that situation and handle it if none of the methods uses super ).
ES2015 brings us class syntax, including declared constructors and methods:
There are two function declarations above: One for the constructor, which gets the name Person , and one for getFullName , which is a function assigned to Person.prototype .

Speaking about the global context, both, the var statement and a FunctionDeclaration at the end will create a non-deleteable property on the global object, but the value of both can be overwritten .
The subtle difference between the two ways is that when the Variable Instantiation process runs (before the actual code execution) all identifiers declared with var will be initialized with undefined , and the ones used by the FunctionDeclaration 's will be available since that moment, for example:
The assignment of the bar FunctionExpression takes place until runtime.
A global property created by a FunctionDeclaration can be overwritten without any problems just like a variable value, e.g.:
Another obvious difference between your two examples is that the first function doesn't have a name, but the second has it, which can be really useful when debugging (i.e. inspecting a call stack).
About your edited first example ( foo = function() { alert('hello!'); }; ), it is an undeclared assignment, I would highly encourage you to always use the var keyword.
With an assignment, without the var statement, if the referenced identifier is not found in the scope chain, it will become a deleteable property of the global object.
Also, undeclared assignments throw a ReferenceError on ECMAScript 5 under Strict Mode .
A must read:
- Named function expressions demystified
Note : This answer has been merged from another question , in which the major doubt and misconception from the OP was that identifiers declared with a FunctionDeclaration , couldn't be overwritten which is not the case.
The two code snippets you've posted there will, for almost all purposes, behave the same way.
However, the difference in behaviour is that with the first variant ( var functionOne = function() {} ), that function can only be called after that point in the code.
With the second variant ( function functionTwo() ), the function is available to code that runs above where the function is declared.
This is because with the first variant, the function is assigned to the variable foo at run time. In the second, the function is assigned to that identifier, foo , at parse time.
More technical information
JavaScript has three ways of defining functions.
- Your first snippet shows a function expression . This involves using the "function" operator to create a function - the result of that operator can be stored in any variable or object property. The function expression is powerful that way. The function expression is often called an "anonymous function", because it does not have to have a name,
- Your second example is a function declaration . This uses the "function" statement to create a function. The function is made available at parse time and can be called anywhere in that scope. You can still store it in a variable or object property later.
- The third way of defining a function is the "Function()" constructor , which is not shown in your original post. It's not recommended to use this as it works the same way as eval() , which has its problems.

A better explanation to Greg's answer
Why no error? We were always taught that expressions are executed from top to bottom(??)
Function declarations and variable declarations are always moved ( hoisted ) invisibly to the top of their containing scope by the JavaScript interpreter. Function parameters and language-defined names are, obviously, already there. ben cherry
This means that code like this:
Notice that the assignment portion of the declarations were not hoisted. Only the name is hoisted.
But in the case with function declarations, the entire function body will be hoisted as well :

Other commenters have already covered the semantic difference of the two variants above. I wanted to note a stylistic difference: Only the "assignment" variation can set a property of another object.
I often build JavaScript modules with a pattern like this:
With this pattern, your public functions will all use assignment, while your private functions use declaration.
(Note also that assignment should require a semicolon after the statement, while declaration prohibits it.)

An illustration of when to prefer the first method to the second one is when you need to avoid overriding a function's previous definitions.
, this definition of myfunction will override any previous definition, since it will be done at parse-time.
does the correct job of defining myfunction only when condition is met.

An important reason is to add one and only one variable as the "Root" of your namespace...
There are many techniques for namespacing. It's become more important with the plethora of JavaScript modules available.
Also see How do I declare a namespace in JavaScript?
Hoisting is the JavaScript interpreter’s action of moving all variable and function declarations to the top of the current scope.
However, only the actual declarations are hoisted. by leaving assignments where they are.
- variable's/Function's declared inside the page are global can access anywhere in that page.
- variable's/Functions declared inside the function are having local scope. means they are available/accessed inside the function body (scope), they are not available outside the function body.
Javascript is called loosely typed language. Which means Javascript variables can hold value of any Data-Type . Javascript automatically takes care of changing the variable-type based on the value/literal provided during runtime.
- functions declared inside the page are hoisted to top of the page having global access.
- functions declared inside the function-block are hoisted to top of the block.
Default return value of function is ' undefined ', Variable declaration default value also 'undefined'
Function Expression
Function assigned to variable Example:
javascript interpreted as
You can check function declaration, expression test over different browser's using jsperf Test Runner
ES5 Constructor Function Classes : Function objects created using Function.prototype.bind
JavaScript treats functions as first-class objects, so being an object, you can assign properties to a function.
ES6 introduced Arrow function : An arrow function expression has a shorter syntax, they are best suited for non-method functions, and they cannot be used as constructors.
ArrowFunction : ArrowParameters => ConciseBody . const fn = (item) => { return item & 1 ? 'Odd' : 'Even'; }; console.log( fn(2) ); // Even console.log( fn(3) ); // Odd

I'm adding my own answer just because everyone else has covered the hoisting part thoroughly.
I've wondered about which way is better for a long while now, and thanks to http://jsperf.com now I know :)

Function declarations are faster, and that's what really matters in web dev right? ;)

- see answer about performance below , different results – d9k Mar 1, 2021 at 17:19
𝗧𝗵𝗲𝗿𝗲 𝗮𝗿𝗲 𝗳𝗼𝘂𝗿 𝗻𝗼𝘁𝗲𝘄𝗼𝗿𝘁𝗵𝘆 𝗰𝗼𝗺𝗽𝗮𝗿𝗶𝘀𝗼𝗻𝘀 𝗯𝗲𝘁𝘄𝗲𝗲𝗻 𝘁𝗵𝗲 𝘁𝘄𝗼 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝘁 𝗱𝗲𝗰𝗹𝗮𝗿𝗮𝘁𝗶𝗼𝗻𝘀 𝗼𝗳 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 𝗮𝘀 𝗹𝗶𝘀𝘁𝗲𝗱 𝗯𝗲𝗹𝗼𝘄.
- Availability (scope) of the function
The following works because function add() is scoped to the nearest block:
try { console.log("Success: ", add(1, 1)); } catch(e) { console.log("ERROR: " + e); } function add(a, b){ return a + b; }
The following does not work because the variable is called before a function value is assigned to the variable add .
try { console.log("Success: ", add(1, 1)); } catch(e) { console.log("ERROR: " + e); } var add=function(a, b){ return a + b; }
The above code is identical in functionality to the code below. Note that explicitly assigning add = undefined is superfluous because simply doing var add; is the exact same as var add=undefined .
var add = undefined; try { console.log("Success: ", add(1, 1)); } catch(e) { console.log("ERROR: " + e); } add = function(a, b){ return a + b; }
The following does not work because var add= begins an expression and causes the following function add() to be an expression instead of a block. Named functions are only visible to themselves and their surrounding block. As function add() is an expression here, it has no surrounding block, so it is only visible to itself.
try { console.log("Success: ", add(1, 1)); } catch(e) { console.log("ERROR: " + e); } var add=function add(a, b){ return a + b; }
- (function) .name
The name of a function function thefuncname(){} is thefuncname when it is declared this way.
function foobar(a, b){} console.log(foobar.name);
var a = function foobar(){}; console.log(a.name);
Otherwise, if a function is declared as function(){} , the function .name is the first variable used to store the function.
var a = function(){}; var b = (function(){ return function(){} }); console.log(a.name); console.log(b.name);
If there are no variables set to the function, then the functions name is the empty string ( "" ).
console.log((function(){}).name === "");
Lastly, while the variable the function is assigned to initially sets the name, successive variables set to the function do not change the name.
var a = function(){}; var b = a; var c = b; console.log(a.name); console.log(b.name); console.log(c.name);
- Performance
In Google's V8 and Firefox's Spidermonkey there might be a few microsecond JIT compilation difference, but ultimately the result is the exact same. To prove this, let's examine the efficiency of JSPerf at micro-benchmarks by comparing the speed of two blank code snippets. The JSPerf tests are found here . And, the jsben.ch tests are found here . As you can see, there is a noticeable difference when there should be none. If you are really a performance freak like me, then it might be more worth your while trying to reduce the number of variables and functions in the scope and especially eliminating polymorphism (such as using the same variable to store two different types).
- Variable Mutability
When you use the var keyword to declare a variable, you can then reassign a different value to the variable like so.
(function(){ "use strict"; var foobar = function(){}; // initial value try { foobar = "Hello World!"; // new value console.log("[no error]"); } catch(error) { console.log("ERROR: " + error.message); } console.log(foobar, window.foobar); })();
However, when we use the const-statement, the variable reference becomes immutable. This means that we cannot assign a new value to the variable. Please note, however, that this does not make the contents of the variable immutable: if you do const arr = [] , then you can still do arr[10] = "example" . Only doing something like arr = "new value" or arr = [] would throw an error as seen below.
(function(){ "use strict"; const foobar = function(){}; // initial value try { foobar = "Hello World!"; // new value console.log("[no error]"); } catch(error) { console.log("ERROR: " + error.message); } console.log(foobar, window.foobar); })();
Interestingly, if we declare the variable as function funcName(){} , then the immutability of the variable is the same as declaring it with var .
(function(){ "use strict"; function foobar(){}; // initial value try { foobar = "Hello World!"; // new value console.log("[no error]"); } catch(error) { console.log("ERROR: " + error.message); } console.log(foobar, window.foobar); })();
𝗪𝗵𝗮𝘁 𝗜𝘀 𝗧𝗵𝗲 "𝗡𝗲𝗮𝗿𝗲𝘀𝘁 𝗕𝗹𝗼𝗰𝗸"
The "nearest block" is the nearest "function," (including asynchronous functions, generator functions, and asynchronous generator functions). However, interestingly, a function functionName() {} behaves like a var functionName = function() {} when in a non-closure block to items outside said closure. Observe.
- Normal var add=function(){}
try { // typeof will simply return "undefined" if the variable does not exist if (typeof add !== "undefined") { add(1, 1); // just to prove it console.log("Not a block"); }else if(add===undefined){ // this throws an exception if add doesn't exist console.log('Behaves like var add=function(a,b){return a+b}'); } } catch(e) { console.log("Is a block"); } var add=function(a, b){return a + b}
- Normal function add(){}
try { // typeof will simply return "undefined" if the variable does not exist if (typeof add !== "undefined") { add(1, 1); // just to prove it console.log("Not a block"); }else if(add===undefined){ // this throws an exception if add doesn't exist console.log('Behaves like var add=function(a,b){return a+b}') } } catch(e) { console.log("Is a block"); } function add(a, b){ return a + b; }
try { // typeof will simply return "undefined" if the variable does not exist if (typeof add !== "undefined") { add(1, 1); // just to prove it console.log("Not a block"); }else if(add===undefined){ // this throws an exception if add doesn't exist console.log('Behaves like var add=function(a,b){return a+b}') } } catch(e) { console.log("Is a block"); } (function () { function add(a, b){ return a + b; } })();
- Statement (such as if , else , for , while , try / catch / finally , switch , do / while , with )
try { // typeof will simply return "undefined" if the variable does not exist if (typeof add !== "undefined") { add(1, 1); // just to prove it console.log("Not a block"); }else if(add===undefined){ // this throws an exception if add doesn't exist console.log('Behaves like var add=function(a,b){return a+b}') } } catch(e) { console.log("Is a block"); } { function add(a, b){ return a + b; } }
- Arrow Function with var add=function()
try { // typeof will simply return "undefined" if the variable does not exist if (typeof add !== "undefined") { add(1, 1); // just to prove it console.log("Not a block"); }else if(add===undefined){ // this throws an exception if add doesn't exist console.log('Behaves like var add=function(a,b){return a+b}') } } catch(e) { console.log("Is a block"); } (() => { var add=function(a, b){ return a + b; } })();
- Arrow Function With function add()
try { // typeof will simply return "undefined" if the variable does not exist if (typeof add !== "undefined") { add(1, 1); // just to prove it console.log("Not a block"); }else if(add===undefined){ // this throws an exception if add doesn't exist console.log('Behaves like var add=function(a,b){return a+b}') } } catch(e) { console.log("Is a block"); } (() => { function add(a, b){ return a + b; } })();

A function declaration and a function expression assigned to a variable behave the same once the binding is established.
There is a difference however at how and when the function object is actually associated with its variable. This difference is due to the mechanism called variable hoisting in JavaScript.
Basically, all function declarations and variable declarations are hoisted to the top of the function in which the declaration occurs (this is why we say that JavaScript has function scope ).
When a function declaration is hoisted, the function body "follows" so when the function body is evaluated, the variable will immediately be bound to a function object.
When a variable declaration is hoisted, the initialization does not follow, but is "left behind". The variable is initialized to undefined at the start of the function body, and will be assigned a value at its original location in the code. (Actually, it will be assigned a value at every location where a declaration of a variable with the same name occurs.)
The order of hoisting is also important: function declarations take precedence over variable declarations with the same name, and the last function declaration takes precedence over previous function declarations with the same name.
Some examples...
Variable foo is hoisted to the top of the function, initialized to undefined , so that !foo is true , so foo is assigned 10 . The foo outside of bar 's scope plays no role and is untouched.
Function declarations take precedence over variable declarations, and the last function declaration "sticks".
In this example a is initialized with the function object resulting from evaluating the second function declaration, and then is assigned 4 .
Here the function declaration is hoisted first, declaring and initializing variable a . Next, this variable is assigned 10 . In other words: the assignment does not assign to outer variable a .
The first example is a function declaration:
The second example is a function expression:
The main difference is how they are hoisted (lifted and declared). In the first example, the whole function declaration is hoisted. In the second example only the var 'abc' is hoisted, its value (the function) will be undefined, and the function itself remains at the position that it is declared.
To put it simply:
To study more about this topic I strongly recommend you this link
In terms of code maintenance cost, named functions are more preferable:
- Independent from the place where they are declared (but still limited by scope).
- More resistant to mistakes like conditional initialization (you are still able to override if wanted to).
- The code becomes more readable by allocating local functions separately of scope functionality. Usually in the scope the functionality goes first, followed by declarations of local functions.
- In a debugger you will clearly see the function name on the call stack instead of an "anonymous/evaluated" function.
I suspect more PROS for named functions are follow. And what is listed as an advantage of named functions is a disadvantage for anonymous ones.
Historically, anonymous functions appeared from the inability of JavaScript as a language to list members with named functions:
In computer science terms, we talk about anonymous functions and named functions. I think the most important difference is that an anonymous function is not bound to a name, hence the name anonymous function. In JavaScript it is a first class object dynamically declared at runtime.
For more information on anonymous functions and lambda calculus, Wikipedia is a good start: Anonymous Functions .
I use the variable approach in my code for a very specific reason, the theory of which has been covered in an abstract way above, but an example might help some people like me, with limited JavaScript expertise.
I have code that I need to run with 160 independently-designed brandings. Most of the code is in shared files, but branding-specific stuff is in a separate file, one for each branding.
Some brandings require specific functions, and some do not. Sometimes I have to add new functions to do new branding-specific things. I am happy to change the shared coded, but I don't want to have to change all 160 sets of branding files.
By using the variable syntax, I can declare the variable (a function pointer essentially) in the shared code and either assign a trivial stub function, or set to null.
The one or two brandings that need a specific implementation of the function can then define their version of the function and assign this to the variable if they want, and the rest do nothing. I can test for a null function before I execute it in the shared code.
From people's comments above, I gather it may be possible to redefine a static function too, but I think the variable solution is nice and clear.
Greg's Answer is good enough, but I still would like to add something to it that I learned just now watching Douglas Crockford's videos.
Function expression:
Function statement:
The function statement is just a shorthand for var statement with a function value.
Which expands further to:
And they are both hoisted to the top of the code.

@EugeneLazutkin gives an example where he names an assigned function to be able to use shortcut() as an internal reference to itself. John Resig gives another example - copying a recursive function assigned to another object in his Learning Advanced Javascript tutorial. While assigning functions to properties isn't strictly the question here, I recommend actively trying the tutorial out - run the code by clicking the button in the upper right corner, and double click the code to edit to your liking.
Examples from the tutorial: recursive calls in yell() :
Tests fail when the original ninja object is removed. (page 13)
function assert(predicate, message) { if(!predicate) { throw new Error(message); } } var ninja = { yell: function(n){ return n > 0 ? ninja.yell(n-1) + "a" : "hiy"; } }; assert( ninja.yell(4) == "hiyaaaa", "A single object isn't too bad, either." ); var samurai = { yell: ninja.yell }; var ninja = null; try { samurai.yell(4); } catch(e){ assert( false, "Uh, this isn't good! Where'd ninja.yell go?" ); }
If you name the function that will be called recursively, the tests will pass. (page 14)
function assert(predicate, message) { if(!predicate) { throw new Error(message); } } var ninja = { yell: function yell(n){ return n > 0 ? yell(n-1) + "a" : "hiy"; } }; assert( ninja.yell(4) == "hiyaaaa", "Works as we would expect it to!" ); var samurai = { yell: ninja.yell }; var ninja = {}; assert( samurai.yell(4) == "hiyaaaa", "The method correctly calls itself." ); console.log(samurai.yell(4));

Another difference that is not mentioned in the other answers is that if you use the anonymous function
and use that as a constructor as in
then one.constructor.name will not be defined. Function.name is non-standard but is supported by Firefox, Chrome, other Webkit-derived browsers and IE 9+.
it is possible to retrieve the name of the constructor as a string with two.constructor.name .
The first one (function doSomething(x)) should be part of an object notation.
The second one ( var doSomething = function(x){ alert(x);} ) is simply creating an anonymous function and assigning it to a variable, doSomething . So doSomething() will call the function.
You may want to know what a function declaration and function expression is.
A function declaration defines a named function variable without requiring variable assignment. Function declarations occur as standalone constructs and cannot be nested within non-function blocks.
ECMA 5 (13.0) defines the syntax as function Identifier ( FormalParameterList opt ) { FunctionBody }
In above condition the function name is visible within its scope and the scope of its parent (otherwise it would be unreachable).
And in a function expression
A function expression defines a function as a part of a larger expression syntax (typically a variable assignment ). Functions defined via functions expressions can be named or anonymous. Function expressions should not start with “function”.
ECMA 5 (13.0) defines the syntax as function Identifier opt ( FormalParameterList opt ) { FunctionBody }

I'm listing out the differences below:
A function declaration can be placed anywhere in the code. Even if it is invoked before the definition appears in code, it gets executed as function declaration is committed to memory or in a way it is hoisted up, before any other code in the page starts execution.
Take a look at the function below:
This is because, during execution, it looks like:-
A function expression, if not defined before calling it, will result in an error. Also, here the function definition itself is not moved to the top or committed to memory like in the function declarations. But the variable to which we assign the function gets hoisted up and undefined gets assigned to it.
Same function using function expressions:
This is because during execution, it looks like:
It is not safe to write function declarations in non-function blocks like if because they won't be accessible.
Named function expression like the one below, may not work in Internet Explorer browsers prior to version 9.

About performance:
New versions of V8 introduced several under-the-hood optimizations and so did SpiderMonkey .
There is almost no difference now between expression and declaration. Function expression appears to be faster now.

Anonymous function expressions appear to have better performance against Named function expression.

- The results differences are too small to be considered as a difference. If you'll run the test 100 times, you will get 100 results. – Ronny Sherer Oct 14, 2020 at 12:59
- @RonnySherer, are you familiar with jsperf? Tests were made after running more than 10 million times! – Panos Kalatzantonakis Oct 14, 2020 at 14:44
- Every measurement has disturbances. The computer it not in the same state and this is not the only process running on the computer. When the difference is so small, it means that you cannot rely on it and it is virtually the same. Try to run the sane test 10 times one after the other and you'll see that the numbers are different. Pretty close, but not the same. – Ronny Sherer Oct 17, 2020 at 21:30
- @RonnySherer js perf creates a virtual environment especially to account for processes with those small differences. It is not running on my computer. It runs only that. When something is so small maybe someone should not give a damn. BUT never the less I count it correctly and I report it. If someone wants to use it inside a loop with billions of iterations then he should pick the function with the best performance. – Panos Kalatzantonakis Oct 18, 2020 at 13:09
- The virtual environment is on a server which might do some other stuff. I did some tests. The results are never exactly the same. – Ronny Sherer Oct 21, 2020 at 14:54
If you would use those functions to create objects, you would get:
In JavaScript there are two ways to create functions:
Function declaration:
This is very basic, self-explanatory, used in many languages and standard across C family of languages. We declared a function defined it and executed it by calling it.
What you should be knowing is that functions are actually objects in JavaScript; internally we have created an object for above function and given it a name called fn or the reference to the object is stored in fn. Functions are objects in JavaScript; an instance of function is actually an object instance.
JavaScript has first-class functions, that is, create a function and assign it to a variable just like you create a string or number and assign it to a variable. Here, the fn variable is assigned to a function. The reason for this concept is functions are objects in JavaScript; fn is pointing to the object instance of the above function. We have initialized a function and assigned it to a variable. It's not executing the function and assigning the result.
Reference: JavaScript function declaration syntax: var fn = function() {} vs function fn() {}
Named Functions Vs. Anonymous Functions
The first function syntax is Anonymous Function Expression :
While, the second one is Function Declaration :
The main difference between both is the function name since Anonymous Functions have no name to call. Anonymous functions are quick and easy to declare, and many libraries and tools tend to encourage this idiomatic style of code. However, anonymous functions have some drawbacks :
Readability: anonymous functions omit a name which could cause less readable code.
Debugging: anonymous functions have no name in stack traces, which can make debugging more difficult.
Self-Reference: what if the function needs to refer to itself, for recursion for example.
Naming Function Expression
Providing a name for your function expression quite effectively addresses all these drawbacks, and has no tangible downsides. The best practice is to always name your function expressions:
Naming IIFEs (Immediate Invoked Function Expression)
For functions assigned to a variable, naming the function, in this case, is not very common and may cause confusion, in this case, the arrow function may be a better choice.

In light of the "named functions show up in stack traces" argument, modern JavaScript engines are actually quite capable of representing anonymous functions.
As of this writing, V8, SpiderMonkey, Chakra and Nitro always refer to named functions by their names. They almost always refer to an anonymous function by its identifier if it has one.
SpiderMonkey can figure out the name of an anonymous function returned from another function. The rest can't.
If you really, really wanted your iterator and success callbacks to show up in the trace, you could name those too...
But for the most part it's not worth stressing over.
Harness ( Fiddle )
Spidermonkey.

Both are different ways of defining a function. The difference is how the browser interprets and loads them into an execution context.
The first case is of function expressions which loads only when the interpreter reaches that line of code. So if you do it like the following, you will get an error that the functionOne is not a function .
The reason is that on the first line no value is assigned to functionOne, and hence it is undefined. We are trying to call it as a function, and hence we are getting an error.
On the second line we are assigning the reference of an anonymous function to functionOne.
The second case is of function declarations that loads before any code is executed. So if you do like the following you won't get any error as the declaration loads before code execution.

They are pretty similar with some small differences, first one is a variable which assigned to an anonymous function (Function Declaration) and second one is the normal way to create a function in JavaScript(Anonymous function Declaration), both has usage, cons and pros:
1. Function Expression
A Function Expression defines a function as a part of a larger expression syntax (typically a variable assignment ). Functions defined via Functions Expressions can be named or anonymous. Function Expressions must not start with “function” (hence the parentheses around the self invoking example below).
Assign a variable to a function, means no Hoisting, as we know functions in JavaScript can Hoist, means they can be called before they get declared, while variables need to be declared before getting access to them, so means in this case we can not access the function before where it's declared, also it could be a way that you write your functions, for the functions which return another function, this kind of declaration could make sense, also in ECMA6 & above you can assign this to an arrow function which can be used to call anonymous functions, also this way of declaring is a better way to create Constructor functions in JavaScript.
2. Function Declaration
A Function Declaration defines a named function variable without requiring variable assignment. Function Declarations occur as standalone constructs and cannot be nested within non-function blocks. It’s helpful to think of them as siblings of Variable Declarations. Just as Variable Declarations must start with “var”, Function Declarations must begin with “function”.
This is the normal way of calling a function in JavaScript, this function can be called before you even declare it as in JavaScript all functions get Hoisted, but if you have 'use strict' this won't Hoist as expected, it's a good way to call all normal functions which are not big in lines and neither are a constructor function.
Also, if you need more info about how hoisting works in JavaScript, visit the link below:
https://developer.mozilla.org/en-US/docs/Glossary/Hoisting
This is just two possible ways of declaring functions, and in the second way, you can use the function before declaration.

Not the answer you're looking for? Browse other questions tagged javascript function methods syntax or ask your own question .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
Hot Network Questions
- Short story taking place on a toroidal planet or moon involving flying
- If a law is new but its interpretation is vague, can the courts directly ask the drafters the intent and official interpretation of their law?
- Mathematica not solving this integral
- What can a lawyer do if the client wants him to be acquitted of everything despite serious evidence?
- Why are trials on "Law & Order" in the New York Supreme Court?
- Finite abelian groups with fewer automorphisms than a subgroup
- Chord III is rarely used, but Pachelbel's Canon in D has F#m
- Styling contours by colour and by line thickness in QGIS
- ncdu: What's going on with this second size column?
- Theoretically Correct vs Practical Notation
- Euler: “A baby on his lap, a cat on his back — that’s how he wrote his immortal works” (origin?)
- Largest Binary Area
- Checking system vs. SEPA and the like
- Is there a proper earth ground point in this switch box?
- Do new devs get fired if they can't solve a certain bug?
- How is Jesus "υἱὸς ὑψίστου κληθήσεται" (Luke 1:32 NAS28) different from a prophet (παιδίον, προφήτης ὑψίστου κληθήσῃ Luke 1:76 NAS28)?
- Transgenic Peach DNA Splicing
- Is it correct to use "the" before "materials used in making buildings are"?
- Movie with vikings/warriors fighting an alien that looks like a wolf with tentacles
- Time arrow with "current position" evolving with overlay number
- Why do small African island nations perform better than African continental nations, considering democracy and human development?
- Confusion About Entropy
- Did any DOS compatibility layers exist for any UNIX-like systems before DOS started to become outmoded?
- Knocking Out Zombies
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

How to Assign a Function to a Variable in JavaScript
This blog post will provide a JavaScript example of how to assign a function to a variable.
How to Assign a Function to a Variable in JavaScript?
There are two different types of functions in JavaScript, that will be used by assigning them to variables:
- Assign an anonymous function to a variable
- Assign an arrow function to a variable
Let’s see how to assign these function types to a variable.
Assign an Anonymous Function to a Variable
An “ anonymous ” function is the simplest type of function that can be assigned to a variable. As indicated by the name, the function will declare without the name.
Syntax Follow the given syntax for assigning an anonymous function to a variable:
Example 1: Assign an Anonymous Function to a Variable Without Parameter Create a variable “ sum ” and assign an anonymous function to it. In the function, create two variables “ a ” and “ b ” by assigning values “ 12 ” and “ 8 ” respectively, and finally, return the sum of two numbers “ a ” and “ b ”:
Call the function by a variable name “ sum ” with braces ” () ” that denotes the function:
The output displays “ 20 ” while calling the anonymous function assigned to a variable:

Example 2: Assign an Anonymous Function to a Variable With Parameter Here, assign an anonymous function to the variable with two parameters “ a ” and “ b ”. It will return the sum of two numbers that will be passed during the function call as an argument:
Call the anonymous function using variable “ sum ” by passing number “ 4 ” as a first argument “ a ” and “ 6 ” as the second argument “ b ”:
The corresponding output will be:

Assign an Arrow Function to a Variable
The “ arrow function ” is the second way to apply the function to the variable. The only difference between the arrow function and the anonymous function is that it will create without using the keyword “ function ” and instead use an arrow. The arrow function in JavaScript has the shortest syntax for function declaration.
Syntax Use the following syntax for assigning the arrow function to the variable:
Example 1: Assign an Arrow Function to a Variable Without Parameter Create a variable “ sum ” and assign an arrow function to it. In the function, create two variables “ a ” and “ b ” by assigning values “ 9 ” and “ 12 ” respectively, and lastly, return the sum of two numbers “ a ” and “ b ”:
Call the function by a variable name “ sum ”:
The output displays “ 21 ” while calling the arrow function without parameters assigned to a variable:

Example 2: Assign an Arrow Function to a Variable With Parameter Create an arrow function with variables “ a ” and “ b ” that will return the sum of two numbers. It is the same as the anonymous function with parameters but without the “ function ” keyword:
Invoke the arrow function using the variable name “ sum ”:

About the author

Farah Batool
I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.

6 Ways to Declare JavaScript Functions
A function is a parametric block of code defined once and called multiple times later. In JavaScript a function is composed and influenced by many components:
- JavaScript code that forms the function body
- The list of parameters
- The variables accessible from the lexical scope
- The returned value
- The context this when the function is invoked
- Named or an anonymous function
- The variable that holds the function object
- arguments object (or missing in an arrow function)
This post teaches you six approaches to declare JavaScript functions: the syntax, examples and common pitfalls. Moreover, you will understand when to use a specific function type in certain circumstances.
Before I go on, let me recommend something to you.
If you want to significantly improve your JavaScript knowledge, take the amazingly useful course "Modern JavaScript From The Beginning 2.0" by Brad Traversy. Use the coupon code "DMITRI" and get up to 20% discount!

Table of Contents
1.1 a regular function, 1.2 difference from function expression, 1.3 function declaration in conditionals, 2.1 named function expression, 2.2 favor named function expression, 3.1 computed property names and methods, 4.1 context transparency, 4.2 short callbacks, 5. generator function, 6. one more thing: new function, 7. at the end, which way is better, 1. function declaration.
A function declaration is made of function keyword, followed by an obligatory function name, a list of parameters in a pair of parenthesis (para1, ..., paramN) and a pair of curly braces {...} that delimits the body code.
An example of function declaration:
function isEven(num) {...} is a function declaration that defines isEven function, which determines if a number is even.
The function declaration creates a variable in the current scope with the identifier equal to the function name. This variable holds the function object.
The function variable is hoisted up to the top of the current scope, which means that the function can be invoked before the declaration (see this chapter for more details).
The created function is named , which means that the name property of the function object holds its name. It is useful when viewing the call stack: in debugging or error messages reading.
Let's see these properties in an example:
The function declaration function hello(name) {...} create a variable hello that is hoisted to the top of the current scope. hello variable holds the function object and hello.name contains the function name: 'hello' .
The function declaration matches for cases when a regular function is needed. Regular means that you declare the function once and later invoke it in many different places. This is the basic scenario:
Because the function declaration creates a variable in the current scope, alongside regular function calls, it is useful for recursion or detaching event listeners. Contrary to function expressions or arrow functions, that do not create a binding with the function variable by its name.
For example, to calculate recursively the factorial you have to access the function inside:
Inside factorial() a recursive call is being made using the variable that holds the function: factorial(n - 1) .
It is possible to use a function expression and assign it to a regular variable, e.g. const factorial = function(n) {...} . But the function declaration function factorial(n) is compact (no need for const and = ).
An important property of the function declaration is its hoisting mechanism. It allows using the function before the declaration in the same scope.
Hoisting is useful in some situations. For example, when you'd like to see how the function is called at the beginning of a script, without reading the function implementation. The function implementation can be located below in the file, so you may not even scroll there.
You can read more details about function declaration hoisting here .
It is easy to confuse the function declaration and function expression . They look very similar but produce functions with different properties.
An easy to remember rule: the function declaration in a statement always starts with the keyword function . Otherwise it's a function expression (see 2. ).
The following sample is a function declaration where the statement starts with function keyword:
In case of function expressions the JavaScript statement does not start with function keyword (it is present somewhere in the middle of the statement code):
Some JavaScript environments can throw a reference error when invoking a function whose declaration appears within blocks {...} of if , for or while statements. Let's enable the strict mode and see what happens when a function is declared in a conditional:
When calling ok() , JavaScript throws ReferenceError: ok is not defined , because the function declaration is inside a conditional block.
The function declaration in conditionals is allowed in non-strict mode, which makes it even more confusing.
As a general rule for these situations, when a function should be created by conditions - use a function expression. Let's see how it is possible:
Because the function is a regular object, assign it to a variable depending on the condition. Invoking ok() works fine, without errors.
2. Function expression
A function expression is determined by a function keyword, followed by an optional function name, a list of parameters in a pair of parenthesis (para1, ..., paramN) and a pair of curly braces { ... } that delimits the body code.
Some samples of the function expression:
The function expression creates a function object that can be used in different situations:
- Assigned to a variable as an object count = function(...) {...}
- Create a method on an object sum: function() {...}
- Use the function as a callback .reduce(function(...) {...})
The function expression is the working horse in JavaScript. Usually, you deal with this type of function declaration, alongside the arrow function (if you prefer short syntax and lexical context).
A function is anonymous when it does not have a name ( name property is an empty string '' ):
This is an anonymous function, which name is an empty string.
Sometimes the function name can be inferred. For example, when the anonymous is assigned to a variable:
The anonymous function name is 'myFunctionVar' , because myFunctionVar variable name is used to infer the function name.
When the expression has the name specified, this is a named function expression . It has some additional properties compared to simple function expression:
- A named function is created, i.e. name property holds the function name
- Inside the function body a variable with the same name holds the function object
Let's use the above example, but set a name in the function expression:
function funName(variable) {...} is a named function expression. The variable funName is accessible within function scope, but not outside. Either way, the property name of the function object holds the name: funName .
When a function expression const fun = function() {} is assigned to a variable, some engines infer the function name from this variable. However, callbacks might be passed as anonymous function expressions, without storing into variables: so the engine cannot determine its name .
It is reasonable to favor named functions and avoid anonymous ones to gain benefits like:
- The error messages and call stacks show more detailed information when using the function names
- More comfortable debugging by reducing the number of anonymous stack names
- The function name says what the function does
- You can access the function inside its scope for recursive calls or detaching event listeners
3. Shorthand method definition
Shorthand method definition can be used in a method declaration on object literals and ES2015 classes. You can define them using a function name, followed by a list of parameters in a pair of parenthesis (para1, ..., paramN) and a pair of curly braces { ... } that delimits the body statements.
The following example uses a shorthand method definition in an object literal:
add() and get() methods in collection object are defined using short method definition. These methods are called as usual: collection.add(...) and collection.get(...) .
The short approach of method definition has several benefits over traditional property definition with a name, colon : and a function expression add: function(...) {...} :
- A shorter syntax is easier to understand
- Shorthand method definition creates a named function, contrary to a function expression. It is useful for debugging.
The class syntax requires method declarations in a short form:
ECMAScript 2015 adds a nice feature: computed property names in object literals and classes. The computed properties use a slight different syntax [methodName]() {...} , so the method definition looks this way:
[addMethod](...) {...} and [getMethod](...) {...} are shorthand method declarations with computed property names.
4. Arrow function
An arrow function is defined using a pair of parenthesis that contains the list of parameters (param1, param2, ..., paramN) , followed by a fat arrow => and a pair of curly braces {...} that delimits the body statements.
When the arrow function has only one parameter, the pair of parentheses can be omitted. When it contains a single statement, the curly braces can be omitted too.
Let's see the arrow function basic usage:
absValue is an arrow function that calculates the absolute value of a number.
The function declared using a fat arrow has the following properties:
- The arrow function does not create its execution context, but takes it lexically (contrary to function expression or function declaration, which create own this depending on invocation)
- The arrow function is anonymous. However, the engine can infer its name from the variable holding the function.
- arguments object is not available in the arrow function (contrary to other declaration types that provide arguments object). You are free to use rest parameters (...params) , though.
this keyword is a confusing aspect of JavaScript (check this article for a detailed explanation on this ). Because functions create own execution context, often it is difficult to detect this value.
ECMAScript 2015 improves this usage by introducing the arrow function, which takes the context lexically (or simply uses this from the immediate outer scope). This is nice because you don't have to use .bind(this) or store the context var self = this when a function needs the enclosing context.
Let's see how this is inherited from the outer function:
Numbers class holds an array of numbers and provides a method addNumber() to insert new numbers. When addNumber() is called without arguments, a closure is returned that allows inserting numbers. This closure is an arrow function that has this as numbersObject instance because the context is taken lexically from addNumbers() method.
Without the arrow function, you have to manually fix the context. It means using workarounds like .bind() method:
or store the context into a separated variable var self = this :
The context transparency can be used when you want to keep this as is, taken from the enclosing context.
When creating an arrow function, the parenthesis pairs and curly braces are optional for a single parameter and single body statement. This helps in creating very short callback functions.
Let's make a function that finds if an array contains 0 :
item => item === 0 is an arrow function that looks straightforward.
Note that nested short arrow functions are difficult to read. The convenient way to use the shortest arrow function form is a single callback (without nesting).
If necessary, use the expanded syntax of arrow functions when writing nested arrow functions. It's just easier to read.
The generator function in JavaScript returns a Generator object . Its syntax is similar to function expression, function declaration or method declaration, just that it requires a star character * .
The generator function can be declared in the following forms:
a. Function declaration form function* <name>() :
b. Function expression form function* () :
c. Shorthand method definition form *<name>() :
In all 3 cases the generator function returns the generator object g . Later g is used to generate a series of incremented numbers.
In JavaScript functions are first-class objects - a function is a regular object of type function . The ways of the declaration described above create the same function object type. Let's see an example:
The function object type has a constructor: Function . When Function is invoked as a constructor new Function(arg1, arg2, ..., argN, bodyString) , a new function is created. The arguments arg1, args2, ..., argN passed to constructor become the parameter names for the new function and the last argument bodyString is used as the function body code.
Let's create a function that sums two numbers:
sumFunction created with Function constructor invocation has parameters numberA and numberB and the body return numberA + numberB .
The functions created this way don't have access to the current scope, thus closures cannot be created. They are always created in the global scope.
One possible application of new Function is a better way to access the global object in a browser or NodeJS script:
Remember that functions almost never should be declared using new Function() . Because the function body is evaluated on runtime, this approach inherits many eval() usage problems : security risks, harder debugging, no way to apply engine optimizations, no editor auto-complete.
There is no winner or loser. The decision which declaration type to choose depends on the situation.
There are some rules however that you may follow in common situations.
If the function uses this from the enclosing function, the arrow function is a good solution. When the callback function has one short statement, the arrow function is a good option too, because it creates short and light code.
For a shorter syntax when declaring methods on object literals, the shorthand method declaration is preferable.
new Function way to declare functions normally should not be used. Mainly because it opens potential security risks, doesn't allow code auto-complete in editors and loses the engine optimizations.
Do you prefer arrow functions or function expressions? Tell me why in a comment below!
Like the post? Please share!
Quality posts into your inbox.
I regularly publish posts containing:
- Important JavaScript concepts explained in simple words
- Overview of new JavaScript features
- How to use TypeScript and typing
- Software design and good coding practices
Subscribe to my newsletter to get them right into your inbox.

About Dmitri Pavlutin
Recommended reading:, when 'not' to use arrow functions, arrow functions shortening recipes in javascript, popular posts.
This forum is now read-only. Please use our new forums! Go to forums

assigning functions to variable
In this lesson, we all of a sudden are told we can create functions by just writing function ‘name’ (X)
What is the difference between this and var ‘name’ = function (x) Can you use this way of declaring functions for objects?
Answer 55d25737937676a0e4000247
This is an anonymous function expression:
We can assign this to a variable,
or we can assign it to a property of an object,
or we can write it has a handler (callback) in an event listener, (assume we have a button element with id=”click-me”),
We call it an expression because it is not a statement, and it needs a context or an assignment.
The declared function is a little different in that it is a complete statement right off the hop:
This form of function is immutable, meaning it cannot be changed. bar is carved in stone in memory and cannot be given a new assignment. foo above can be given a new assignment at any time.
To learn more about this, search, ‘function declaration vs function expression’ and keep an eye out for the term, ‘hoisting’ so you get an idea how that fits into this picture.
Aside: name is reserved word in JavaScript and we cannot use it in global window context, only inside a function or as an object property. Search name window context and you might find something about this.

Popular free courses
Learn javascript.
JS Tutorial
Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript function definitions.
JavaScript functions are defined with the function keyword.
You can use a function declaration or a function expression .
Function Declarations
Earlier in this tutorial, you learned that functions are declared with the following syntax:
Declared functions are not executed immediately. They are "saved for later use", and will be executed later, when they are invoked (called upon).
Semicolons are used to separate executable JavaScript statements. Since a function declaration is not an executable statement, it is not common to end it with a semicolon.
Function Expressions
A JavaScript function can also be defined using an expression .
A function expression can be stored in a variable:
After a function expression has been stored in a variable, the variable can be used as a function:
The function above is actually an anonymous function (a function without a name).
Functions stored in variables do not need function names. They are always invoked (called) using the variable name.
The function above ends with a semicolon because it is a part of an executable statement.
Advertisement
The Function() Constructor
As you have seen in the previous examples, JavaScript functions are defined with the function keyword.
Functions can also be defined with a built-in JavaScript function constructor called Function() .
You actually don't have to use the function constructor. The example above is the same as writing:
Most of the time, you can avoid using the new keyword in JavaScript.
Function Hoisting
Earlier in this tutorial, you learned about "hoisting" ( JavaScript Hoisting ).
Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope.
Hoisting applies to variable declarations and to function declarations.
Because of this, JavaScript functions can be called before they are declared:
Functions defined using an expression are not hoisted.
Self-Invoking Functions
Function expressions can be made "self-invoking".
A self-invoking expression is invoked (started) automatically, without being called.
Function expressions will execute automatically if the expression is followed by ().
You cannot self-invoke a function declaration.
You have to add parentheses around the function to indicate that it is a function expression:
The function above is actually an anonymous self-invoking function (function without name).
Functions Can Be Used as Values
JavaScript functions can be used as values:
JavaScript functions can be used in expressions:
Functions are Objects
The typeof operator in JavaScript returns "function" for functions.
But, JavaScript functions can best be described as objects.
JavaScript functions have both properties and methods .
The arguments.length property returns the number of arguments received when the function was invoked:
The toString() method returns the function as a string:
A function defined as the property of an object, is called a method to the object. A function designed to create new objects, is called an object constructor.
Arrow Functions
Arrow functions allows a short syntax for writing function expressions.
You don't need the function keyword, the return keyword, and the curly brackets .
Arrow functions do not have their own this . They are not well suited for defining object methods .
Arrow functions are not hoisted. They must be defined before they are used.
Using const is safer than using var , because a function expression is always constant value.
You can only omit the return keyword and the curly brackets if the function is a single statement. Because of this, it might be a good habit to always keep them:
Arrow functions are not supported in IE11 or earlier.

COLOR PICKER

Get your certification today!

Get certified by completing a course today!

Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your Suggestion:
Thank you for helping us.
Your message has been sent to W3Schools.
Top Tutorials
Top references, top examples, web certificates, get certified.
Assign a Function to a Variable in JavaScript

This article explains how we assign a declared function to any variable and check whether the function contains parameters or not. The function associated with the variable may return any value and store that value in a variable; we can also call the function using its assigned variable as many times as we want.
Example of Assigning a Function to a Variable Using JavaScript in HTML
Please enable JavaScript
Examine the Given HTML Code
Create a text document using a notepad or any other text editing tool., paste the given code in the created text file., save that text file with the extension of .html and open it with any default browser., you can see the input form to insert value and the submit button; using that button, you can check your value., alternative way to assign a function to a variable in javascript, related article - javascript function, related article - javascript variable.
Assign variable to function VS assign function to variable
I know that in the code above, we passed a function to a variable. fn=baz , if I change it to fn=baz() IDE will give me a type error: fn is not a function. So I assume in js we do not assign functions to variables, we assign the output of the functions into a variable. Because the elements at the each side of = has to be the same type. Am I correct?
Then what does this mean? function bar(){fn();} ? why do we need to add a parameter after a variable?
I am a bit confused…
You can assign functions to variables (because in JS you can pass around functions as if they were plain data), like in var f = function() {...}; . You can also invoke the function in f by writing f() in your code.
Also, variables in JS have no type. A variable that previously held a number doesn’t care if you assign it a string or array, or a function
When you changed it to fn = baz() , you were invoking the baz function, which returns undefined (simply because there are no return statements in that function). So fn now is undefined , which is definitely not a function, and you get the error when fn() was executed.
I don’t think that baz function returns undefined because here in this example, it returns 2.
But to understand the code I put 1st was
- baz got assigned to fn 1st via fn=baz .
- then baz got invoked via function bar(){fn();} .
Don’t confuse the result of console.log ging with return values. The 2 that you see is not a return value, but rather the result of console.log ging the 2 from inside baz() . When a function has no return statements, their return values are implicitly undefined .
True. The global fn variable holds a reference to the baz function. Then you can later invoke the baz function by using fn()
I will remember this from now on. Thanks!!

IMAGES
VIDEO
COMMENTS
Programmers can create a single variable using the var, let, or const keywords and assign the function expression to that. However, creating a
However, when we use the const-statement, the variable reference becomes immutable. This means that we cannot assign a new value to the variable. Please note
Assign an Anonymous Function to a Variable ... An “anonymous” function is the simplest type of function that can be assigned to a variable. As indicated by the
Parameters are essentially passed to functions by value — so if the code within the body of a function assigns a completely new value to a
It is possible to use a function expression and assign it to a regular variable, e.g. const factorial = function(n) {...} . But the function
Aside: name is reserved word in JavaScript and we cannot use it in global window context, only inside a function or as an object property. Search name window
This video explains the difference between declaring a function and assigning an anonymous function to a variable on JavaScript.
Functions stored in variables do not need function names. They are always invoked (called) using the variable name. The function above ends with a semicolon
Example of Assigning a Function to a Variable Using JavaScript in HTML ; script type · text/javascript · > ; form id="form" onsubmit · return false;
You can assign functions to variables (because in JS you can pass around functions as if they were plain data), like in var f = function() {...};