what javascript actually is
what people think javascript is
First we understand scope in JavaScript.
Locally scoped variable
Globally scoped variable
/ Example of accessing variables INSIDE the function
// words is a LOCAL variable
function speak(){
var words = 'hi';
console.log(words);
}
speak(); // 'hi'
console.log(words); // Uncaught ReferenceError: words is not defined
// Example of accessing variables OUTSIDE the function
// words is a GLOBAL variable
var words = 'hi';
function speak(){
console.log(words);
}
speak(); // 'hi'
console.log(words); // 'hi'
Closures in Nested Functions
function speak() {
return function logIt() {
var words = 'hi';
console.log(words);
}
}
A closure is a function that has access to the parent scope, even after the scope has closed.
function speak() {
var words = 'hi';
return function logIt() {
console.log(words);
}
}
Closures basically allow us to do 3 things
When people first encounter Hoisting in Javascript
Hoisting is employed to explain how Variables and Function declarations are ‘lifted’ to the top of a function or a global scope.
So what is Hoisting?
An example of hoisting
console.log(notyetdeclared);
var notyetdeclared = "now it is declared";
hoisting();
function hoisting() {
console.log(notyetdeclared);
var notyetdeclared = "declared differently";
console.log(notyetdeclared);
}
A call stack for the code sample
Lexical environments for the code sample
So to elaborate on the first phase: It works in two steps.
Questions?