JavaScript interview questions and answer

JavaScript interview questions and answer

Q. What are the possible ways to create objects in JavaScript

A. There are many ways to create objects in javascript as below


Object constructor:


The simplest way to create an empty object is using the Object constructor. Currently, this approach is not recommended.


var object = new Object();


An object's creating method:


The create method of Object creates a new object by passing the prototype object as a parameter

var object = Object.create(null);


Object literal syntax:


The object literal syntax (or object initializer), is a comma-separated set of name-value pairs wrapped in curly braces.

var object = {

     name: "Sudheer"

     age: 34

};


Object literal property values can be of any data type, including array, function, and nested object.

Note: This is the easiest way to create an object


Function constructor:


Create any function and apply the new operator to create object instances,


function Person(name){

   this.name=name;

   this.age=21;

}

var object = new Person("Sudheer");


Function constructor with prototype:


This is similar to function constructor but it uses prototype for their properties and methods,


function Person(){}

Person.prototype.name = "Sudheer";

var object = new Person();

This is equivalent to an instance created with an object creating a method with a function prototype and then calling that function with an instance and parameters as arguments.


function func {};


new func(x, y, z);


(OR)


// Create a new instance using function prototype.

var newInstance = Object.create(func.prototype)


// Call the function

var result = func.call(newInstance, x, y, z),


// If the result is a non-null object then use it otherwise just use the new instance.

console.log(result && typeof result === 'object' ? result : newInstance);


ES6 Class syntax:


ES6 introduces class feature to create the objects


class Person {

   constructor(name) {

      this.name = name;

   }

}


var object = new Person("Sudheer");


Singleton pattern:


A Singleton is an object which can only be instantiated one time. Repeated calls to its constructor return the same instance and this way one can ensure that they don't accidentally create multiple instances.


var object = new function(){

   this.name = "Sudheer";

}

Q. What is a prototype chain?

A. Prototype chaining is used to build new types of objects based on existing ones. It is similar to inheritance in a class-based language.

The prototype on object instance is available through Object.getPrototypeOf(object) or proto property whereas prototype on constructors function is available through Object. prototype.

What is the difference between Call, Apply and Bind

The difference between Call, Apply, and Bind can be explained with the below examples,


Call: The call() method invokes a function with a given this value and arguments provided one by one


var employee1 = {firstName: 'John', lastName: 'Rodson'};

var employee2 = {firstName: 'Jimmy', lastName: 'Baily'};


function invite(greeting1, greeting2) {

    console.log(greeting1 + ' ' + this.firstName + ' ' + this.lastName+ ', '+ greeting2);

}


invite.call(employee1, 'Hello', 'How are you?'); // Hello John Robson, How are you?

invite.call(employee2, 'Hello', 'How are you?'); // Hello Jimmy Baily, How are you?

Apply: Invokes the function with a given this value and allows you to pass in arguments as an array


var employee1 = {firstName: 'John', lastName: 'Rodson'};

var employee2 = {firstName: 'Jimmy', lastName: 'Baily'};


function invite(greeting1, greeting2) {

    console.log(greeting1 + ' ' + this.firstName + ' ' + this.lastName+ ', '+ greeting2);

}


invite.apply(employee1, ['Hello', 'How are you?']); // Hello John Robson, How are you?

invite.apply(employee2, ['Hello', 'How are you?']); // Hello Jimmy Baily, How are you?

bind: returns a new function, allowing you to pass any number of arguments


var employee1 = {firstName: 'John', lastName: 'Rodson'};

var employee2 = {firstName: 'Jimmy', lastName: 'Baily'};


function invite(greeting1, greeting2) {

    console.log(greeting1 + ' ' + this.firstName + ' ' + this.lastName+ ', '+ greeting2);

}


var inviteEmployee1 = invite.bind(employee1);

var inviteEmployee2 = invite.bind(employee2);

inviteEmployee1('Hello', 'How are you?'); // Hello John Robson, How are you?

