Posts

Showing posts from February, 2023

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' ) ; }

JavaScript - How to create(imitate) a class?

Creating a class using function constructor. This is a conventional approach used in JavaScript to imitate classes without using class keyword. Older version of JS was not having class keyword. let Person = ( function () { function Person (name , title = 'Mr.' ) { //defining properties this . name = name ; this . title = title ; } //defining functions Person . prototype . greet = function () { console . log ( `Hello ${ this . title } ${ this . name } ` ) ; } ; return Person ; }()) ; let manoj = new Person ( 'Manoj' ) ; manoj . greet () ; Creating a class using class keyword. class Person { constructor (name , title = 'Mr.' ){ this . name = name ; this . title = title ; } greet () { console . log ( `Hello ${ this . title } ${ this . name } ` ) ; } } let manoj = new Person ( 'Manoj' ) ; manoj . greet () ;

JavaScript - What is the difference between call, bind and apply?

The value of this depends on how the code is executed rather how the code has been written. These functions are used to stabilize the value of this . call and apply are used like this. function thisLogger (comment) { console . log (comment + ', this=' + this ) ; } var myThis = { 'key' : 'value' } ; //Fixing the value of this as myThis //any value including primitive can be sent thisLogger . call (myThis , 'Sent my this' ) ; //apply is exactly same except the parameters //are passed as single array argument thisLogger . apply (myThis , [ 'Sent my this' ]) ; bind is used to fix the value of this when a function is defined. var myThis = 'myThis' ; var fixedThis = function fixedThis (){ console . log ( this ) } . bind (myThis) ; //The value is this is now fixed to myThis fixedThis () ; //print 'myThis' //Sending new value of this does not change it fixedThis . call ( 'changedThis' )...

JavaScript - What is closure?

Image
When a function is created using a variable in its outer function scope, the variable is stored as closure. function functionHoldingVar () { var closureCandidate = 'Hello Geeks' ; return function () { console . log (closureCandidate) ; } ; } var closureFunc = functionHoldingVar () ; //closureCandidate no more available in scope //It is stored in Closure scope closureFunc () ; //prints 'Hello Geeks' Please see below a snapshot of variables when a breakpoint is placed. The value of variable in closure does not depend on when the function is created rather when the function is executed. Below example would explain this. var globalObj = {} ; function returnFunctionWithClosure () { //store globalObj in local var var localRef = globalObj ; localRef . test = 'Function Scope' ; return function () { //localRef is stored in closure console . log (localRef . test ) ; } ; } var closureWithGlobalRef ...

JavaScript - What is hoisting of variable and function?

A variable defined with var and a function can be used before it is declared. hoistedExecute () ; //defined later function hoistedExecute (){ console . log ( 'In hoistedExecute function' ) ; } //Use of variable console . log (iAmDefinedLater) ; //prints undefined var iAmDefinedLater = 'hoisted' ; //Not defining iAmDefinedLater ever throws error Above is possible because of hoisting. All the functions are placed at the top of the scope. And variable declared using var keyword is kept at the top leaving the assignment at the same place. e.g. This code anyFunction () ; var aVariable = 'global' ; function anyFunction () { console . log ( 'anyFunction executed' ) ; //Error: localFunction is until now undefined localFunction () ; //If commented //Would print 'anyFunction executed undefined' var aVariable = 'local' ; var localFunction = function (){ console . log ( 'localFunction execut...

JavaScript - What is strict mode?

Strict mode in JS means strict operating context. It can be enabled by putting ‘use strict’ at the top of the file or at the top of a function. 'use strict' ; //other functions and variables //To enable only for a particular function function (param){ 'use strict' ; //Now only this function is in strict mode } Strict mode has the following effect on the code execution: Variable can not be used without declaration. (() => { 'use strict' ; undeclaredVar = 'someValue' ; //Not allowed //Error: undeclaredVar is not defined })() ; Not possible to use reserved keywords as variable names. e.g.  let , const , var etc. (() => { 'use strict' ; var eval = 'someValue' ; //Not allowed //Unexpected strict mode reserved word })() ; delete of var , function and function arguments is not allowed. (() => { 'use strict' ; var toBeDeleted = 'TryDeletingMe' ; var aFunctio...