JavaScript Interview Preparation

JavaScript Interview Preparation

JavaScript Interview Preparation

What is the nature of JavaScript?

  • JavaScript is a Single Threaded and Synchronous Programming Language
  • Single-threaded means one command process at a time

What is Synchronous and aSyncronous in JavaScript? What is Single thread and Multi-thread?

  • Synchronous code runs in sequence. This means that each operation must wait for the previous one to complete before executing, It Stops the Execution of further code until done, it is also called Blocking.

  • Asynchronous code runs in parallel. This means that an operation can occur while another one is still being processed.

  • Single-threaded processes contain the execution of instructions in a single sequence, one command is processed at a time, and JS has only one call stack that is used to execute the program.

  • Multi-thread processes allow the execution of multiple parts of a program at the same time. Ex. NodeJS


What is Scope? Type of Scope? Scope Chain? Lexical Scope? Lexical Environment?

  • Scope is the part of a program where it is available for use. Scope means where you can access specific variable or function in our code.

  • JavaScript has 3 types of scope:

    1. Block scope
    2. Function scope
    3. Global scope
  • Variables declared Globally have Global Scope.

  • The scope created with a pair of curly braces is called Block Scope, Block scope is inside a specified Block.
  • Scope inside a Function is called Function scope.
  • Code inside {} is called a block scope, if it's inside a function it's called function scope.

Scope Chain

  • The Scope Chain is the hierarchy of scopes that will be searched in order to find a function or variable.

ScopeChain.PNG

  • The process of going one by one to parent and checking for values is called scope chain or Lexical environment chain.

Lexical Scope

  • Lexical Scope means that in a nested group of functions, the inner functions have access to the variables and other resources of their parent scope.

  • Lexical means hierarchy or in order.

  const fullName = "Murtuza Rangwala";
  // Nested functions
  function outer() {
    function inner() {
      return fullName;
    }
    return inner();
  }
  console.log(outer());
  • Let's try to understand by the diagram.

LexicalScope.PNG

lexical.PNG

  • Here inner() which is inside outer() has the access to its parent outer() and global also, so we can acess fullname inside inner(), it's called Lexical Scope.

  • If variable is still not found in global scope it also search in lexical environment of global, which is Null so if variable is not found till this point, it will give error as not defined.

Lexical Environment

  • Lexical Environment is the local memory along with lexical environment of its parent.
  • We can also refer to the above diagram of lexical scope or we can look at how it works inside the browser.

  • We can see here that a() has local memory as well as global(which is its parent).

Is JavaScript a Statically typed or dynamically typed language?

  • JavaScript is a Dynamically-typed language, because we do not have to provide any of the thing like numbers, strings, etc.
  let firstName;    // We defined variable
  firstName = 23;   // assign value in number
  firstName = "Murtaza"; // now assign value as string
  console.log(firstName); // Murtuza
  • In the above example we declared a variable named firstName, then we assign value as number and then we again assign value as string. We can reassign value regardless of its data type.

  • TypeScript is a Statically typed language.


What is undeclared and undefined in JavaScript?

  • If we use variable before defining then it return as undefined.
  • If we use variable without defining anywhere in a program it return as undeclared or not defined.
  console.log(firstName);  // undefined
  var firstName;
  console.log(lastName);  // ReferenceError: lastName is not defined
  • Undeclared means it is not declared anywhere in Code/program.(not born)
  • undefined is used before declaring it. (born but we do not take responsibility)

What is Hoisting in JavaScript?

  • JavaScript engine scans the whole program/code before executing, it is known as Hoisting.

  • Hoisting is a concept which enables us to extract values of variables and functions even before initializing/assigning value without getting error and this is happening due to the 1st phase (memory creation phase) of the Execution Context.

  console.log(firstName);  // undefined
  var firstName;
  • Again take the same example, here JavaScript engine scan firstName and add it in the Memory phase(1st phase of EC).

What is 'this' in JavaScript?

  • This keyword refers to an object that is executing the current piece of code. It references the object that is executing the current function.

  • When this is used alone, it refers to the global object.

  • When this is used in a function, it refers to the global object.

  • When this is used inside an object's method, it refers to the object it lies within.

  • When this is used inside the arrow function, it refers to the parent scope.

  let user = {
    firstName: "Murtuza",
    lastName: "Rangwala",
    role: "admin",
    getUserDetails: function () {
      return `User: ${this.firstName} ${this.lastName} has role of ${this.role}`;
    },
  };
  console.log(user.getUserDetails());
  • this keyword in browser gives window object.
  • this keyword in node give {}

