Three Basic JavaScript Concepts
Three Basic JavaScript Concepts You Should Know.
1. Scope
2. IIFE (Immediately Invoked Function Expression)
3. Hoisting
First and foremost, JavaScript has three different keywords to declare a variable. The differences between the three are based on Scope, Hoisting and Reassignment.
- var
var is function scope, can be hoisted, can be reassigned, can be redeclared.
- let
let is block scope, cannot be hoisted, can be reassigned, cannot be redeclared.
- const
const is block scope, cannot be hoisted, cannot be reassigned, cannot be redeclared.
1. Scope
Scope in JavaScript refers to the current context of code, which determines the accessibility of variables to JavaScript. The two types of scope are local and global.
- local --> the ones declared inside of a block.
- global --> the ones declared outside of a block.
2.IIFE
An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. The name IIFE is promoted by Ben Alman. It's also known as Anonymous function.
3. Hoisting
JavaScript saved x to memory as a variable before the execution of the script. Since it was still called before it was defined, the result is undefined and not 100. However, it does not cause a ReferenceError and halt the script. Although the var keyword did not actually change location of the var, this is a helpful representation of how hoisting works. This behavior can cause issues, though, because the programmer who wrote this code likely expects the output of x to be 100, when it is instead undefined.
In this example, we declared x to be 100 globally. Depending on an if statement, x could change to 200, but since the condition was false it should not have affected the value of x. Instead, x was hoisted to the top of the hoist() function, and the value became undefined. This type of unpredictable behavior can potentially cause bugs in a program.
Since let and const are block-scoped, they will not hoist in this manner, as seen below.
The other JavaScript concepts posts are coming soon, stay tuned!
Thanks for reading!