inviteEmployee2('Hello', 'How are you?'); // Hello Jimmy Baily, How are you?

Call and apply are pretty interchangeable. Both execute the current function immediately. You need to decide whether it’s easier to send in an array or a comma-separated list of arguments. You can remember by treating Call is for a comma (separated list) and Apply is for Array.


Whereas Bind creates a new function that will have this set to the first parameter passed to bind().

Q. What are JSON and its common operations?

A. JSON is a text-based data format following JavaScript object syntax, which was popularized by Douglas Crockford. It is useful when you want to transmit data across a network and it is basically just a text file with an extension of .json, and a MIME type of application/JSON


Parsing: Converting a string to a native object


JSON.parse(text)

Stringification: converting a native object to a string so it can be transmitted across the network


JSON.stringify(object)

Q. What is the purpose of the array slice method?

A. The slice() method returns the selected elements in an array as a new array object. It selects the elements starting at the given start argument and ends at the given optional end argument without including the last element. If you omit the second argument then it selects till the end.


Some of the examples of this method are,


let arrayIntegers = [1, 2, 3, 4, 5];

let arrayIntegers1 = arrayIntegers.slice(0,2); // returns [1,2]

let arrayIntegers2 = arrayIntegers.slice(2,3); // returns [3]

let arrayIntegers3 = arrayIntegers.slice(4); //returns [5]

Note: Slice method won't mutate the original array but it returns the subset as a new array.

Q. What is the purpose of the array splice method?

A. The splice() method is used to either adds/remove items to/from an array and then return the removed item. The first argument specifies the array position for insertion or deletion whereas the optional second argument indicates the number of elements to be deleted. Each additional argument is added to the array.


Some of the examples of this method are,


let arrayIntegersOriginal1 = [1, 2, 3, 4, 5];

let arrayIntegersOriginal2 = [1, 2, 3, 4, 5];

let arrayIntegersOriginal3 = [1, 2, 3, 4, 5];


let arrayIntegers1 = arrayIntegersOriginal1.splice(0,2); // returns [1, 2]; original array: [3, 4, 5]

let arrayIntegers2 = arrayIntegersOriginal2.splice(3); // returns [4, 5]; original array: [1, 2, 3]

let arrayIntegers3 = arrayIntegersOriginal3.splice(3, 1, "a", "b", "c"); //returns [4]; original array: [1, 2, 3, "a", "b", "c", 5]

Note: Splice method modifies the original array and returns the deleted array.

Q. What is the difference between slice and splice

A. Some of the major differences in these as below:- Slice Doesn't modify the original array(immutable) while Splice Modifies the original array(mutable) Slice Returns the subset of the original array while Splice Returns the deleted elements as array Slice Used to pick the elements from the array while Splice Used to insert or delete elements to/from the array


Q. How do you compare Object and Map

A. Objects are similar to Maps in that both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. Due to this reason, Objects have been used as Maps historically. But there are important differences that make using a Map preferable in certain cases.
  • The keys of an Object are Strings and Symbols, whereas they can be any value for a Map, including functions, objects, and any primitive.
  • The keys in Map are ordered while keys added to Object are not. Thus, when iterating over it, a Map object returns keys in order of insertion.
  • You can get the size of a Map easily with the size property, while the number of properties in an Object must be determined manually.
  • A Map is iterable and can thus be directly iterated, whereas iterating over an Object requires obtaining its keys in some fashion and iterating over them.
  • An Object has a prototype, so there are default keys in the map that could collide with your keys if you're not careful. As of ES5, this can be bypassed by using map = Object.create(null), but this is seldom done.
  • A Map may perform better in scenarios involving frequent addition and removal of key pairs.

Q. What is the difference between == and === operators?

