⏱ 0:01est. 5 min
Chapter 35- Function Statements and Function Expressions
Notes
#BIGWORD Expression - A unit of code that results in a value, It doesn't have to save to a variable
//Function expression
a = 3
returns 3
//Function statement
function greet(){
console.log("hi");
}
Example 1 - As we know functions are objects in js. Here we are creating a function on the fly and set it equal to a variable.
var anonymousGreet = function(){
console.log(‘hi');
}
//Here we still get function object. JS engine creates one and in this case NAME property is anonymous but you can access it with a reference i.e variable name and CODE i.e invocable is console.log("hi");
We can call this function using following statement.
anonymousGreet();
Example 2
greet(); // OUTPUT : hi
function greet(){
console.log("hi");
}
anonymousGreet(); // OUTPUT : Uncaught TypeError, Undefined is not a function
REASON : Because of function expressions are not hoisted.
var anonymousGreet = function(){
console.log("hi");
}
Example 3
greet(); // OUTPUT : hi
function greet(){
console.log("hi");
}
var anonymousGreet = function(){
console.log("hi");
}
anonymousGreet(); // OUTPUT : hi
function log(a){
console.log(a);
}
log(3); //creating a value on the fly -- OUTPUT : 3
log("hello"); //creating a string on the fly -- OUTPUT : hello
log({
greeting: ‘hi'
}); //creating an object on the fly -- OUTPUT : {greeting:"hi"}
log(function(){
console.log(‘hi');
});//creating anonymous function on the fly -- OUTPUT : function(){ console.log(‘hi');}
Example 4 - executing function created on the fly , Concept of first class functions where you can pass function around as a parameter, use them like variables called functional programming.
function log(a){
a()
}
log(function(){
console.log("hi");
});///OUTPUT : hi