This and Arrow function in JavaScript.
"This" keyword -> Refers to current context.
console.log(this)
// O/P -> an empty object initially.
const user = {
user : "harsh"
roll :28,
welcomeMessage : function(){
console.log(`${this.user} ,welcome)
}
}
user.welcomeMessage() // O/P -> harsh welcome
if we console.log(this) in chrome browser console this will print global object
which in the case of a browser environment, is usually the window
object.
Arrow function :-
Arrow functions in JavaScript provide a concise syntax for writing function expressions. They were introduced in ES6 (ECMAScript 2015) and offer a more concise syntax compared to traditional function expressions.
const addTwo = (num1,num2) =>{
return num1 + num2 //explicit return
}
const addTwo = (num1,num2) => num1 + num2; // implicit return.
const addTwo = (num1,num2) => (num1 + num2); //important.
if I give { } then I will have to write return keyword.
IIFE (Immediately Invoked Function Expression)
It is a common way to write function in javascript where a function is defined and executed immediately.
(function chai (){
console.log("Connected")
})
chai() //traditional way to define and call function
//IFFE
(function chai (){
console.log("Connected")
}) ( ) ; //semicolon is needed so that other IFFE also work(mainly when we write 2 or 3 IFFE)
// The trailing () immediately invokes the function expression.
( ) ( ) => IFFE
// To avoid pollution of global scope we use IFFE.
//Global scope k pollution se bachne k liye we use IFFE
( (name ) => {
console.log(`connected ${name}`)
}) ("harsh")
//when there is any parameter.