What are the different type of Functions we have and how all functions works? What is Arrow function?

  • JavaScript functions are used to perform operations. We can call JavaScript function many times to reuse the code.
  • Every JavaScript function is Function Object. You can check (function () {}).constructor === Function // return true

Function Definition / Function Declaration:

  • We can define function as below:
  function funName() {
    return console.log(`Funtion Called`);
  }
  funName();
  • Syntax:
    function functionName(parameter1,parameter2,.....){
       return something
    }
    
  • Here parameters are not compulsory.

Function Expression:

  • Here name can be provided with a function expression, Assigning a function to a variable. Function acts like a value.
var b = function() {
console.log("Hello");
}
b();

Difference between function statement and expression ?

  • Main Difference is Hoisting.
  a(); // "Hello A"
  b(); // TypeError: b is not a function
  function a() {
  console.log("Hello A");
  }
  var b = function() {
  console.log("Hello B");
  }
  • During memory creation phase a is created in memory as a function. But b is created like a variable (b: undefined) and until the code reaches the function() part, it is still undefined, So it cannot be called.

Anonymous Function:

  • A function without a name.
  • We can use it in Function Expression,setTimeout(),setInterval(),Arrow Function, and many more.
// Use in setTimeout
  setTimeout(function () {
    console.log("Welcome to JavaScript World !");
  }, 2000);
  • Syntax : function () {}

  • Anonymous functions are used when functions are used as values.

Arrow Function:

  • Arrow functions were introduced in ES6 or ECMAScript 2015.
  let sum = (a, b) => {
      let result = a + b;
      return result;
  }
  let result1 = sum(5,7);
  console.log(result1); // 12
  • Syntax : let myFunction = (arg1, arg2, ...argN) => { statement(s) }
  • Here also parameters are not compulsory and even if {} is not used when there is only one line of code. Example:
  let greet = () => console.log("Hello");
  greet(); // Hello

Difference between let,var and const ?

  • var has global scope and let and const are block/defined scope.
  console.log(a);   // undefined
  var a = 10;
  console.log(b);   // Cannot access 'b' before initialization
  let b = 20;
  console.log(c);
  const c = 30;
  • Main Difference between var and let is Hoisting. variableDeclaration

  • Here we can see a is stored inside Global Scope whereas b and c is stored inside script or local Scope. let and const are the same in terms of hoisting.

  • const must have initializer in its declaration, and we can't reassign value to it but in the case of let we can declare later and change the value also.

Temporal Dead Zone :

  • Time since when the let variable was hoisted until it is initialized some value.
  • Declare and initialize all variables with let to the top to avoid errors and also shrink the temporal dead zone window to zero.

What is DOM(Detail) and Virtual DOM?

  • DOM (The Document Object Model) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content.

  • We can also add events to these elements to make our page more dynamic.

<html lang="en">
  <head>
    <title>JavaScript</title>
    <style>
      body {
        background-color: #8f8f8f;
      }
    </style>
  </head>
  <body>
    <h1>JavaScript</h1>
    <div>
      <h3>Welcome To JavaScript</h3>
      <p>DOM</p>
    </div>
    <script src="./script.js"></script>
  </body>
</html>
  • Let's take the above code and visualize its DOM Tree.

dom-tree.PNG

  • Four Stages to Manipulate HTML Tag:

    1. Finding HTML Element
    2. Changing
    3. Append/Add and Delete/Remove
    4. Add Event Listener

1. Finding HTML Elements:

  • getElementById() : returns the element having the given id value.

  • getElementsByClassName() : returns all the elements having the given class name.

  • querySelector() : returns the first value that matches the selector it’s given. This method can accept all CSS style selectors, allowing it to select by tag, class, or ID.

  • querySelectorAll(): This works similar to above which returns a node list collection of all matching elements.

2. Changing:

  • setAttribute() : Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value.

    Example : element.setAttribute("class", "democlass");

  • classList.add() : The classList is a read-only property of an element that returns a live collection of CSS classes.

    Example: const classes = element.classList

  • textContent : The textContent property sets or returns the text content of the specified node, and all its descendants.

    Example : let text = element.textContent;