A. JavaScript provides both strict(===, !==) and type-converting(==, !=) equality comparison. The strict operators take the type of variable into consideration, while non-strict operators make type correction/conversion based upon values of variables. The strict operators follow the below conditions for different types, 1) Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions. 2) Two numbers are strictly equal when they are numerically equal. i.e, Having the same number value. There are two special cases in this, a) NaN is not equal to anything, including NaN. b) Positive and negative zeros are equal to one another. 3) Two Boolean operands are strictly equal if both are true or both are false. 4) Two objects are strictly equal if they refer to the same Object. 5) Null and Undefined types are not equal with ===, but equal with ==. i.e, null===undefined --> false but null==undefined --> true

Some of the example which covers the above cases, 0 == false // true 0 === false // false 1 == "1" // true 1 === "1" // false null == undefined // true null === undefined // false '0' == false // true '0' === false // false []==[] or []===[] //false, refer different objects in memory {}=={} or {}==={} //false, refer different objects in memory

Q. What are lambda or arrow functions

A. An arrow function is a shorter syntax for a function expression and does not have its own this, arguments, super, or new.target. These functions are best suited for non-method functions, and they cannot be used as constructors.

Q. What is a first-class function

A. In Javascript, functions are first-class objects. First-class functions mean when functions in that language are treated like any other variable.

For example, in such a language, a function can be passed as an argument to other functions, can be returned by another function, and can be assigned as a value to a variable. For example, in the below example, handler functions assigned to a listener

const handler = () => console.log ('This is a click handler function');
document.addEventListener ('click', handler);

Q. What is the difference between let and var

A. You can list out the differences in a tabular format
varlet
It is been available from the beginning of JavaScriptIntroduced as part of ES6
It has a function scopeIt has a block scope
Variables will be hoistedHoisted but not initialized

Let's take an example to see the difference,

function userDetails(username) {

   if(username) {

     console.log(salary); // undefined due to hoisting

     console.log(age); // ReferenceError: Cannot access 'age' before initialization

     let age = 30;

     var salary = 10000;

   }

   console.log(salary); //10000 (accessible to due function scope)

   console.log(age); //error: age is not defined(due to block scope)

}

userDetails('John');

Q. What is Hoisting

A. Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. Remember that JavaScript only hoists declarations, not initialization. Let's take a simple example of variable hoisting,

console.log(message); //output : undefined
var message = 'The variable Has been hoisted';

The above code looks like as below to the interpreter,

var message;
console.log(message);
message = 'The variable Has been hoisted';


Q. What are closures

A. A closure is the combination of a function and the lexical environment within which that function was declared. i.e, It is an inner function that has access to the outer or enclosing function’s variables. The closure has three scope chains

Own scope where variables defined between its curly brackets
Outer function’s variables
Global variables
Let's take an example of closure concept,

function Welcome(name){
  var greetingInfo = function(message){
   console.log(message+' '+name);
  }
return greetingInfo;
}
var myFunction = Welcome('John');
myFunction('Welcome '); //Output: Welcome John
myFunction('Hello Mr.'); //output: Hello Mr.John
As per the above code, the inner function(i.e, greetingInfo) has access to the variables in the outer function scope(i.e, Welcome) even after the outer function has returned.

Q. What are classes in ES6

A. In ES6, Javascript classes are primarily syntactic sugar over JavaScript’s existing prototype-based inheritance. For example, the prototype based inheritance written in function expression as below,

function Bike(model,color) {
    this.model = model;
    this.color = color;
}

Bike.prototype.getDetails = function() {
    return this.model + ' bike has' + this.color + ' color';
};
Whereas ES6 classes can be defined as an alternative

class Bike{
  constructor(color, model) {
    this.color= color;
    this.model= model;
  }

  getDetails() {
    return this.model + ' bike has' + this.color + ' color';
  }
}

Q. What are modules
A. Modules refer to small units of independent, reusable code and also act as the foundation of many JavaScript design patterns. Most of the JavaScript modules export an object literal, a function, or a constructor


Q. Why do you need modules
A. Below are the list of benefits using modules in javascript ecosystem

Maintainability
Reusability
Namespacing


Q. What is scope in javascript
A. Scope is the accessibility of variables, functions, and objects in some particular part of your code during runtime. In other words, scope determines the visibility of variables and other resources in areas of your code.


