Important JavaScript concepts that every developer should know.
The important javascript topics that programmers need to be familiar with are covered in this article.
🌟Hoisting
👉: Many developers obtain surprising outputs when unfamiliar with the idea of hoisting in Javascript.
⭐What is hoisting?
👉🏻Before the execution of the code, the interpreter appears to move the declaration of functions, variables, or classes to the top of their scope. This process is known as JavaScript hoisting.
See the code below👇🏻
console.log(myName);
var myName ;
The above programs work as below and the output will be undefined👇🏻
// using test before declaring
var myName;
console.log(myName); //o/p undefined
👉🏻Note: Keywords like let and const do not enable hoisting in terms of variables and constants.
👉🏻The variable is only raised to the top of the function when it is used inside of it. For instance,
function greet() {
b = 'Good Morning';
console.log(b); // Good Morning
var b;
}
greet(); // Good Morning
console.log(b);
Output:
hello
Uncaught ReferenceError: b is not defined
👉🏻In the example above, variable b is raised to the top of the function greet and is now a local variable. B is therefore only reachable within the function. There is no global variable created for b.
Before a function is declared, it may be called. For instance,
greet();
function greet() {
console.log('Good Morning');
}
👉🏻The function greet is called in the aforementioned program before it is declared, and the output is displayed. This is a result of hoisting.
👉🏻Only declarations are hoisted, so when a function is used as an expression, an error occurs.
🌟IIFE(Immediately Invoked Function Expression)
👉🏻IIFE, as its name suggests, is a Javascript function that is immediately invoked and executed after being defined.
// Regular Function.
function Greet() {
console.log("Good Morning");
};
// Execution of Regular Function.
Greet();
// IIFE creation and execution.
(function() {
console.log("Good Morining");
})();
🙂The main benefits of using IIFE are data privacy and quick code execution.
🌟Callback & Higher-Order Function
⭐Higher Order Function:
👉🏻In general, a function that takes another function as an argument is called a "hoof."
⭐Call Back Function:
👉🏻A callback is merely a function that is invoked or carried out inside another function and is passed to it as a parameter.
// Calculator :
const add = (a,b) => {
return a+b;
}
// console.log(add(5,2));
const subs = (a,b) => {
return Math.abs(a-b);
}
const mult = (a,b) => {
return a*b;
}
const calculator = (num1,num2, operator) => {
return operator(num1,num2);
}
👉🏻I have to perform the hardcoded for each operation, which is not good. To make it easier to use, we will use the callback and the HOF.
👉🏻Now instead of calling each function individually we can call it by simply using one function which is a calculator.
console.log(calculator(5,6,add));
console.log(calculator(5,6,subs));
console.log(calculator(5,6,mult));
👉🏻The calculator, the higher-order function in the aforementioned illustration, takes three arguments, the third of which is the callback. Because it accepts another function as an argument, the calculator in this case is referred to as the Higher Order Function.
👉🏻and because they are used as arguments in other functions add, sub, and mult are referred to as callback functions.
🌟Callback Hell(Pyramid of doom)
⭐Callback Hell is essentially a pyramidal structure made of nested callbacks that are stacked on top of one another. The pyramid structure that results from each callback depending on or waiting for the one before it has an impact on the code's readability and maintainability.☹
Example:👇🏻
console.log("Callback Hell");
setTimeout(()=>{
console.log(`1️⃣`);
setTimeout(()=>{
console.log(`2️⃣`);
setTimeout(()=>{
console.log(`3️⃣`);
setTimeout(()=>{
console.log(`4️⃣`);
setTimeout(()=>{
console.log(`5️⃣`);
setTimeout(()=>{
console.log(`6️⃣`);
}, 1000)
}, 1000)
}, 1000)
}, 1000)
}, 1000)
}, 1000)
🌟Promises
⭐In JavaScript, asynchronous operations are managed by promises. When dealing with numerous asynchronous operations, where callbacks can lead to callback hell and unmanageable code, they are simple to manage.
👉🏻Producing code is a time-consuming process.
👉🏻Code that must wait for the output is referred to as "consuming code."
👉🏻A JavaScript object called a promise connects writing code and reading code.
⭐There are three possible states for a promise.
Fulfilled: When the action is successfully finished, the condition is fulfilled.
Rejected: When an action fails, it is rejected.
Pending: Initial state of pending, neither fulfilled nor rejected.
// returns a promise
let countValue = new Promise(function (resolve, reject) {
reject('Promise rejected');
});
// executes after a successful promise resolution
countValue.then(
function successValue(result) {
console.log(result);
},
)
// runs if there is an error
.catch(
function errorValue(result) {
console.log(result);
}
);
🌟Async&Await
⭐The async keyword is used with a function to indicate that it is an asynchronous function. A promise is returned by the async function.
async function name(parameter1, parameter2, ...paramaterN) {
// statements
}
//name - the function's name
//parameters - parameters that are passed to the function
// async function example
async function f() {
console.log('Hello');
return Promise.resolve(1);
}
f();
👉🏻The async function uses the await keyword to wait for the asynchronous operation.
👉🏻The await keyword is used by the async function to wait for an asynchronous operation.
// promise
let promise = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('Hello')
}, 4000);
});
// async function
async function asyncFunc() {
// wait for the promise to be fulfilled
let result = await promise;
console.log(result);
console.log('hi!!');
}
// calling the async function
asyncFunc();
//output
//Promise resolved
//hi!!
👉🏻You write the code synchronously when using the async function. To catch the error, you can also use the catch() method. For instance,
// a promise
let promise = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('Promise is Resolveed')
}, 4000);
});
// async function
async function asyncFunc() {
try {
// wait for the promise to be fulfilled
let result = await promise;
console.log(result);
}
catch(error) {
console.log(error);
}
}
// calling the async function
asyncFunc();
👉🏻The program will move to the try block if it executes successfully. Additionally, the catch block will be called if the program throws an error.
🌟Closures
⭐A closure is made up of references to the state of the environment and a function that has been wrapped up (enclosed) (the lexical environment).
👉🏻In other words, a closure enables inner functions to access the scope of an outer function.
👉🏻Closures are created whenever a function is created in JavaScript, at function creation time.
const outerFun = (a) => {
let b = 10;
const innerFun = () => {
let sum = a+b;
console.log(`the sum of the two no is ${sum}`);
}
return innerFun;
}
let checkClousure = outerFun(5);
console.dir(checkClousure);
🌟Event Propagation
The concept of event propagation describes how events move through the DOM tree to reach their destination and what happens to them once they do.
In modern browser event propagation proceeds in two phases: capturing, and bubbling phase.
⭐Event Bubbling:
👉🏻During this phase, the target element's ancestors are visited one by one as the event bubbles up or propagates back up the DOM tree to the window. For instance, if a user clicks a link, the click event would go through the document node, the body element, the HTML element, and the p element that contains the link.
⭐Event Capturing:
👉🏻Events travel from the Window down the DOM tree to the target node during the capturing phase. For instance, if a user clicks a link, the click event would go through the HTML, body, and p elements before reaching the link itself.
🌟Currying:
👉🏻Currying is the process of evaluating multiple-argument functions and breaking them down into a series of single-argument functions.
const sum = (num1) => (num2) => (num3) => console.log(num1+num2+num3);
sum(5)(3)(8);
🌟Spread Operator
JavaScript got the Spread Operator in ES6. It takes an iterable and breaks it down into separate components.
For Example👇🏻
const colors = ['red', 'green', 'blue', 'white', 'pink'];
//case:1
const MyFavColors = ['red', 'green', 'blue', 'white','pink', 'yellow', 'black'];
//case:2 using spread operator
const MyFavColors = [ ...colors, 'yellow', 'black'];
console.log(MyFavColors);
🌟Destructuring
👉🏻A JavaScript expression called "Assignment" enables the unpacking of array values or object properties into separate variables. Data can be taken out of arrays, objects, nested objects, and variable assignments.
⭐Array Destructuring:
const MyBio= ['XYZ','abc','pqr'];
// Case no.1
let fname= MyBio[0];
let prof= MyBio[1];
let passion= MyBio[2];
console.log(fname);
console.log(prof);
console.log(passion);
//Now rather than above case, I can use below case also.
// case no.2
let [fname,prof,passion]= MyBio;
console.log(fname);
console.log(prof);
console.log(passion);
⭐Object Destructuring:
const myBioData = {
myFname: 'XYZ',
myLname: 'PQR',
myAge: 18,
}
// case 1
let myFname = myBioData.myFname;
let age = myBioData.myAge;
console.log(myFname);
console.log(age);
//case 2
let {myFname,myLname,myAge,myDegree="MCA"}=myBioData;
console.log(myDegree);
✨Conclusion:
So far, we have covered many essential JavaScript concepts and received an introduction to them in this post. In general, for each concept, a sample code was provided in order to understand the concepts.
👇🏻Check out my other platforms as well
Thanks for Reading😊