[SOLVED] What is the difference between anonymous function and function expression in JavaScript?

Issue

I’ve been having trouble with function expression and anonymous function.

let sayHi = function() {
  alert( "Hello" );
}; //This is function expression

var anon = function() {
  alert('I am anonymous');
}
anon(); //This is anonymous function

I don’t see the difference between those two. From i see, they look the same to me. Can anyone please give me a better explanation of it so i can understand it. I appreciate it. Thank you

Solution

I think the better way of understanding is

let sayHi = function someName() {
  alert( "Hello" );
}; //This is function expression but with name and function can be called either way like sayHi() or someName().

var anon = function() {
  alert('I am anonymous');
}
anon(); //This is also function expression but without name to the function hence it is anonymous function.

An anonymous function is a function without a function name. Only function expressions can be anonymous, function declarations must have a name.

function() {
  alert('Hi')
}); // When used as a function expression 
(() => {
  alert('Hi')
}); // or using the ECMAScript 2015 arrow notation

MDN link to mozzilla developer network for more on functions

Answered By – pavan kumar

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.