Q. What is a service worker
A. A Service worker is basically a script (JavaScript file) that runs in the background, separate from a web page and provides features that don't need a web page or user interaction. Some of the major features of service workers are Rich offline experiences(offline first web application development), periodic background syncs, push notifications, intercept and handle network requests and programmatically managing a cache of responses.


Q. How do you manipulate DOM using a service worker
A. Service worker can't access the DOM directly. But it can communicate with the pages it controls by responding to messages sent via the postMessage interface, and those pages can manipulate the DOM.


Q. How do you reuse information across service worker restarts
A. The problem with service worker is that it gets terminated when not in use, and restarted when it's next needed, so you cannot rely on global state within a service worker's onfetch and onmessage handlers. In this case, service workers will have access to IndexedDB API in order to persist and reuse across restarts.


Q. What is IndexedDB
A. IndexedDB is a low-level API for client-side storage of larger amounts of structured data, including files/blobs. This API uses indexes to enable high-performance searches of this data.


Q. What is a web storage
A. Web storage is an API that provides a mechanism by which browsers can store key/value pairs locally within the user's browser, in a much more intuitive fashion than using cookies. Web storage provides two mechanisms for storing data on the client.

Local storage: It stores data for current origin with no expiration date.
Session storage: It stores data for one session and the data is lost when the browser tab is closed.

Q. What is a Cookie
A. A cookie is a piece of data that is stored on your computer to be accessed by your browser. Cookies are saved as key/value pairs. For example, you can create a cookie named username as below,

Q. Why do you need a Cookie
A. Cookies are used to remember information about the user profile(such as username). It basically involves two steps,

When a user visits a web page, the user profile can be stored in a cookie.
Next time the user visits the page, the cookie remembers the user profile.

Q. What are the options in a cookie
A. There are a few below options available for a cookie,

By default, the cookie is deleted when the browser is closed but you can change this behavior by setting the expiry date (in UTC time).
document.cookie = "username=John; expires=Sat, 8 Jun 2019 12:00:00 UTC";
By default, the cookie belongs to a current page. But you can tell the browser what path the cookie belongs to using a path parameter.
document.cookie = "username=John; path=/services";

Q. How do you delete a cookie
A. You can delete a cookie by setting the expiry date as a passed date. You don't need to specify a cookie value in this case. For example, you can delete a username cookie in the current page as below.

document.cookie = "username=; expires=Fri, 07 Jun 2019 00:00:00 UTC; path=/;";
Note: You should define the cookie path option to ensure that you delete the right cookie. Some browsers don't allow to delete a cookie unless you specify a path parameter.

Q. What are the differences between a cookie, local storage, and session storage

A. Below are some of the differences between a cookie, local storage, and session storage,
FeatureCookieLocal storageSession storage
Accessed on client or server sideBoth server-side & client-sideclient-side onlyclient-side only
LifetimeAs configured using Expires optionuntil deleteduntil tab is closed
SSL supportSupportedNot supportedNot supported
Maximum data size4KB5 MB5MB

Q. What is the main difference between localStorage and sessionStorage

A. LocalStorage is the same as SessionStorage but it persists the data even when the browser is closed and reopened(i.e it has no expiration time) whereas in sessionStorage data gets cleared when the page session ends.

Q. How do you access web storage

A. The Window object implements the WindowLocalStorage and WindowSessionStorage objects which has localStorage(window.localStorage) and sessionStorage(window.sessionStorage) properties respectively. These properties create an instance of the Storage object, through which data items can be set, retrieved and removed for a specific domain and storage type (session or local). For example, you can read and write on local storage objects as below

localStorage.setItem('logo', document.getElementById('logo').value);
localStorage.getItem('logo');

Q. What are the methods available on session storage

A. The session storage provided methods for reading, writing and clearing the session data

// Save data to sessionStorage
sessionStorage.setItem('key', 'value');

// Get saved data from sessionStorage
let data = sessionStorage.getItem('key');

