Expression in JS: Something that returns a value
Example: Try out following in chrome console:
a = 10
output : 10
(1 + 3)
output = 4
Declaration/Statement: Something that does not return a value
Example:
if (1 > 2) {
// do something.
}
here (1>2) is an expression but the 'if' statament is not. Its not returning anything.
Similarly, we have Function Declaration/Statement vs Function Expression
Lets take an example:
// test.js
var a = 10;
// function expression
var fun_expression = function() {
console.log("Running function Expression");
}
// funciton expression
function fun_declaration() {
console.log("Running function Statement");
}
Important:
What happens when JavaScript engines runs the above js file.
Now suppose we update the js to.
// test.js
console.log(a) //output: udefined (No error)
console.log(fun_expression) // output: undefined (No error)
console.log(fun_expression()) // output: Error. As we trying to invoke undefined.
console.log(fun_declaration()) // output: running function statement (As fun_declaration is already hoisted in the memory).
var a = 10;
// function expression
var fun_expression = function() {
console.log('Running function expression')
}
// function declaration
function fun_declaration() {
console.log('running function declaration')
}
console.log(a) // output: 10
console.log(fun_expression()) //output: Running function expression
console.log(fun_declaration()) //output: running function declaration
The output mentioned above in the comments, should be useful to understand the different between function expression and function statement/declaration.