JavaScript Basics for Beginners 2
Use of “use Strict” : Its strictly checks if the variable is defined using var keyword or let keyword.
Handle Global Variables: It is difficult to avoid global variables. But we can organize it properly by putting global variables in a proper Namespace, Closure and IIFE.
Closures: Closures are functions inside functions and it makes normal functions stateful.
Need of closure: To create self contained function/ Module/ state.
What is IIFE : stands for Immediately Invoked Function Expression. It is an anonymous function which means it does not have name and it gets immediately invoked.
var x = 10
(function() {
var y = 4
alert('I am IIFE function and I will execute')
})();
Here, variable y is local to this IIFE function only, if we try to get y out of this function it throws undefined.
Use of IIFE : It avoids name collision
What is name collision : Name collision happens when same name function names and variable names are declared.
function Init() {
var x =1
}
var Init = 0
Init()
Here it throws error Init is not a function. As Javascript is a dynamic langauge its data type is change from function to Number.
A normal function has a name, but IIFE does not have name. So with a normal function you can have a name collision but with IIFE you will not have any collision as it does not have name.
Let Keyword : It was introduced in ES6 and it helps to create block level scoped local variable
function Test(){
let x = 10;
if(x ===10) {
let x= 2;
console.log(x) --> 2
}
console.log(x) --> 10
}
Let and Var :
Variable declared by var keyword has immediate function scope while let has immediate enclosing block(block scope).
Var keyword is function scope and let keyword is block scope.
In var variable are initialized and hoisted undefined
In let variable are not initialized with any values so when trying to get value it throws an error.