3. Append/Add and Delete/Remove:

  • createElement(tagName) : It creates the HTML element specified by tagName.

    Example: let ab =document.createElement("div")

  • appendChild() : It appends a node (element) as the last child of an element.

    Example: document.appendChild(ab)

  • removeChild() : It removes an element's child.

    Example:

    const list = document.getElementById("myList");
    if (list.hasChildNodes()) {
    list.removeChild(list.children[0]);
    }
    

4. Add Event Listener:

  • The method of the eventListener interface sets up a function that will be called whenever the specified event is delivered to the target.

  • Syntax : addEventListener(type, listener)

  • Example of Some Events Types :

    • click : It is fired when we click using pointing device.

    • dblclick : It is fired when we double click using pointing device.

    • mouseenter : It is fired at an Element when a pointing device is initially moved.

    • mouseleave : It is fired at an Element when the cursor of a pointing device is moved out of it.

    • mouseover : It is fired at an Element when a pointing device is used to move the cursor onto the element.

    • input : It is fired at element when element like <input> or <textarea> gets user input

    • change : It is fired at element when elements like radio buttons and checkboxes changed it's original State.

    • blur : It is fired at element when an object loses focus, used for form Validation, it's opposite of focus

    • keyup : It is fired when a key is released.

What is Virtual DOM?

  • The virtual DOM is a fundamental React concept.

  • Instead of allowing the browser to redraw all the page elements after every re-render or DOM update, React uses the concept of virtual DOM to figure out what exactly has changed without involving the actual DOM and then ensures that the actual DOM only repaints the necessary data.

  • Vdom(Virtual DOM) is a programming concept where ideal or virtual representation of ui is kept in memory and sync with real DOM in React.


Explain Closure in JavaScript?

  • Function bundled along with its lexical scope is closure.

  • JavaScript has a lexical scope environment. If a function needs to access a variable, it first goes to its local memory. When it does not find it there, it goes to the memory of its lexical parent.

  function x() {
    var a = 7;
    function y() {
      console.log(a);
    }
    return y;
  }
  var z = x();
  console.log(z); // value of z is entire code of function y.
  • Over here function y() along with its lexical scope i.e. (function x() ) would be called a closure.

  • In Simple Words, closure gives you access to an outer function’s scope from an inner function.

  • In JavaScript, closures are created every time a function is created, at function creation time.


Explain Destructuring? Explain rest and spread operators?

  • Destructuring makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

  • Example :

let sciValue = [2.72, 3.14, 9.81, 37, 100];
let [e, pi, gravity, bodytemp, boil] = sciValue;
console.log(gravity); // 9.81
  • In above Example we can actually declaring e = 2.72 ,pi = 3.14, and vice verca.

Rest

  • The rest parameter syntax allows a function to accept an indefinite number of arguments as an array.

  • Example:

function sumtwo(...omg) {
  console.log(omg);     // [ 1, 2, 3, 4, 5 ]
  let sum = 0;
  for (let a of omg) {
    sum = sum + a;
  }
  return sum;
}
console.log(sumtwo(1, 2, 3, 4, 5));   //15
  • A function definition's last parameter can be prefixed with ... which will cause all remaining parameters to be placed within a standard JavaScript array.

  • Only the last parameter in a function definition can be a rest parameter.

Spread

  • Spread syntax (...) allows an iterable, such as an array or string, to be expanded in places where zero or more arguments or elements are expected.

  • Example:

function sum(x, y) {
  return x + y;
}
let vari = [5, 6];
console.log(sum(...vari));    // 11
  • Spread syntax looks exactly like rest syntax, but spread syntax is the opposite of rest syntax.

  • Spread syntax "expands" an array into its elements, while rest syntax collects multiple elements and "shrink" them into a single element.


Different types of Errors in JavaScript?

- Types of Error:

1 Syntax Error: Uncaught ReferenceError: x is not defined at ...

This Error signifies that x has never been in the scope of the program. This literally means that x was never defined/declared and is being tried to be accessed.

2 Reference Error: Uncaught ReferenceError: cannot access 'a' before initialization

This Error signifies that 'a' cannot be accessed because it is declared as 'let' and since it is not assigned a value, it is its Temporal Dead Zone. Thus, this error occurs.

3 Type Error: Uncaught SyntaxError: Missing initializer in const declaration

