Question: What will be the value of bar after it is hoisted?
var bar = function() {
return 3;
};
I think: the function expression. I'm wrong?
Question: What will be the value of bar after it is hoisted?
var bar = function() {
return 3;
};
I think: the function expression. I'm wrong?
Why not just try it?
var bar = function() {
return 3;
};
console.log(bar);
Output,
function () {
return 3;
}
If you try to use an undefined variable then that will of course throw a reference error. If you try to assign to an undefined variable then it will create a global variable (in a web page, roughly equivalent to writing window.foo = bar;
). However the variable will still be undefined until it is created.
If however you declare a local variable using const
or var
, then it will be defined from the beginning of the function as having the value undefined
, so accessing the variable "early" will not throw a reference error, and setting it will set the local value. You do not have to declare the variable at the start of the function; the declaration will be hoisted to the scope of the function.
By comparison, in ES6, if you declare a variable using let
, then it will only be hoisted to the beginning of the block.
Also, if you declare a "variable" using function
, then its value will be hoisted too, so you can call a function before its declaration. (The function has to be in the same script though.)