Javascript function declaration vs function expression

Published on 2024-12-22 by Raul

In javascript, you can declare a function in several ways.

function myFunc() {
	//function body 
}

var myFunc2 = function() {
	//function body
}

Apparently, the two functions declared above are the same. But they're not, and knowing the difference can make your code cleaner and prevent bugs.

myFunc is called a function. But myFunc2 is a function definition.

Difference? Hoisting! myFunc is defined from the beginning of the scope, while the second will be defined AFTER the assignment. 

So writing:

myFunc(); //works
myFunc2(); //is throwing a TypeError

function myFunc()
{
	//function body 
}

var myFunc2 = function() {
	//function body
}

 I will explaing javascript hoisting in a future post.


Keep in touch


About

Hey there, I'm Raul, owner of CreativeCLR, a small consulting company.

Feel free to drop me any question you might have on this post using the comment section or the contact page.