This Error signifies that we haven't initialized or assigned value to a const declaration.


What is BOM(browser object model)?

  • The Browser Object Model (BOM) allows JavaScript to talk to the browser about matters other than the content of the page.

  • The BOM is a browser-specific convention referring to all the objects exposed by the web browser.

    BOM

  • Properties:

    • screen.width : returns the users screen width in pixels.
    • screen.height : returns the users screen height in pixels.
    • screen.availWidth : returns the users screen width in pixels, excluding the interface features.
    • screen.availHeight : returns the users screen height in pixels excluding the interface features.
    • screen.colorDepth : returns the bits (number) to be used to display one color. Usually, 24 bit or 32 bit hardware is used for color resolution.
      • 24 bits = 16, 777, 216 different (True Colors)
      • 32 bits = 4, 294, 967, 296 different (Deep Colors)
    • screen.pixelDepth : returns the pixel depth of the screen.
  • BOM Detail Article with Example


Is JavaScript is pass by value or pass by reference?

  • It's always pass by value, but for objects the value of the variable is a reference. Because of this, when you pass an object and change its members, those changes persist outside of the function. This makes it look like pass by reference. But if you actually change the value of the object variable you will see that the change does not persist, proving it's really pass by value.

  • All function arguments are always passed by value.


Explain the use of “Use Strict” in JavaScript.

  • use strict is a JavaScript directive that is introduced in ES5.

  • In strict mode we can’t use a variable without declaring it.

  • Strict mode makes it easier to write "secure" JavaScript.

  • As an example, in normal JavaScript, mistyping a variable name creates a new global variable, but In strict mode, this will throw an error, making it impossible to accidentally create a global variable.


What is Generator function in JavaScript?

  • Generators are functions that can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances.

  • A generator is a process that can be paused and resumed and can yield multiple values.

  • They use the yield keyword to yield execution control back to the calling function and can then resume execution once the next() function is called again

  function* generator(i) {
    yield i;
    yield i + 10;
  }
  const gen = generator(10);
  console.log(gen.next().value);    //10
  console.log(gen.next().value);    //20

What is IIFE in JavaScript?

  • An IIFE (Immediately Invoked Function Expression) is a function that runs as soon as it is defined.

  • This pattern has been used to alias global variables, make variables and functions private, and ensure asynchronous code in loops is executed correctly.

  (function () {
    // …
  })();

  (() => {
    // …
  })();

  (async () => {
    // …
  })();

- Use Cases Of IIFE

  • Avoid polluting the global namespace
  • To create closures
  • Avoid conflict of variable names between libraries and programs.
  • IIFE is used to create private and public variables and methods
  • It is used to execute async and await function

What are promises in Javascript and how to use promises in JS?

  • Promises are used to handle asynchronous operations in JavaScript.

  • Promise object has four states:

    • Pending - Initial state of promise. This state represents that the promise has neither been fulfilled nor been rejected, it is in the pending state.

    • Fulfilled - This state represents that the promise has been fulfilled, meaning the async operation is completed.

    • Rejected - This state represents that the promise has been rejected for some reason, meaning the async operation has failed.

    • Settled - This state represents that the promise has been either rejected or fulfilled.

  • A promise is created using the Promise constructor which takes in a callback function with two parameters, resolve and reject respectively. resolve is a function that will be called, when the async operation has been successfully completed.

  • reject is a function that will be called, when the async operation fails or if some error occurs.

  • Example :

function sumOfThreeElements(...elements) {
  return new Promise((resolve, reject) => {
    if (elements.length > 3) {
      reject("Only Three elements or less are allowed");
    } else {
      let sum = 0;
      let i = 0;
      while (i < elements.length) {
        sum = sum + elements[i];
        i++;
      }
      resolve("Sum has been calculated: " + sum);
    }
  });
}
sumOfThreeElements(4, 5, 6)
  .then((result) => console.log(result))
  .catch((error) => console.log(error));
  • We can consume any promise by attaching then() and catch() methods to the consumer.

    then() method is used to access the result when the promise is fulfilled.

    catch() method is used to access the result/error when the promise is rejected.


Hope You Like the Article, Give your Feedback.

#learncodeonline

#iwritecode

Special Thanks to

Hitesh Sir Anurag Sir learncodeonline.in ineuron.ai