console.log(lunch); //undefined
var lunch = 'orange chicken'
//var declaration
var lunch;
//var assignment
lunch = 'orange chicken';
//var declaration and assignment
var lunch = 'orange chicken';
//how JS interepts the order
//only the declaration is hoisted; not the assignment
var lunch;
lunch = 'orange chicken';
Always declare all variables at the beginning of every scope
Function Declarations
begins with 'function' and no variable assignment
sibling of var declarations
are known before any code is run
are hoisted to the top
Function Expressions
function foo(){
return 'hello';
}
foo();
var bar = function(){
return 'world';
}
bar()
function add(n1, n2){
return n1 + n2;
}
console.log(add(1,2)); // logs 3
console.log(subtract(5,3)); // logs 2
function subtract(n1, n2){
return n1 - n2;
}
var add = function(n1, n2){
return n1 + n2;
}
console.log(add(2, 3)); // logs 5
console.log(subtract(5, 2)); //error
var subtract = function(n1, n2){
return n1 - n2;
}
//function declaration
add();
function add(n1, n2){
return n1 + n2;
}
//How Javascript interepts it:
//function declaration gets hoisted to the top
function add(n1, n2){
return n1 + n2;
}
add();
//function expression
subtract()
var subtract = function(n1, n2){
return n1 - n2;
}
//How Javascript interepts it:
//Only the variable declaration is hoisted to the top
var subtract;
subtract(); //error subtract is not a function
subtract = function(n1, n2){
return n1 - n2;
}
//Expression and Declaration
//What is the result of invoking five()?
var five = function(){
return 5;
}
function five(){
return 'five'
}
five(); //?
//Expression and Declaration
//How will this be interepted?
var five = function(){
return 5;
}
function five(){
return 'five'
}
five(); //?
//How the code is interpreted through hoisting
function five(){
return 'five';
}
var five;
five = function(){
return 5;
}
five(); // 5