Question

What is difference between function declaration and function definition in JavaScript? I read chapter 5.3.2 from this book

When nested, however, function declarations may only appear at the top level of the function they are nested within. That is, function definitions may not appear within if statements, while loops, or any other statements.

but don't understand difference between declaration and definition... Please, explain it ( note: I understand difference between function expression and function declaration!)

Was it helpful?

Solution 2

In this case, they are just using two different terms to refer to the same thing. The official* term is "function declaration".

Source for official is page 98 of the ECMAScript standard.

OTHER TIPS

The important thing is to distinguish two cases:

  • var f1 = function() {...} This is often referred to as a function expression.

  • function f2() {...} This is often referred to as a function declaration.

Whatever the names you give to it, var f1 will be hoisted to the top of the wrapping function (but f1 will be assigned the value of the function only at the line you have written it). However the whole function declaration of f2 will be hoisted to the top of the wrapping function.

There is a great post that explains this more in details here.

function isEven(num){
     if(num%2 === 0){
return true;
}else{
return false;
}
}

In the above code function isEven(num) is called as function declaration, its like in that line of code you declare that isEven you are using is a function.

And the remaining part of the code inside the curly braces is called function definition. Where you provide defintion for the function isEven.

In js, we don't seperate the declaration and defintion, because we have hoisting. Hoisting makes your function declaration & definition to be hoisted to the top, so you can use the function even before defining it.

In other programming languages like 'C', you don't have hoisting. So the declarations of functions are made before usage and defintions can be placed where ever we want, inside the file.

And thus the reason for two names and what they mean.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top