// Remove saved data from sessionStorage
sessionStorage.removeItem('key');

// Remove all saved data from sessionStorage
sessionStorage.clear();

Q. What is a storage event and its event handler

A. The StorageEvent is an event that fires when a storage area has been changed in the context of another document. Whereas onstorage property is an EventHandler for processing storage events. The syntax would be as below

 window.onstorage = functionRef;
Let's take the example usage of onstorage event handler which logs the storage key and it's values

window.onstorage = function(e) {
  console.log('The ' + e.key +
    ' key has been changed from ' + e.oldValue +
    ' to ' + e.newValue + '.');
};

Q. Why do you need web storage

A. Web storage is more secure, and large amounts of data can be stored locally, without affecting website performance. Also, the information is never transferred to the server. Hence this is a more recommended approach than Cookies.

Q. How do you check web storage browser support

A. You need to check browser support for localStorage and sessionStorage before using web storage,

if (typeof(Storage) !== "undefined") {
  // Code for localStorage/sessionStorage.
} else {
  // Sorry! No Web Storage support..
}

Q. How do you check web workers browser support

A. You need to check browser support for web workers before using it

if (typeof(Worker) !== "undefined") {
  // code for Web worker support.
} else {
  // Sorry! No Web Worker support..
}

Q. Give an example of a web worker

A. You need to follow below steps to start using web workers for counting example

Create a Web Worker File: You need to write a script to increment the count value. Let's name it as counter.js
let i = 0;

function timedCount() {
  i = i + 1;
  postMessage(i);
  setTimeout("timedCount()",500);
}

timedCount();
Here postMessage() method is used to post a message back to the HTML page

Create a Web Worker Object: You can create a web worker object by checking for browser support. Let's name this file as web_worker_example.js
if (typeof(w) == "undefined") {
  w = new Worker("counter.js");
}
and we can receive messages from web worker

w.onmessage = function(event){
  document.getElementById("message").innerHTML = event.data;
};
Terminate a Web Worker: Web workers will continue to listen for messages (even after the external script is finished) until it is terminated. You can use the terminate() method to terminate listening to the messages.
w.terminate();
Reuse the Web Worker: If you set the worker variable to undefined you can reuse the code
w = undefined;

Q. What is a promise

A. A promise is an object that may produce a single value some time in the future with either a resolved value or a reason that it’s not resolved(for example, network error). It will be in one of the 3 possible states: fulfilled, rejected, or pending.

The syntax of Promise creation looks like below,

    const promise = new Promise(function(resolve, reject) {
      // promise description
    })
The usage of a promise would be as below,

const promise = new Promise(resolve => {
  setTimeout(() => {
    resolve("I'm a Promise!");
  }, 5000);
}, reject => {

});

promise.then(value => console.log(value));

Q. Why do you need a promise

A. Promises are used to handle asynchronous operations. They provide an alternative approach for callbacks by reducing the callback hell and writing the cleaner code.

Q. What are the three states of promise

A. Promises have three states:

Pending: This is an initial state of the Promise before an operation begins
Fulfilled: This state indicates that the specified operation was completed.
Rejected: This state indicates that the operation did not complete. In this case an error value will be thrown.

Q. What is a callback function

A. A callback function is a function passed into another function as an argument. This function is invoked inside the outer function to complete an action. Let's take a simple example of how to use callback function

function callbackFunction(name) {
  console.log('Hello ' + name);
}

function outerFunction(callback) {
  let name = prompt('Please enter your name.');
  callback(name);
}

outerFunction(callbackFunction);

Q. Why do we need callbacks

A. The callbacks are needed because javascript is an event driven language. That means instead of waiting for a response javascript will keep executing while listening for other events. Let's take an example with the first function invoking an API call(simulated by setTimeout) and the next function which logs the message.

function firstFunction(){
  // Simulate a code delay
  setTimeout( function(){
    console.log('First function called');
  }, 1000 );
}
function secondFunction(){
  console.log('Second function called');
}
firstFunction();
secondFunction();

