Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between function with a name and function without name in Javascript

1.

function abc(){     alert("named function"); } 

v/s

2.

function(){     alert("Un-Named function"); } 

Kindly explain from beginners point.

like image 493
Shwet Avatar asked Sep 16 '13 13:09

Shwet


People also ask

What is function without name in JavaScript?

JavaScript allows us to define a function without any name. This unnamed function is called anonymous function. Anonymous function must be assigned to a variable. Example: Anonymous Function.

What is the difference between named function and anonymous function in JavaScript?

Anonymous functions are never hoisted (loaded into memory at compilation). Named functions are hoisted (loaded into memory at compilation). When invoking an anonymous function, you can only call it after the declaration line. A name function can be invoked before declaration.

What is the difference between function expression and anonymous function?

An anonymous function is a function without a function name. Only function expressions can be anonymous, function declarations must have a name. Show activity on this post. A function expression is an expression which defines a function.

What are the 3 types of functions in JavaScript?

There are 3 ways of writing a function in JavaScript: Function Declaration. Function Expression. Arrow Function.


1 Answers

They work exactly the same. It's only in how you are able to run them that they are different.

So example #1 you could call again at any point with abc();. For example 2, you would either have to pass it as a parameter to another function, or set a variable to store it, like this:

var someFunction = function() {     alert("Un-Named function"); } 

Here's how to pass it into another function and run it.

// define it function iRunOtherFunctions(otherFunction) {     otherFunction.call(this); }  // run it iRunOtherFunctions(function() {     alert("I'm inside another function"); }); 

As David mentions below, you can instantly call it too:

(function() {     alert("Called immediately"); })(); // note the () after the function. 
like image 194
Jordan Avatar answered Sep 18 '22 02:09

Jordan