DEV Community

jtwebguy
jtwebguy

Posted on

JavaScript: Closure, variables & hoisting

Closure

I will try to get a shot at explaining these three things because these are mostly asked during interviews so hang around a bit.

Closure is, to simply say is the boundary of each function on JavaScript between the two curly braces or "mustaches" for its own variables.

Consider this example.

let name = 'Sally';

function greeting() {
let message = 'Hi';
console.log("Greeting:", message + ' '+ name);
}

That function will log "Hi Sally" because "name" is a global variable and it is accessible inside the function.

But if you try:

let name = 'Sally';

function greeting() {
let message = 'Hi';
}
console.log("Greeting:", message + ' '+ name);

It will put out "ReferenceError: message is not defined" error because the message variable is not referenced outside of its enclosing function. No leaking out it is.

You can find more advanced closure explanations [here].(https://www.javascripttutorial.net/javascript-closure/)

Variables

Variables in JavaScript are just like any variables in other language but much more simple. It is declared by using "var", "const" or "let" keywords.

var is the oldest kid in the JS world. It can hold any variable type and can be changed inside a function when declared globally but it cannot be referenced outside its parent function. (See closure above)

const is a variable that cannot be changed throughout your code.

let is block scoped to the function, expression or statement that is used.

for(let i=0; i<10; i++){
console.log(i)
}
console.log(i)

The variable "i" in the above for loop will console.log fine but outside it will be undefined.

for(var i=0; i<10; i++){
console.log(i)
}
console.log(i)

Using "var" instead of "let" lets you use "i" outside the loop so it has some uses.

Hoisting

MDN says:
JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code. Hoisting allows functions to be safely used in code before they are declared.

console.log(i); //undefined
var i=0

Considering the code above, log will output undefined because the variable was hoisted up prior to execution.

console.log(i); //ReferenceError: can't access lexical declaration 'i' before initialization
let i=0

console.log(i); //ReferenceError: can't access lexical declaration 'i' before initialization
const i=0

Hoisting does not work for const or let keywords so keep that in mind.

That's it for now folks! Happy coding.

Top comments (0)