Output
// Second function called
// First function called
As observed from the output, javascript didn't wait for the response of the first function and the remaining code block got executed. So callbacks are used in a way to make sure that certain code doesn’t execute until the other code finishes execution.

Q. What is a callback hell

A. Callback Hell is an anti-pattern with multiple nested callbacks which makes code hard to read and debug when dealing with asynchronous logic. The callback hell looks like below,

async1(function(){
    async2(function(){
        async3(function(){
            async4(function(){
                ....
            });
        });
    });
});

Q. What are server-sent events

A. Server-sent events (SSE) is a server push technology enabling a browser to receive automatic updates from a server via HTTP connection without resorting to polling. These are a one way communications channel - events flow from server to client only. This has been used in Facebook/Twitter updates, stock price updates, news feeds etc.

Q. How do you receive server-sent event notifications

A. The EventSource object is used to receive server-sent event notifications. For example, you can receive messages from server as below,

if(typeof(EventSource) !== "undefined") {
  var source = new EventSource("sse_generator.js");
  source.onmessage = function(event) {
    document.getElementById("output").innerHTML += event.data + "<br>";
  };
}

Q. How do you check browser support for server-sent events

A. You can perform browser support for server-sent events before using it as below,

if(typeof(EventSource) !== "undefined") {
  // Server-sent events supported. Let's have some code here!
} else {
  // No server-sent events supported
}

Q. What are the events available for server-sent events

A. Below are the list of events available for server-sent events

Event Description
onopen It is used when a connection to the server is opened
onmessage This event is used when a message is received
onerror It happens when an error occurs

Q. What are the main rules of promise

A. A promise must follow a specific set of rules,
  • A promise is an object that supplies a standard-compliant .then() method
  • A pending promise may transition into either fulfilled or rejected state
  • A fulfilled or rejected promise is settled and it must not transition into any other state.
  • Once a promise is settled, the value must not change.

Q. What is promise.all

A. Promise.all is a promise that takes an array of promises as an input (an iterable), and it gets resolved when all the promises get resolved or any one of them gets rejected. For example, the syntax of promise.all method is below,

Promise.all([Promise1, Promise2, Promise3]) .then(result) => {   console.log(result) }) .catch(error => console.log(`Error in promises ${error}`))
Note: Remember that the order of the promises(output the result) is maintained as per input order.

Q. What is the purpose of the race method in promise

A. Promise.race() method will return the promise instance which is firstly resolved or rejected. Let's take an example of race() method where promise2 is resolved first

var promise1 = new Promise(function(resolve, reject) {
    setTimeout(resolve, 500, 'one');
});
var promise2 = new Promise(function(resolve, reject) {
    setTimeout(resolve, 100, 'two');
});

Promise.race([promise1, promise2]).then(function(value) {
  console.log(value); // "two" // Both promises will resolve, but promise2 is faster
});

Q. What is a strict mode in javascript

A. Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a “strict” operating context. This way it prevents certain actions from being taken and throws more exceptions. The literal expression "use strict"; instructs the browser to use the javascript code in the Strict mode.

Q. What is the purpose of double exclamation

A. The double exclamation or negation(!!) ensures the resulting type is a boolean. If it was falsey (e.g. 0, null, undefined, etc.), it will be false, otherwise, true. For example, you can test IE version using this expression as below,

let isIE8 = false;
isIE8 = !! navigator.userAgent.match(/MSIE 8.0/);
console.log(isIE8); // returns true or false
If you don't use this expression then it returns the original value.

console.log(navigator.userAgent.match(/MSIE 8.0/));  // returns either an Array or null
Note: The expression !! is not an operator, but it is just twice of ! operator.

Q. What is the purpose of the delete operator

A. The delete keyword is used to delete the property as well as its value.

var user= {name: "John", age:20};
delete user.age;

console.log(user); // {name: "John"}

Q. What is the typeof operator

