Blog

  • Memoization

    As our systems grow and start doing more complex calculations, the need for speed grows and process optimization becomes necessary. Ignoring this issue results in applications that use a lot of system resources and operate slowly.

    In this chapter, we will discuss memoization, a technique that can significantly reduce processing time when used properly.

    What is Memoization?

    Memorization is a technique for speeding up applications by storing the results of expensive function calls and providing them when the same inputs are used again.

    Let’s try to understand this by dividing the term into smaller parts −

    • Expensive Function Calls: In computer applications, memory and time are the two primary resources. So a function call that uses a lot of these two resources because it is performing a lot of calculations is considered expensive.
    • Cache: A cache is only a short-term data storage system that holds information to allow faster processing of future requests for that information.

    Benefits of Memoization

    After receiving input, a function does the necessary computation, caches the result, and then returns the value. If the same input is received again in the future, the process will not need to be repeated. It would just return the response that was saved in memory. As a result, a code’s execution time will be greatly reduced.

    When to Use Memoization?

    Here are some of the points mentioned while you should use memoization −

    • When a function calls itself. For example, consider the recursive functions.
    • When the function is pure (returns the same value every time it is invoked). If the value changes with each function call, there is no reason for holding it. As a result, we cannot use memoization in JavaScript when the function is impure.
    • When the function has a high temporal complexity. In this case, keeping the results in a cache improves efficiency by reducing time complexity by avoiding re-computation of functions.

    Memoization in JavaScript

    JavaScript memorization is an optimization technique used to minimize the application’s runtime, complexity, and proper use of time and memory. The procedure involves reducing the number of expensive function calls (a function that recursively calls itself and has some overlapping issues) by using an additional space (cache).

    We store the values that were computed in those previous subproblems using memoization. The saved value is then used once again if the identical subproblem comes up, which lowers the time complexity by reducing the need to perform the same calculation repeatedly.

    How Does Memoization Work?

    JavaScript Memoization purely based on two below concepts −

    • Closure
    • High-order function

    Closures

    The Closure is made up of a function enclosed by references to the state. A closure provides access to an outside function’s scope from an inside function. The closure is formed in JavaScript when a function is created.

    let greeting ="Welcome";functionwelcomeMessage(){let user ="Rahul"; 
       console.log(${greeting} to the program, ${user}!);}welcomeMessage();

    Output

    This will generate the below result −

    Welcome to the program, Rahul!
    

    In the above JavaScript code −

    • The variable greeting is a global variable. It can be accessible from anywhere, including the welcomeMessage() function.
    • The variable user is a local variable that can only be used within the welcomeMessage() function.

    Lexical scoping allows for nested scopes, with the inner function having access to the variables specified in the outer scope. Hence, in the code below, the inner function welcome() gets access to the variable user.

    functionwelcomeMessage(){let user ="Rahul";functionwelcome(){
    
      console.log(Greetings, ${user}!);}welcome();}welcomeMessage();</pre>

    Output

    This will procedure the following output −

    Greetings Rahul!
    

    Now we will modify the welcomeMessage() function and rather than invoking the function welcome(), we will return the welcome() function object.

    functionwelcomeMessage(){let user ='Rahul';functionwelcome(){
    
      console.log(Greetings ${user}!);}return welcome;}let greet =welcomeMessage();greet();</pre>

    Output

    If we run this code, we will get the same results as before. But it is important to note that a local variable is often only present during the function's execution.

    This means that after welcomeMessage() is executed, the user variable is no longer available. In this case, when we call gree(), the reference to welcome() remains, as does the user variable. A closure is a function that keeps the outside scope in the inside scope.

    Greetings Rahul!
    

    Higher-Order Functions

    Higher-order functions act on other functions by passing them as arguments or returning them. In the code above, welcomeMessage() is an example of a higher-order function.

    Now, using the well-known Fibonacci sequence, we will look at how memoization uses these concepts.

    Fibonacci sequence: The Fibonacci sequence is a set of numbers that begin and end with one, with the rule that each number (known as a Fibonacci number) is equal to the sum of the two numbers preceding it.

    1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...
    

    So a simple recursive function for this problem will be as follows −

    functionfibonacciSeq(n){if(n <2)return1;returnfibonacciSeq(n -1)+fibonacciSeq(n -2);}

    If we plot the recursion tree for the above function at n=4, it will look like this. As you can see, there are too many unnecessary computations. Let's try to fix this via memoization.

    functionmemoizedFibSeq(num, memo){// Initialize memo array if not provided
       memo = memo ||[1,1];// if num is less than or equal to 1, return the result directlyif(num <=1)return memo[num];// If result is already computed, return it from memoif(memo[num])return memo[num];// Calculate and store the result in memo
       memo[num]=memoizedFibSeq(num -1, memo)+memoizedFibSeq(num -2, memo);return memo[num];}// Calculate the 10th Fibonacci number
    console.log(memoizedFibSeq(10));

    Output

    Here is the outcome of the above code −

    89
    

    We modify the function in the code example above to accept an optional input named memo. We use the cache object as a temporary memory to store Fibonacci numbers and their corresponding indices as keys, which can then be retrieved later in the execution.

  • Local Storage

    This chapter will show you how to use JavaScript’s localStorage to save data for several browser sessions. We will demonstrate how to use this method using the Window.localStorage property, as well as go over the principles of web storage in JavaScript.

    What is localStorage in JavaScript?

    The localStorage feature allows JavaScript apps and websites to save key-value pairs in a web browser with no expiration date. This means that the stored data remains even if the user closes the browser or restarts the computer.

    LocalStorage is a window object property, so it can interact with and manipulate the browser window. It can also work when combined with other window settings and methods.

    Syntax

    The below Syntax returns a storage object and it can be used to get the current origin’s local storage space.

    myStorage = window.localStorage;

    What is Window.localStorage?

    The localStorage method is accessible via the Window.localStorage property. Window.localStorage is a JavaScript Window interface component that represents a window with a DOM content within.

    The Window interface has a wide number of functions, constructors, objects and namespaces. Window.localStorage is a read-only property that returns a reference to a local storage object which is intended to store data that can only be accessed by the origin that created it.

    When to use localStorage

    In simple terms, localStorage securely stores and retrieves data. While localStorage can save small amounts of data, it is not suitable for large datasets. Because localStorage is accessible to anybody who uses the device, you should avoid keeping critical information there. You can use it to save user preferences like language or theme. If you use it regularly it can also serve as a data cache. LocalStorage can save form data so that it is not lost when the user closes the browser.

    If your application requires you to log in, you can use localStorage to store your session data. You can stay logged in even after closing and reopening the browser.

    How does localStorage work?

    You have heard it before: localStorage stores data. And, if you’re saving data, you might need to access it later. In this section, we will look at exactly how localStorage works. Here’s an overview of how it works −

    • setItem() It adds a key and value to localStorage.
    • getItem() It retrieves/gets things from local storage.
    • removeItem(): It removes an item from localStorage.
    • clear(): To erase all data from localStorage, use clear().
    • key(): To obtain a localStorage’s key, it passes a number.

    Usage of setItem() Method

    The setItem() method lets you store values in localStorage. It accepts two parameters: a key and a value. The key can be used later to get the value linked to it. Here is how it should look −

    localStorage.setItem('name','Ankit Sharma');

    In the code above, the key is name, and the value is Ankit Sharma. As we said before, localStorage can only store strings. To store arrays or objects in localStorage you have to first convert them to strings.

    To do this, we will use the JSON.stringify() method before providing to setItem(), as follows −

    const userArr =["Ankit",25]
    localStorage.setItem('user',JSON.stringify(userArr));

    Usage of getItem() Method

    The getItem() method gives you access to the data saved in the browser’s localStorage object. This method takes a single parameter, the key, and returns the value as a string −

    localStorage.getItem('name');

    This returns a string with the value “Ankit Sharma”. If the key given is not found in localStorage, it will return null. For arrays, we use the JSON.parse() function, which converts a JSON string in a JavaScript object −

    JSON.parse(localStorage.getItem('user'));

    Using the array we constructed previously, here’s how to access it from local storage −

    const userData =JSON.parse(localStorage.getItem('user'));
    console.log(userData);

    This method returns the array [“Ankit”, 25]. You can look into the webpage and find it in the console, as follows −

    [Log] Name from localStorage: - "Ankit Sharma" (example.html, line 22)
    [Log] User array from localStorage: - ["Ankit", 25] (2) (example.html, line 26)
    

    This output is from Safari so it will look a little different on other browsers. Let us compare it with a different array which is not stored with localStorage −

    const userArr2 =["Anjali",27];
    console.log(userArr2);

    So now we have two arrays on the console you can see in the below output −

    [Log] Name from localStorage: - "Ankit Sharma" (example.html, line 22)
    [Log] User array from localStorage: - ["Ankit", 25] (2) (example.html, line 26)
    [Log] ["Anjali", 27] (2) (example.html, line 29)
    

    Normally, if you comment them out in the code editor they should disappear from the terminal. But anything saved via localStorage stays. Here is one example.

    Usage of removeItem() Method

    To delete an item from localStorage you can use the removeItem() function. When a key name is given to the removeItem() method so the current key is deleted from storage. If no object is linked with the given key this method will do nothing. Here’s the code.

    .localStorage.removeItem('name');

    Usage of clear() Method

    To delete all things from localStorage you can use the clear() function. When this method is used so it will clear all records in the domain’s storage. It does not accept any parameters. Use the following code −

    localStorage.clear();

    Usage of key() Method

    The key() function is useful for looping over keys while giving a number or index to localStorage to get the key’s name. The index option gives the key’s zero-based index for which you want to retrieve the name. Below is how it looks −

    localStorage.key(index);

    Advantages of LocalStorage

    Here are some advantages of using localStorage −

    • The first advantage of localStorage is that saved data never expires.
    • You can still access the data offline since localStorage stores data that is available even without an internet connection.
    • LocalStorage is more secure than cookies and provides greater control over your data.
    • LocalStorage provides more storage capacity than cookies.
    • Cookies can only store four kilobytes of data, whereas local storage can contain up to five megabytes.

    Disadvantages of LocalStorage

    Here are some disadvantages of localStorage −

    • LocalStorage is synchronous which refers to each operation occurs one after the other.
    • This has little impact on smaller datasets but as your data grows it can become a significant concern.
    • Local storage is more secure than cookies, but it should not be used to store sensitive information.
    • Anyone with access to the user’s device can view the data stored in localStorage.
    • Also localStorage can only save strings; if you want to store other data types, you must first convert them to strings.
    • Finally, storing too much data in localStorage may cause your application to slow down.
  • Lexical Scope

    What is Lexical Scope?

    Lexical scope refers to an expression’s definition area. In other words, an item’s lexical scope is the context in which it was generated.

    Lexical scope is sometimes known as static scope. The lexical scope of an item is not always determined by where it was invoked (or called). The lexical scope of an object serves as its definition space.

    So you may know that variables and methods have different levels of scope −

    • Global Scope: Variables defined outside of any function or block yet accessible throughout the program.
    • Local Scope: Variables defined within a function or block that can only be accessed within that function or block are considered local scope.
    • Nested Scope: Inner functions can access variables in their parent functions.
    • Block Scope: Variables defined with let and const are only valid in the block where they are declared, such as loops or conditionals.

    Now let us see some examples of lexical scope in JavaScript in the below section.

    Example 1

    Let us see the example code below −

    // Define a variable in the global scopeconst myName ="Shwetaa";// Call myName variable from a functionfunctiongetName(){return myName;}

    In the above sample code, we defined the myName variable in the global scope and used it in the getName() function.

    So here question arises, Which of the two spaces covers myName’s lexical scope? Is it the global or local scope of the getName() function?

    So you have to remember that lexical scope refers to definition space, not invocation space. As a result of our definition of myName in the global environment, its lexical scope is global.

    Example 2

    Let us see another example of lexical scope in JavaScript −

    functiongetName(){const myName ="Swati";return myName;}

    So here question arises, Where is myName’s lexical scope?

    And the answer is, Notice how we defined and invoked myName within getName(). As a result, myName’s lexical scope is the local environment of getName(), which is myName’s definition space.

    How Does Lexical Scope Work?

    The code that can access a JavaScript expression is determined by the environment in which it was defined.

    In other words, only code in an item’s lexical scope has access to it. For example, take the following code −

    // Define a functionfunctionmyLastName(){const lastName ="Sharma";return lastName;}// Define another functionfunctionshowFullName(){const fullName ="Swati "+ lastName;return fullName;}// Invoke showFullName():
    console.log(showFullName());

    Output

    The calling above will return −

    Uncaught ReferenceError: lastName is not defined
    

    Notice that the previous snippet’s call to showFullName() resulted in an Uncaught ReferenceError. The error was returned because the item can only be accessed by code within its lexical scope.

    As a result, the showFullName() function and its internal code cannot access the lastName variable because it was defined in a different scope. In other words, lastName’s lexical scope differs from that of showFullName().

    LastName’s definition space is showLastName(), whereas showFullName()’s lexical scope is the global environment.

    Now, see this below code −

    functionshowLastName(){const lastName ="Sharma";return lastName;}// Define another function:functiondisplayFullName(){const fullName ="Swati "+showLastName();return fullName;}// Invoke displayFullName():
    console.log(displayFullName());
    displayFullName;

    This will generate the below result −

    Swati Sharma
    

    Because showFullName() and showLastName() are in the same lexical scope, they both returned “Swati Sharma” in the example above.

    In other words, because the two procedures are written in the same global scope, showFullName() might call showLastName().

    Summary

    Understanding lexical scope in JavaScript is important for creating clean, maintainable code. By properly scoping variables and functionsyou canminimize naming conflicts, improve code readability, and prevent undesirable effects. Understanding lexical scope leads to more ordered and efficient programs.

  • Kaboom.js

    Kaboom.js makes it easy to create JavaScript games. You can add physics, detect collisions and make sprites in addition to controlling different scenes. By using Kaboom.js, you can focus on making an engaging and creative game instead of writing complex code. Think about adding other features like backgrounds, power-ups or scoring to further enhance your game!

    Getting Started with Kaboom

    To start your Kaboom application you need to call Kaboom to initialize the Kaboom contexts −

    kaboom({
       global:true,});

    If you build your application in your code editor, be careful to import both your JS file and the Kaboom.JS library into your HTML file.

    <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Simple Kaboom Game</title><script src="https://kaboomjs.com/lib/0.5.0/kaboom.js"></script></head><body><script src="example.js"></script></body></html>

    Create your Scene

    In Kaboom, everything is a component of a scenario. The scenario is essentially how the game will look, behave, and play out.

    kaboom({
       global:true,});scene("main",()=>{//...}]);

    In the example above, the scene method is activated for our “main” scene, and the other game elements are given inside the function. Lastly, we need to call the scene by using start at the end.

    Load your Sprites and Create Player

    Now we will have to start “drawing” our sprites onto our game UI. A sprite is a two-dimensional bitmap contained in a larger scene, usually in a 2D video game. For this chapter, we will use a Yeti sprite grabbed from Imgur.

    To load our sprites and build our players, we will use the load sprite method, enter our sprite image information and then create the player in the scene.In the previous example, we call the scene method for our “main” scene and pass the remaining game pieces to the function. Finally, we must use “start at the end” to refer to the scenario.

    kaboom({
      global:true,});loadRoot('https://i.imgur.com/');loadSprite('yeti','OqVwAm6.png');scene('main',()=>{const yeti =add([sprite('yeti'),pos(80,80),color(255,188,0),]);});start('main');

    If your code is accurate, you should see a yeti sprite on screen. Right-click your index.html file, copy the path, and paste it into a new browser page.

    Output

    This will generate the below result −

    Kaboom Example

    We’ll begin by adding the body component to your initialized sprite. This method effectively forces your sprite to follow the “rules of gravity”. Once this method is run, your sprite will begin to slide off the screen, therefore we will have to create a temporary platform as well.

    kaboom({
      global:true,});loadRoot('https://i.imgur.com/');loadSprite('yeti','OqVwAm6.png');scene('main',()=>{const yeti =add([sprite('yeti'),pos(80,80),color(255,188,0),body(),]);// Add the groundadd([rect(width(),12),pos(0,280),origin('topleft'),solid(),]);});start('main');

    Output

    This will produce the following result −

    Kaboom Example

    Kaboom Key Events

    The body method allows your sprite to use methods like and . We can use these methods alongside with key events to provide additional interesting behavior to our sprite. Let us give our Yeti the capacity to move left and right and jump. Add the following lines of code in your main scene function.

    kaboom({
      global:true,});loadRoot('https://i.imgur.com/');loadSprite('yeti','OqVwAm6.png');scene('main',()=>{const yeti =add([sprite('yeti'),pos(80,80),color(255,188,0),body(),]);// Add the groundadd([rect(width(),12),pos(0,280),origin('topleft'),solid(),]);// Add controls for jump and moveconstJUMP_FORCE=320;constMOVE_SPEED=120;keyPress("space",()=>{
    
    yeti.jump(JUMP_FORCE);});keyDown("left",()=&gt;{
    yeti.move(-MOVE_SPEED,0);});keyDown("right",()=&gt;{
    yeti.move(MOVE_SPEED,0);});});start('main');</pre>

    Output

    This will generate the following outcome −

    Kaboom Example

    Add a Background Image

    To conclude this chapter of Kaboom, we will add a background image to our UI and resize it to fit.

    kaboom({
       global:true,});loadSprite("yeti","https://i.imgur.com/OqVwAm6.png");loadSprite("bg","/Users/abc/Downloads/image.jpg");scene("main",()=>{// Add background spriteadd([sprite("bg"),scale(width()/240,height()/240),// Adjust the size of the backgroundorigin("topleft"),]);const yeti =add([sprite("yeti"),pos(80,80),color(255,188,0),body(),]);// Add the groundadd([rect(width(),12),pos(0,280),origin("topleft"),solid(),]);// Controls for jump and movementconstJUMP_FORCE=320;constMOVE_SPEED=120;keyPress("space",()=>{
    
      yeti.jump(JUMP_FORCE);});keyDown("left",()=&gt;{
      yeti.move(-MOVE_SPEED,0);});keyDown("right",()=&gt;{
      yeti.move(MOVE_SPEED,0);});});start("main");</pre>

    Output

    This will lead to the following outcome −

    Kaboom Example
  • Immutability

    Immutable means that something that cannot be changed. In programming, immutable means a value that cannot be changed once set.

    Most programs require the generation, modification, and deletion of data. So, why would anyone want to deal with immutable data?

    In this tutorial, we will look at the immutability of primitives, arrays, and objects using JavaScript examples.

    Concept of Immutability

    Immutability is a simple but powerful concept. In simple terms, something that cannot be modified is an immutable value. We can come across situations when we need to create a new object in our code with a new attribute or value while maintaining the existing value, particularly when creating our apps. The idea of immutability allows us to create new objects without changing the original value.

    JavaScript has two types: primitive and reference. Primitive types consist of numbers, strings, booleans, null, and undefined. Reference types are objects, arrays, and functions.

    The difference between the two is that primitive types are immutable (unchangeable), whereas reference types are mutable (changeable). For example, a string is immutable:

    let userAge ="22";let userNewAge = userAge;
    userAge ="24";

    We simply generated two variables and used userAge to the userNewAge variable. But when we modify the value of userAge, you will realize that both remain the same.

    console.log(userAge === userNewAge);// false

    Why use Immutability?

    Here are some reasons that shows you should use immutability in Javascript −

    • Predictability: When the data does not change it is easy to understand how your software works.
    • Prevent bugs: Immutable data can help prevent unexpected changes that can cause program errors.
    • Simple to Share: As immutable data never changes so it is better to distribute it throughout your applications.

    Examples of Immutability

    Below are some example to show the immutability in JavaScript −

    Example 1

    Here is the first example using strings as you may know strings in JavaScript are immutable. When you change a string so you create a new one.

    // Create a string herelet greeting ="Hello, world!";// This will not change the original string.
    greeting[0]="h"; 
    
    console.log(greeting);

    Output

    In this example we are trying to change the first letter of the greeting from “H” to “h.” But strings cannot be edited in this way. The original string remains the same.

    Hello, world!
    

    Example 2

    Now we will talk about the second example, in which we will use arrays and you may know arrays are mutable but we can create a new array instead of changing the existing one with the help of the spread operator in Javascript.

    // create an arraylet numbers =[1,2,3];// Create a new array with an extra number.let newNumbers =[...numbers,4]; 
    
    console.log(numbers); 
    console.log(newNumbers);

    Output

    In the above example we started with an array of numbers instead of changing the numbers we created a new array called newNumbers and insert a new number. Check the below output −

    [1, 2, 3]
    [1, 2, 3, 4]
    

    Example

    Objects are also mutable but we can create a new object instead of changing the existing one.

    let person ={ name:"Amit", age:25};// Create a new object with an updated age.let updatedPerson ={...person, age:26}; 
    
    console.log(person); 
    console.log(updatedPerson);

    Output

    This will generate the below result −

    { name: "Amit", age: 25 }
    { name: "Amit", age: 26 }
    

    Importance of Immutability

    There are several reasons why immutability is so important to our everyday code.

    • Once set, an immutable value cannot be changed. Instead, a fresh value is created. So the value remains consistent and dependable throughout the code. As a result, it makes state management across the program easier. Plus immutability is a core principle of state management frameworks like Redux.
    • Code becomes easier to read and less prone to errors when data structures are not changed quickly. This helps with troubleshooting and maintenance.
    • Immutability encourages less side effects and more predictable code, which aligns with the ideas of functional programming.
  • Function Composition

    Function composition is a powerful functional programming approach that allows programmers to combine numerous functions into a single function. This compositional method enhances readability, modularity and code reuse. The compose function is important for JavaScript’s ability to provide function composition.

    What is Function Composition?

    The method of combining several functions to create a new function is known as function composition. The output of one function becomes the input of the subsequent function in the composition chain, involving an order of operations or transformations performed to an input value.

    After receiving two or more functions, the compose function creates a new function that applies the functions in a right to left order. It means that the function on the right is applied first, then the function on the left, and so forth.

    Example

    Let’s consider an example to get a better understanding of function composition. Now look at the three functions increaseBy5, tripleValue, and reduceBy10. We want to create a composite function that uses these functions to a given input value. To do that, use the compose function as follows −

    constincreaseBy5=(num)=> num +5;consttripleValue=(num)=> num *3;constreduceBy10=(num)=> num -10;const applyOperations =compose(reduceBy10, tripleValue, increaseBy5);const finalResult =applyOperations(7);
    
    console.log("The final result after applying the operations is:", finalResult);

    Three basic functions are defined in the above example: reduceBy10, tripleValue, and increaseBy5. In order to apply these functions to an input value of 7, we have to create a composite function. By linking the functions together in the right order, the compose function enables us to do this.

    TripleValue, increaseBy5, and reduceBy10 are all represented by the composite function applyOperations. The functions are applied in the given order when we call applyOperations with the input value 7, yielding the output value 36.

    Implement the Compose Function

    To take advantage of the power of function composition, we need to define the compose function. Here is the implementation −

    constcompose=(...ops)=>{return(value)=>{return ops.reduceRight((result, operation)=>{returnoperation(result);}, value);};};
    console.log("Chained functions have been successfully executed.");

    Output

    This will produce the following result −

    Chained functions have been successfully executed.
    The final result after applying the operations is: 26
    

    This implementation uses the spread operator…functions to allow the compose function to take any number of functions as arguments. It returns a new function that applies each function on the accumulated result by iterating over the functions in reverse order using reduceRight.

    Benefits of Function Composition

    When creating clear and maintainable code, function composition has the following advantages −

    • Re-usability: We can create large operations without duplicating code by assembling smaller, reusable functions. By allowing each function focus on a particular task, code modularity and re-usability are encouraged.
    • Readability: We can express complex operations in a more easy and concise way by using function composition. We can define the desired transformation in a manner that closely resembles the issue domain by chaining functions together.
    • Maintainability: Understanding, testing, and modifying individual functions is made simpler by the clear purpose of each function. Code that is easier to maintain and understand results from changes made to one function that have no effect on other functions in the composition.

    Summary

    One effective functional programming technique that promotes code modularity, reusability, and readability is function composition. By simply chaining several functions together and applying them to input values, the compose function allows us to write more expressive and maintainable code.

  • Execution Context

    We will learn about the JavaScript execution context in this chapter, where we will also cover its types, definition, execution stack, creation process, and overall execution phase. We will go over each topic individually. First, let’s get started with the introduction.

    What is Execution Context?

    The execution context is a term that describes the internal workings of code. The JavaScript Execution Context describes the environment in which JavaScript code can be run. The execution context specifies which code sections have access to the functions, variables and objects used in the code.

    During the execution context, the given code is parsed line by line, with variables and functions kept in memory. An execution context is similar to a container for storing variables; code is evaluated and then executed. So, the execution context provides an environment in which specific code can be executed.

    Types of Execution Context

    The JavaScript execution context types are as follows −

    • Global Execution Context/GEC
    • Functional Execution Context/FEC
    • Eval Execution Context

    Now let us discuss each type one by one in the below section −

    Global Execution Context

    GEC (Global Execution Context) is often referred to as the base or default execution. Any JavaScript code that does not occur in a function will be found in the global execution context. The word ‘default execution context’ refers to the fact that the code is executed when the file is first loaded into the web browser. GEC carries out the following two tasks −

    • First, it creates a global object for Node.js and a window object for browsers.
    • Second, use the keyword ‘this’ to refer to the Windows object.
    • Create a memory heap to store variable and function references.
    • Then it stores all function declarations in the memory heap and initializes all variables in the GEC with ‘undefined’.

    Because the JS engine is single-threaded, there is only one global environment that may be used to execute JavaScript code.

    Functional Execution Context

    FEC, or Functional Execution Code, is the type of context generated by the JavaScript engine when a function call is found. Because each function has its own execution context, the FEC, unlike the GEC, can have multiple instances. Also, the FEC has access to the whole GEC code, while the GEC does not have access to all of the FEC’s code. During GEC code execution, a function call is initiated, and when the JS engine finds it, it generates a new FEC for that function.

    Eval Function Execution Context

    Any JavaScript code executed using the eval function creates and retains its own execution context. But JavaScript developers do not use the eval function which is a component of the Execution Context.

    Phases of the Execution Context in JS

    There are 2 main phases of JavaScript execution context −

    • Creation Phase: In the creation phase, the JavaScript engine establishes the execution context and configures the script’s environment. It sets the values of variables and functions as well as the execution context’s scope chain.
    • Execution Phase: In this phase, the JavaScript engine runs the code in the execution context. It parses any statements or expressions in the script and evaluates any function calls.

    Everything in JavaScript works within this execution context. It is divided into two parts. One is memory and the other one is code. It is important to keep in mind that these phases and components are applicable to both global and functional execution settings.

    Creation Phase

    Let us see the below example −

    var n =6;functionsquare(n){var ans = n * n;return ans;}var sqr1 =square(n);var sqr2 =square(8);  
    
    console.log(sqr1)
    console.log(sqr2)

    Output

    This will generate the below result −

    36
    64
    

    Initially, the JavaScript engine executes the full source code, creates a global execution context and then performs the following actions −

    • Creates a global object that is a window in the browser and global in Node.js.
    • Creates a memory for storing variables and functions.
    • Stores variables with undefined values and function references.

    After the creation phase the execution context will be moved to the code execution phase.

    Execution Phase

    During this step, it begins running over the entire code line by line from top to bottom. When it finds n = 5, it assigns the value 5 to the memory variable ‘n’. Initially, the value of ‘n’ was undefined by default.

    Then we get to the ‘square’ function. Because the function has been allocated memory, it goes right to the line var square1 = square(n);. square() is then invoked, and JavaScript creates a new function execution context.

    When the calculation is finished, it assigns the value of square to the previously undefined ‘ans’ variable. The function will return its value and the function execution context will be removed.

    The value generated by square() will be assigned to square1. This also applies to square two. Once all of the code has been executed, the global context will look like this and will be erased.

    Execution Stack

    The JavaScript engine uses a call stack to keep track of all contexts, both global and functional. A call stack is also referred to as a Execution Context Stack, Runtime Stack or Machine Stack.

    It follows the LIFO concept (Last-In-First-Out). When the engine initially starts processing the script, it generates a global context and pushes it to the stack. When a function is invoked, the JS engine constructs a function stack context, moves it to the top of the call stack and begins executing it.

    When the current function completes the JavaScript engine removes the context from the call stack and returns it to its parent. Let us check the below example code −

    functionfirstFunc(m,n){return m * n;}functionsecondFunc(m,n){returnfirstFunc(m,n);}functiongetResult(num1, num2){returnsecondFunc(num1, num2)}var res =getResult(6,7);
    console.log("The result is:", res);

    Output

    This will produce the below result −

    The result is: 42
    

    In this case, the JS engine creates a global execution context and starts the creation process.

    It initially allocates memory for firstFunc, secondFunc, the getResult function, and the res variable. Then it invokes getResult(), which is pushed to the call stack.

    Then getResult() calls secondFunc(). At this point, secondFunc’s context will be saved to the top of the stack. Then it will begin execution and invoke another function, firstFunc(). Similarly function A’s context will be pushed.

    After execution of each function it is removed from the call stack.

    The call stack’s size is determined by the operating system or browser. If the number of contexts exceeds the limit a stack overflow error will be returned. This happens when a recursive function has a base condition.

    functiondisplay(){display();}display();

    Output

    This will generate the below result −

    C:\Users\abc\Desktop\Javascript\example.js:2
    
    display();
    ^
    RangeError: Maximum call stack size exceeded

    Summary

    Finally, understanding how JavaScript works behind the scenes needs knowledge of the execution context. It defines the environment in which code is executed as well as the variables and functions available for use.

    The method of building involves creating the global and function execution contexts, the scope chain and allocating memory for the variables and functions. During the execution step the JavaScript engine goes over the code line by line. This includes evaluating and executing statements.

  • Engine and Runtime

    A JavaScript engine is a computer software that executes JavaScript code. It is responsible for translating human-readable JavaScript code into instructions that the hardware of the computer can understand.

    When JavaScript code is executed in a browser, it does not make direct contact with your computer’s hardware. Rather, it communicates with the JavaScript engine, which acts as an interface between the system and your code.

    Google’s v8 Engine is the most used JS engine, even though each browser has its own. This v8 Engine powers Node.js, which is used to build server-side applications, and Google Chrome.

    In this chapter you will learn more about what a JS engine is and how it functions −

    How JavaScript Engine Works?

    A call stack and a heap are always present in any JS engine. With the help of the execution context, our code is run in the call stack. Also, the heap is an unstructured memory pool that houses every item our application needs.

    JavaScript Engine Working

    Now that you know where the code is executed, the next step is to find out how to compile it into machine code so that it can run later. But let’s first review the compilation and interpretation.

    Compilation vs Interpretation

    During compilation, all of the code is concurrently transformed into machine code and stored in a binary file that a computer can run.

    Line by line the source code is executed by the interpreter during interpretation. While the program is running, the code still needs to be transformed into machine code, but this time it is done line by line.

    In the past, JS was only an interpreted language. But “just-in-time” compilation, a combination of compilation and interpretation, is now used by the contemporary JS engine.

    When using JIT compilation all of the code is concurrently translated into machine code and run immediately.

    You are possibly curious about the difference between JIT and compilation. One notable distinction is that the machine code is saved in a portable file after compilation. There is no need to rush after the compilation process; you can run it whenever you like.

    However, when JIT is used, the machine code must be executed as soon as the compilation process is completed.

    JIT and JavaScript

    Let us look at how JIT works specifically in JavaScript.

    So, when a piece of JavaScript code enters the engine, the first step is to parse it.

    During the parsing process, the code is converted into a data structure known as the AST or Abstract Syntax Tree. This works by first breaking down each line of code into bits that are significant to the language (e.g. as the const or function keywords), and then saving all of these pieces into the tree in a structured manner.

    This phase also determines whether there are any syntax mistakes. The generated tree is then used to generate machine code.

    JIT in JavaScript

    The next stage is compilation. The engine takes the AST and compiles it into machine code. The machine code is then performed promptly because JIT is used; keep in mind that this execution occurs on the call stack.

    But it’s not the end. The contemporary JavaScript engine generates wasteful machine code in order to run the program as fast as possible. The engine then takes the pre-compiled code, optimizes and re-compiles it while the program is already running. All this optimizing happens in the background.

    So far, you have learnt about the JS Engine and how it works behind the scenes. Let us take a look at what a JavaScript runtime is, more especially the browser runtime.

    List of JavaScript Engines

    Here is the list of available JavaScript Engines −

    BrowserName of Javascript Engine
    Google ChromeV8
    Edge (Internet Explorer)Chakra
    Mozilla FirefoxSpider Monkey
    SafariJavascript Core Webkit

    Let us understand each engine mentioned in the above table in brief −

    • V8: Developed by Google for Chrome. It improves the user experience on websites and applications by accelerating JavaScript execution. Also, V8 manages memory by collecting superfluous information and makes it easier to use JavaScript on servers, like in Node.js.
    • Chakra: Chakra was created by Microsoft for Internet Explorer. It speeds up JavaScript and lets the browser do other things at the same time by running scripts on a separate CPU core.
    • SpiderMonkey: Brendan Eich at Netscape developed the first JavaScript engine, SpiderMonkey, which is currently maintains Mozilla for Firefox. Anyone can use or modify it because it is open-source.
    • WebKit: WebKit for Safari was developed by Apple and is used by iOS devices, Kindles and PlayStations. WebKit manages common browser features like history and back-and-forth navigation in addition to displaying webpages.

    What is a JavaScript Runtime?

    A JavaScript (JS) runtime is a full environment for executing JavaScript code. It is made up of a number of components that work together to help JavaScript applications run smoothly. When we talk about a JS runtime, we often mean the full ecosystem that goes beyond just executing code.

    Depending on where JavaScript is executed (in the web browser or on the server with Node.js), the runtime may include additional environment-specific features. For example, in a browser, there can be functionality for managing browser events, accessing the DOM and interfacing with browser-specific functionalities.

    For the time being, we will only cover the JavaScript runtime in the browser. Consider a JS runtime to be a large box containing all of the components required to run JavaScript in browser.

    The JS engine is at the heart of any JS runtime. However, the engine alone is not sufficient. Web APIs are required for good functionality.

    JS runtimes, particularly those used in web browsers, include Web APIs that extend the fundamental JavaScript language’s capabilities. These APIs include interactions with the Document Object Model (DOM), XMLHttpRequest (for sending HTTP requests), timers, and more.

    Web APIs extend JavaScript’s capabilities by allowing it to interact with the browser environment and perform activities like changing web-page structure, handling user events and sending network requests.

    So, basically, Web APIs are engine-provided features that are not part of the JavaScript language. JavaScript gains access to these APIs via the window object.

    JS Runtime in the Browser

    Asynchronous actions in JavaScript, like receiving user input or performing network queries, make use of callback functions. These routines are placed in the callback queue and await execution. The callback queue manages asynchronous tasks in an ordered manner.

    To react to specific events, we can attach event handler methods to DOM events like buttons. These event handler functions are also known as callback functions. So, when the click event occurs, the callback function will be called.

  • Design Patterns

    In JavaScript, design patterns are classes and communicating objects that are designed to deal with a general design problem in a specific setting. Generic, reusable solutions to typical issues that come up throughout software design and development are known as software design patterns.

    They give developers a forum to discuss successful design concepts and function as best practices for resolving particular kinds of problems.

    What are Design Patterns?

    A design pattern in software engineering is a generic, replicable fix for a typical problem in program design. The design is not complete enough to be coded right away. It is a description or model for problem-solving that can be used in various contexts.

    Types of Software Design Patterns

    In JavaScript, there are primarily three categories of design patterns namely −

    • Creational Design Patterns
    • Structural Design Patterns
    • Behavioral Design Patterns

    Let’s discuss them one by one −

    Creational Design Patterns in JavaScript

    In software development, creational design patterns are a subset of design patterns. They work on the object generation process, trying to make it more flexible and efficient. It maintains the independence of the system and the composition, representation, and creation of its objects.

    Singleton Pattern

    The singleton design pattern makes sure a class has only one immutable instance. In simple terms, the singleton pattern is an object that cannot be changed or replicated. It is often useful when we want an immutable single point of truth for our application.

    Suppose that we want to have a single object that has all of our application’s configuration. We also want to make it prohibit to copy or modify that object.

    Two ways to implement this pattern are using classes and object literals −

    const Settings ={initialize:()=> console.log('Application is now running'),refresh:()=> console.log('Application data has been refreshed'),}// Freeze the object to prevent modifications
    Object.freeze(Settings)// "Application is now running"
    Settings.initialize()// "Application data has been refreshed"
    Settings.refresh()// Trying to add a new key
    Settings.version ="1.0" 
    console.log(Settings)

    This will generate the below result −

    Application is now running
    Application data has been refreshed
    { initialize: [Function: initialize], refresh: [Function: refresh] }
    
    classSettings{constructor(){}launch(){ console.log('Application is now running')}refresh(){ console.log('Application data has been refreshed')}}const appInstance =newSettings()
    Object.freeze(appInstance)// "Application is now running"
    appInstance.launch()// "Application data has been refreshed"
    appInstance.refresh()

    Output

    Here is the outcome of the above code −

    Application is now running
    Application data has been refreshed
    

    Factory Method Pattern

    The Factory method pattern provides an interface for creating objects that can be modified after they are generated. By combining the logic for building our objects in a single place, this reduces and enhances the organization of our code.

    This often used pattern can be implemented in two ways: by using classes or factory functions, which are methods that return an object.

    classCreature{constructor(name, message){this.name = name
    
      this.message = message
      this.type ="creature"}fly=()=&gt; console.log("Whoooosh!!")speak=()=&gt; console.log(this.message)}const creature1 =newCreature("Zee","Hello! I'm Zee from outer space!")
    console.log(creature1.name)// output: "Zee"

    This will produce the below output −

    Zee
    

    Abstract Factory Pattern

    Without knowing the precise types of linked objects, we can use the Abstract Factory design to generate groups of them. This is useful when we need to build unique objects that share only a few characteristics.

    It works like this: a primary abstract factory connects with the client, or user. This abstract factory then uses some logic to invoke a specific factory to generate the actual object. As a result, it acts as an overlay over the typical factory layout, allowing us to produce a large range of items in a single primary factory.

    For example, we are able to develop a system for an automobile manufacturer that includes trucks, motorcycles, and cars. The Abstract Factory pattern, which handles several object types with a single primary factory, makes this easy for us to do.

    // Each class represents a specific type of vehicleclassCar{constructor(){this.type ="Car"this.wheels =4}startEngine=()=> console.log("Vroom Vroom!")}classTruck{constructor(){this.type ="Truck"this.wheels =8}startEngine=()=> console.log("Rumble Rumble!")}classMotorcycle{constructor(){this.type ="Motorcycle"this.wheels =2}startEngine=()=> console.log("Zoom Zoom!")}const vehicleFactory ={createVehicle:function(vehicleType){switch(vehicleType){case"car":returnnewCar()case"truck":returnnewTruck()case"motorcycle":returnnewMotorcycle()default:returnnull}}}const car = vehicleFactory.createVehicle("car")const truck = vehicleFactory.createVehicle("truck")const motorcycle = vehicleFactory.createVehicle("motorcycle") 
    
    console.log(car.type)
    car.startEngine()
    
    console.log(truck.type) 
    truck.startEngine() 
    
    console.log(motorcycle.type)
    motorcycle.startEngine()

    Output

    This will generate the below result −

    Car
    Vroom Vroom!
    Truck
    Rumble Rumble!
    Motorcycle
    Zoom Zoom!
    

    Builder Pattern

    The Builder pattern is used to generate objects in “steps”. Functions or methods that add particular attributes or methods are typically included in our object.

    Because it separates the development of methods and attributes into separate entities, this design is cool.

    The object we create will always contain every property and method defined by a class or factory function. Using the builder pattern, which enables us to construct an object and apply only the “steps” that are required, provides a more flexible approach.

    // Define our creaturesconst creature1 ={
       name:"Buzz Lightwing",
       message:"You'll never debug me!"}const creature2 ={
       name:"Sneaky Bugsworth",
       message:"Can't catch me! Ha ha!"}// These functions add abilities to an objectconstenableFlying=obj=>{
       obj.fly=()=> console.log(${obj.name} has taken flight!)}constenableSpeaking=obj=>{
       obj.speak=()=> console.log(${obj.name} says: "${obj.message}")}// Add abilities to the creaturesenableFlying(creature1)
    creature1.fly()enableSpeaking(creature2)
    creature2.speak()

    Output

    This will give the following result −

    Buzz Lightwing has taken flight!
    Sneaky Bugsworth says: "Can't catch me! Ha ha!"
    

    Prototype Pattern

    By using another object as a blueprint and inheriting its properties and methods, you can create an object using the prototype pattern.

    Prototypal inheritance and how JavaScript handles it are likely familiar to you if you have been using JavaScript for a time.

    As methods and properties can be shared between objects without depend on the same class, the final result is much more flexible than what we obtain when we use classes.

    // Define a prototype objectconst creatureAbilities ={attack:()=> console.log("Zap! Zap!"),escape:()=> console.log("Soaring through the sky!")}// Create a new creature const creature1 ={
       name:"Winged Buzz",
       message:"You can't debug me!"}// Set the prototype
    Object.setPrototypeOf(creature1, creatureAbilities)// Confirm that the prototype is set successfully
    console.log(Object.getPrototypeOf(creature1)) 
    
    console.log(creature1.message) 
    console.log(creature1.attack()) 
    console.log(creature1.escape())

    Output

    This will produce the following outcome −

    { attack: [Function: attack], escape: [Function: escape] }
    You can't debug me!
    Zap! Zap!
    undefined
    Soaring through the sky!
    undefined
    

    Structural Design Patterns in JavaScript

    In software development, structural design patterns are a subset of design patterns that focus on how classes or objects are put together to create complex, larger structures. In order to increase a software system’s flexibility, re-usability, and maintainability, they help in the organization and management of relationships between objects.

    Adapter Pattern

    The Adapter Method is a structural design pattern which helps you to connect the gap between two incompatible interfaces and make them operate together.

    Let us see an example below −

    // Array of cities with population in millionsconst citiesPopulationInMillions =[{ city:"Mumbai", population:12.5},{ city:"Delhi", population:19.0},{ city:"Bangalore", population:8.4},{ city:"Kolkata", population:4.5},]// The new city we want to addconst Chennai ={
       city:"Chennai",
       population:7000000}consttoMillionsAdapter=city=>{ city.population =parseFloat((city.population /1000000).toFixed(1))}toMillionsAdapter(Chennai)// We add the new city to the array
    citiesPopulationInMillions.push(Chennai)// This function returns the largest population number constCityWithMostPopulation=()=>{return Math.max(...citiesPopulationInMillions.map(city=> city.population))}
    
    console.log(CityWithMostPopulation())

    Output

    This will generate the below result −

    19
    

    Decorator Pattern

    The decorator method is a structural design pattern that enables the addition of static or dynamic functionality to particular objects without changing how other objects of the same class behave.

    Following is the simple demonstration of this Reactivity Pattern −

    // Base class for a CarclassCar{constructor(){this.description ="Basic Car";}getDescription(){returnthis.description;}cost(){// Base price  return10000;}}// Decorator to add air conditioningclassAirConditioningDecorator{constructor(car){this.car = car;}getDescription(){returnthis.car.getDescription()+" + Air Conditioning";}cost(){// Adds cost for air conditioning  returnthis.car.cost()+1500;}}// Decorator to add a sunroofclassSunroofDecorator{constructor(car){this.car = car;}getDescription(){returnthis.car.getDescription()+" + Sunroof";}cost(){returnthis.car.cost()+2000;}}// Create a basic carconst myCar =newCar();
    console.log(myCar.getDescription()); 
    console.log(Cost: $${myCar.cost()});// Add air conditioning featureconst myCarWithAC =newAirConditioningDecorator(myCar);
    console.log(myCarWithAC.getDescription()); 
    console.log(Cost: $${myCarWithAC.cost()});// Add sunroof feature to the car const myCarWithACAndSunroof =newSunroofDecorator(myCarWithAC);
    console.log(myCarWithACAndSunroof.getDescription()); 
    console.log(Cost: $${myCarWithACAndSunroof.cost()});

    Output

    This will generate the below result −

    Basic Car
    Cost: $10000
    Basic Car + Air Conditioning
    Cost: $11500
    Basic Car + Air Conditioning + Sunroof
    Cost: $13500
    

    Facade Pattern

    The Facade Method is a structural design pattern that improves client interaction with a subsystem by offering a higher-level, simplified interface to a group of interfaces within that subsystem.

    To make it simpler to interface with a subsystem containing multiple complex parts in an automobile, we want to create a CarFacade class. The client should only use the CarFacade class; it should not use the individual components.

    // Subsystem classesclassEngine{start(){
    
     console.log("Engine started!");}stop(){
     console.log("Engine stopped!");}}classTransmission{shiftGear(){
     console.log("Transmission shifted!");}}classAirConditioning{turnOn(){
     console.log("Air conditioning is ON.");}turnOff(){
     console.log("Air conditioning is OFF.");}}// Facade classclassCarFacade{constructor(){this.engine =newEngine();this.transmission =newTransmission();this.airConditioning =newAirConditioning();}startCar(){
     console.log("Starting the car...");this.engine.start();this.transmission.shiftGear();this.airConditioning.turnOn();}stopCar(){
     console.log("Stopping the car...");this.airConditioning.turnOff();this.transmission.shiftGear();this.engine.stop();}}// Client code using the Facade patternconst myCar =newCarFacade();// Starting the car
    myCar.startCar();// Stopping the car myCar.stopCar();

    Output

    This will generate the below result −

    Starting the car...
    Engine started!
    Transmission shifted!
    Air conditioning is ON.
    Stopping the car...
    Air conditioning is OFF.
    Transmission shifted!
    Engine stopped!
    

    Proxy Pattern

    The Proxy Method is a structural design pattern that allows you to create an object substitute that can control access to the real object or serve as an intermediate.

    // Real objectclassRealImage{constructor(filename){this.filename = filename;this.load();}load(){
    
     console.log(Loading image: ${this.filename});}display(){
     console.log(Displaying image: ${this.filename});}}// Proxy classclassProxyImage{constructor(filename){this.filename = filename;// Real image is only loaded when neededthis.realImage =null;}load(){if(!this.realImage){// Lazy load   this.realImage =newRealImage(this.filename);}}display(){// Ensure the real image is loaded before displaying it  this.load();this.realImage.display();}}// Client codeconst image1 =newProxyImage("image1.jpg");const image2 =newProxyImage("image2.jpg");// Image is not loaded yet
    image1.display();// Image is already loaded image1.display();// A different image is loaded image2.display();

    Output

    This will lead to the below result −

    Loading image: image1.jpg
    Displaying image: image1.jpg
    Displaying image: image1.jpg
    Loading image: image2.jpg
    Displaying image: image2.jpg
    

    Behavioral Design Patterns in JavaScript

    Behavioral design patterns are a subset of software development design patterns that focus on the interactions and communication between classes and objects. They focus on how classes and objects work together and communicate in order to fulfill responsibilities.

    Chain of Responsibility Pattern

    The Chain of Responsibility is used to route requests via a number of handlers. Each handler decides whether to process the request or pass it on to the next handler in the chain.

    We could use the same example as before for this pattern because middlewares in Express are handlers that either execute a request or forward it to the next handler.

    Iterator Pattern

    The iterator can be used to navigate over the elements of a collection. This can appear unimportant in today’s computer languages, but it used to be that way.

    Any of the built-in JavaScript functions that let us iterate across data structures (for, forEach, for…of, for…in, map, reduce, filter, and so on) can use the iterator pattern.

    As with any traversal technique, we write code to iterate through data with advanced structures such as trees or graphs.

    Observer Pattern

    The observer pattern allows you to create a subscription mechanism that notifies multiple items about any changes to the item being observed. Basically, the rule is like having an event listener on a specific object, and when that object does the action we are looking for, we do something.

    React’s useEffect hook could be an excellent example here. UseEffect executes a provided function at the time it is declared.

    The hook is separated into two parts: the executable function and an array of dependents. If the array is empty, like in the example below, the function is called every time the component is shown.

    useEffect(()=>{ console.log('The component has  been rendered')},[])

    If we declare any variables in the dependency array, the function will only run when they change.

    useEffect(()=>{ console.log('var1 has been changed')},[var1])

    Even simple JavaScript event listeners can be considered as observers. This approach is also illustrated by reactive programming and tools like RxJS, which manage asynchronous information and events across systems.

  • Dead Zone

    What is a Dead Zone?

    A dead zone in JavaScript is a point during code execution where a variable exists but cannot be accessed.

    This is because of the behavior of variable hoisting, a mechanism that moves variable declarations to the top of their scope during compilation while leaving assignments intact.

    Dead Zones (DZs) are most commonly seen when variables are declared with let and const. Let and const declarations are block scoped which means they can only be accessed within the brackets around them. Variables on the other hand are not restricted in this way.

    How it works?

    JavaScript code executes in two phases:

    • Declaration Phase: During the declaration phase, all variables declared with var, let or const are initialized. Only var variables are initialized (set to undefined) but let and const are in a “temporal dead zone” until their actual value is assigned.
    • Execution Phase: The execution phase consists of setting values to variables and running code line by line.

    If you try to use a let or const variable before its value has been assigned, you will receive a runtime error.

    Variable Hoisting and Dead Zones

    Here is the example below −

    console.log(x);// This will give an error: "Cannot access 'x' before initialization"let x =5;

    When the console.log(x) command is executed the let variable x is declared but not initialized. So it is in the “dead zone,” and trying to use it results in an error.

    This does not apply to var variables which are automatically initialized with undefined during the declaration process.

    This happens due to the fact that variable x declaration is moved to the top of the scope, its initialization stays in its original location. So, there is a period between hoisting and actual initialization during which accessing the variable gives an error.

    Dead Zones with let and const

    Variables declared using let and const are hoisted differently from those declared with var. And var is hoisted and initialized with undefined, let and const stay uninitialized during the procedure. This behavior results in dead zones with these variable declarations.

    console.log(x);// Output: undefinedvar x =42;

    In this case, using var, x is hoisted and initialized with undefined, allowing it to be accessed before assignment. But if we replace the function by let or const:

    console.log(x);// Output: ReferenceError: Cannot access 'x' before initializationlet x =42;

    Using let, x is hoisted but not initialized. Trying to access it before initialization generates a ReferenceError, showing a dead zone.

    Dead Zones with var

    While var declarations in JavaScript behave differently than let and const declarations they can nevertheless produce dead zone refers to if not used properly.

    Understanding how var behaves during hoisting and scoping is critical for accurately detecting and managing dead zones.

    Variables declared with var are hoisted differently than let and const. With var both the declaration and the initialization are moved to the top of the scope. However, all over the hoisting phase, the variable remains undefined.

    Let us see this behavior using the below example −

    console.log(x);// Output: undefinedvar x =42;

    In this situation, x is elevated to the top of the scope and its declaration is set to undefined.

    As a result, attempting to use x before its actual assignment returns undefined rather than a ReferenceError, as let and const do.

    Handling of Dead Zones

    To avoid finding dead zones in your code, use following practices −

    • Declare Variables Before Use:- To avoid dead zones always declare variables at the beginning of their scope.
    • Understand Block Scope: Variables declared with let and const are block scoped which means they can only be accessible within the block in which they were defined. Understanding block scope allows you to manage variables more efficiently.
    • Use var with caution: While var rarely causes dead zones it does have different scoping limitations than let and const. Use var with caution and knowledge.
    • Use coding linters: Many coding linters can detect potential dead zone issues in your code helping you to catch them early in the development process.

    Benefits of reducing Dead Zones

    Identifying and decreasing dead zones in your JavaScript code can result in a number of advantages that increase overall code quality and maintainability −

    • Preventing Unexpected Problems: Eliminating dead zones reduces the possibility of having ReferenceErrors or other unexpected runtime issues, resulting in more predictable code behavior and better performance.
    • Improving Code Readability: Code without dead zones is easier to understand and maintain because developers can easily think about variable scope and initialization throughout the code-base. This improves readability and reduces cognitive stress when analyzing or altering the code.
    • Increasing Debugging Efficiency: With less dead zones, debugging becomes easier because developers can focus on actual issues rather than chasing down failures caused by uninitialized variables or incorrect variable access.
    • Collaboration: Clean, dead zone-free code promotes team collaboration by removing the chance of misunderstandings or misinterpretations about variable scoping and initialization. This promotes efficient code reviews and the smoother integration of changes into the code-base.