Posts

Newly added posts

JavaScript - What is Event Loop?

It is known that JavaScript is single threaded. It runs usually in browser which must remain responsive all the time. If a code which could run slow and is written synchronously, the main thread gets blocked and UI becomes unresponsive. It’s a huge problem! Event loop solves this problem by allowing to queue functions to be executed later when there is nothing to be executed on main thread. Take the following code as an example. Everything is running synchronously. console . log ( 'Fast! But not everyone.' ) ; await slowCode ( 2000 ) ; console . log ( 'I was blocked by slow code.' ) ; Slow code emulator. const delayForMs = (forMilliseconds) => new Promise (resp => setTimeout (resp , forMilliseconds)) ; async function slowCode (forMilliseconds) { console . log ( 'I block browser.' ) ; await delayForMs (forMilliseconds) ; console . log ( 'Finally I am done!' ) ; } What gets printed on console...

JavaScript - How to use async & await?

async and await are used to make asynchronous call to synchronous. async could be used before a function. Technically it is possible to use async on any function to make it asynchronous. It automatically wraps the return to a Promise . Any error thrown inside the method would also be wrapped inside a Promise . Unnecessary use of async async function square (m) { return m * m ; } // print Promise { 16 } console . log ( square ( 4 )) ; The function square is not having any await . The Promise return would resolve immediately and async gives no benefit. Executing above code would print Promise { 16 } . Most useful scenario for async & await Take the slightly modified code as an example. An await has been placed to simulate delay of 0 millisecond. const delayForMs = (forMilliseconds) => new Promise (resp => setTimeout (resp , forMilliseconds)) ; async function square (m) { // To use await the function must be asy...

JavaScript - How to use rest parameters and spread syntax?

Rest and spread is a very useful feature for handling variable number of arguments in a function. What is arguments inside a function? arguments contains information about all the parameters being passed to a function. Don’t make mistake of understanding it as an array. It is an object of type Arguments Let’s take the following code block as an example function getFuncArguments () { // arguments is of type Arguments, not exactly an array return arguments ; } const normalArray = [ 1 , 3 , 'a' ] ; console . log ( getFuncArguments ( 1 , 3 , 'a' )) // [Arguments] { '0': 1, '1': 3, '2': 'a' } console . log ( getFuncArguments ( ... normalArray)) ; // [Arguments] { '0': 1, '1': 3, '2': 'a' } console . log ( getFuncArguments (normalArray)) ; // [Arguments] { '0': [ 1, 3, 'a' ] } Technically, arguments could be used to so...

JavaScript - What is Promise and how to work with it?

The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value. [ 2 ]. A promise can have three state pending, fulfilled and rejected. To understand promise lets take a look at the below function. It returns a promise with even number or gives error randomly. function randomEven () { let randomResolve = new Promise ((resolve , reject) => { //get a number between 1 & 10 randomly let numberBetween0And9 = Math . floor ( Math . random () * 10 ) ; //check if the number is even let isEven = (numberBetween0And9 % 2 === 0 ) ; //resolve or reject after 1 sec setTimeout (() => { if (isEven) { //resolve if even resolve (numberBetween0And9) ; } else { //Reject if odd reject ( 'The number is odd' ) ; } } , 1000 ) ; }) ; return randomResolve ; } Using a function returning Promise . //evenNum...

JavaScript - What is setTimeout and setInterval?

setTimeout is used to execute some code after a specified amount of time. The function defined in setTimeout is queued in event loop after the specified interval. The execution would happen after the timeout, but might not execute immediately after timeout. setTimeout (() => { console . log ( 'Executes after timeout' ) ; } , 1000 ) ; //above code executes after 1000ms setTimeout with 0ms timeout. //Making timeout 0 does not make it synchronous setTimeout (() => { console . log ( 'Executes after 0 ms' ) ; } , 0 ) ; console . log ( 'Execute on main thread.' ) ; //above prints //Execute on main thread. //Executes after 0 ms setInterval is used to execute some code repeatedly at an interval. setInterval ( function (){ console . log ( 'I am printed at an interval of 1 sec.' ) ; } , 1000 ) ;

JavaScript - Single quote, double quotes and backtick strings?

There are three ways a string could be defined in JavaScript. There is no particular difference between single quote and double quote strings. But, which to use can depend on situation. Single quote, double quotes The only difference is that it is required to escape " or ' depending on which quote is being used. Examples // Wrong choice let stringSingleQuote = 'I \' m inside single quote' ; let stringDoubleQuote = "He said, \" Work is Worship \" " ; let htmlDoubleQuote = "<h1 class= \" some-class \" >Some text</h1>" ; // Below is easier let stringSingleQuote = "I'm inside single quote" ; let stringDoubleQuote = 'He said, "Work is Worship!"' ; let htmlDoubleQuote = '<h1 class="some-class">Some text</h1>' ; Backtick(`) strings or template strings We would need to escape backticks. let withBacktick = `I have backtick( \` ).`...

JavaScript - How to handle errors?

Creating a custom error. //Creating a custom error let customError1 = new Error ( 'Custom Error' ) ; let customError2 = Error ( 'Custom Error' ) ; //both errors have exactly same behavior Throwing an error. //Throwing a custom error throw customError1 ; throw (customError2) ; // A simple string can be thrown throw 'I am an error' ; throw ( 'I am an error' ) ; //A boolean or number also throw true ; throw 6 ; try...catch...finally block. try { let customError1 = new Error ( 'Custom Error' ) ; throw customError1 ; } catch (error) { console . log (error . message ) ; //prints 'Custom Error' } finally { //Executes always in all cases console . log ( 'I am logged in all cases' ) ; }