A. You can use the JavaScript typeof operator to find the type of a JavaScript variable. It returns the type of a variable or an expression.

typeof "John Abraham"     // Returns "string"
typeof (1 + 2)        // Returns "number"

Q. What is the difference between null and undefined

A. Below are the main differences between null and undefined,

Null Undefined
It is an assignment value which indicates that variable points to no object. It is not an assignment value where a variable has been declared but has not yet been assigned a value.
Type of null is object Type of undefined is undefined
The null value is a primitive value that represents the null, empty, or non-existent reference. The undefined value is a primitive value used when a variable has not been assigned a value.
Indicates the absence of a value for a variable Indicates absence of variable itself
Converted to zero (0) while performing primitive operations Converted to NaN while performing primitive operations

Q. What is eval

A. The eval() function evaluates JavaScript code represented as a string. The string can be a JavaScript expression, variable, statement, or sequence of statements.

console.log(eval('1 + 2')); //  3

Q. How do you access history in javascript

A. The window.history object contains the browser's history. You can load previous and next URLs in the history using back() and next() methods.

function goBack() {
  window.history.back()
}
function goForward() {
  window.history.forward()
}
Note: You can also access history without window prefix.

Q. What is isNaN

A. The isNaN() function is used to determine whether a value is an illegal number (Not-a-Number) or not. i.e, This function returns true if the value equates to NaN. Otherwise it returns false.

isNaN('Hello') //true
isNaN('100') //false

Q. What are the differences between undeclared and undefined variables

A. Below are the major differences between undeclared and undefined variables,
undeclared undefined
These variables do not exist in a program and are not declared These variables declared in the program but have not assigned any value
If you try to read the value of an undeclared variable, then a runtime error is encountered If you try to read the value of an undefined variable, an undefined value is returned.

Q. What is the difference between window and document

A. Below are the main differences between window and document,

Window Document
It is the root level element in any web page It is the direct child of the window object. This is also known as Document Object Model(DOM)
By default window object is available implicitly in the page You can access it via window.document or document.
It has methods like alert(), confirm() and properties like document, location It provides methods like getElementById, getElementsByTagName, createElement etc

Q. What is event bubbling

A. Event bubbling is a type of event propagation where the event first triggers on the innermost target element, and then successively triggers on the ancestors (parents) of the target element in the same nesting hierarchy till it reaches the outermost DOM element.

Q. What is event capturing

A. Event capturing is a type of event propagation where the event is first captured by the outermost element, and then successively triggers on the descendants (children) of the target element in the same nesting hierarchy till it reaches the innermost DOM element.

Q. How do you submit a form using JavaScript

A. You can submit a form using document.forms[0].submit(). All the form input's information is submitted using onsubmit event handler

function submit() {
    document.forms[0].submit();
}

Q. What is the purpose of void 0

A. Void(0) is used to prevent the page from refreshing. This will be helpful to eliminate the unwanted side-effect because it will return the undefined primitive value. It is commonly used for HTML documents that use href="JavaScript:Void(0);" within an <a> element. i.e, when you click a link, the browser loads a new page or refreshes the same page. But this behavior will be prevented using this expression. For example, the below link notify the message without reloading the page

<a href="JavaScript:void(0);" onclick="alert('Well done!')">Click Me!</a>

Q. What is the use of the preventDefault method

A. The preventDefault() method cancels the event if it is cancelable, meaning that the default action or behavior that belongs to the event will not occur. For example, prevent form submission when clicking on submit button and prevent opening the page URL when clicking on hyperlinks are some common use cases.

document.getElementById("link").addEventListener("click", function(event){
 event.preventDefault();
});
Note: Remember that not all events are cancelable.

Q. What is the use of the stopPropagation method

A. The stopPropagation method is used to stop the event from bubbling up the event chain. For example, the below-nested divs with the stopPropagation method prevents default event propagation when clicking on nested div(Div1)

<p>Click DIV1 Element</p>
<div onclick="secondFunc()">DIV 2
  <div onclick="firstFunc(event)">DIV 1</div>
</div>

<script>
function firstFunc(event) {
  alert("DIV 1");
  event.stopPropagation();
}

function secondFunc() {
  alert("DIV 2");
}
</script>

Q. What is ECMAScript

A. ECMAScript is the scripting language that forms the basis of JavaScript. ECMAScript is standardized by the ECMA International standards organization in the ECMA-262 and ECMA-402 specifications. The first edition of ECMAScript was released in 1997.

Q. What is JSON

A. JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging. It is based on a subset of JavaScript language in the way objects are built-in JavaScript.

Q. What are PWAs

A. Progressive web applications (PWAs) are a type of mobile app delivered through the web, built using common web technologies including HTML, CSS, and JavaScript. These PWAs are deployed to servers, accessible through URLs, and indexed by search engines.

Q. How do you validate an email in javascript

A. You can validate an email in javascript using regular expressions. It is recommended to do validations on the server-side instead of the client-side. Because the javascript can be disabled on the client-side.

function validateEmail(email) {
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(String(email).toLowerCase());
}

Q. How do get query string values in javascript

A. You can use URLSearchParams to get query string values in javascript. Let's see an example to get the client code value from URL query string,

const urlParams = new URLSearchParams(window.location.search);
const clientCode = urlParams.get('clientCode');

Q. How do you loop through or enumerate javascript object

A. You can use the for-in loop to loop through javascript object. You can also make sure that the key you get is an actual property of an object, and doesn't come from the prototype using hasOwnProperty method.

var object = {
    "k1": "value1",
    "k2": "value2",
    "k3": "value3"
};

for (var key in object) {
    if (object.hasOwnProperty(key)) {
        console.log(key + " -> " + object[key]); // k1 -> value1 ...
    }
}

Q. How do you display the current date in javascript

A. You can use new Date() to generate a new Date object containing the current date and time. For example, let's display the current date in mm/dd/yyyy

var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();

today = mm + '/' + dd + '/' + yyyy;
document.write(today);

Q. How do you compare two date objects

A. You need to use date.getTime() method to compare date values instead of comparison operators (==, !=, ===, and !== operators)

var d1 = new Date();
var d2 = new Date(d1);
console.log(d1.getTime() === d2.getTime()); //True
console.log(d1 === d2); // False

Q. What are break and continue statements

A. The break statement is used to "jump out" of a loop. i.e, It breaks the loop and continues executing the code after the loop.

for (i = 0; i < 10; i++) {
  if (i === 5) { break; }
  text += "Number: " + i + "<br>";
}
The continue statement is used to "jump over" one iteration in the loop. i.e, It breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

for (i = 0; i < 10; i++) {
    if (i === 5) { continue; }
    text += "Number: " + i + "<br>";
}

Q. How do you define JSON arrays

A. JSON arrays are written inside square brackets and arrays contain javascript objects. For example, the JSON array of users would be as below,

"users":[
  {"firstName":"John", "lastName":"Abrahm"},
  {"firstName":"Anna", "lastName":"Smith"},
  {"firstName":"Shane", "lastName":"Warn"}
]

Q. What is the purpose of exec method

A. The purpose of exec method is similar to test method but it executes a search for a match in a specified string and returns a result array, or null instead of returning true/false.

var pattern = /you/;
console.log(pattern.exec("How are you?")); //["you", index: 8, input: "How are you?", groups: undefined]

Q. How do you convert date to another timezone in javascript

A. You can use the toLocaleString() method to convert dates in one timezone to another. For example, let's convert current date to British English timezone as below,

console.log(event.toLocaleString('en-GB', { timeZone: 'UTC' })); //29/06/2019, 09:56:00

Q. What is the difference between proto and prototype

A. The __proto__ object is the actual object that is used in the lookup chain to resolve methods, etc. Whereas prototype is the object that is used to build __proto__ when you create an object with new

( new Employee ).__proto__ === Employee.prototype;
( new Employee ).prototype === undefined;