window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-63172957-1');
Created by potrace 1.16, written by Peter Selinger 2001-2019
Back to blog

Javascript Interview Questions & Answers (Part 3)

Article contents:

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,

document.cookie = "username=John";

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, user profile can be stored in a cookie.
  • Next time the user visits the page, the cookie remembers user profile.

There are 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 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";

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 doesn’t allow to delete a cookie unless you specify a path parameter.

How do you access web storage?

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

What are the methods available on session storage?

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

// Remove all saved data from sessionStorage

What is a storage event and its event handler?

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 storage 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 + '.');

How do you check web storage browser support?

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..

What is a promise?

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 would be as below

const promise = new Promise(function(resolve, reject) {
  // promise description

What is a callback function?

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


Why do we need callbacks?

The callbacks are needed because javascript is a 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 first function invoking an API call(simulated by setTimeout) and 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');

// Second function called
// First function called

As observed from the output, javascript didn’t wait for the response of first function and remaining code block get executed. So callbacks used in a way to make sure that certain code doesn’t execute until other code finished execution.

What is a strict mode in javascript?

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.

Why do you need strict mode?

Strict mode is useful to write “secure” JavaScript by notifying “bad syntax” into real errors. For example, it eliminates accidentally creating a global variable by throwing an error and also throws an error for assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object.

How do you declare strict mode?

The strict mode is declared by adding “use strict”; to the beginning of a script or a function. If declare at the beginning of a script, it has global scope.

"use strict";
x = 3.14; // This will cause an error because x is not declared

and if you declare inside a function, it has local scope

x = 3.14; // This will not cause an error.

function myFunction() {
"use strict";
y = 3.14; // This will cause an error

What is the purpose of double exclamation?

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.

What is the purpose of delete operator?

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"}

What is typeof operator?

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"

What is undefined property?

The undefined property indicates that a variable has not been assigned a value, or not declared at all. The type of undefined value is undefined too.

var user; // Value is undefined, type is undefined
console.log(typeof(user)) //undefined

Any variable can be emptied by setting the value to undefined.

user = undefined

What is null value?

The value null represents the intentional absence of any object value. It is one of JavaScript’s primitive values. The type of null value is object. You can empty the variable by setting the value to null.

var user = null;
console.log(typeof(user)) //object

What is eval?

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

How do you access history in javascript?

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() {
function goForward() {

Note: You can also access history without the window prefix.

What are the javascript data types?

Below is the list of javascript data types available

  • Number
  • String
  • Boolean
  • Object
  • Undefined

What is isNaN?

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

What are global variables?

Global variables are those that are available throughout the length of the code without any scope. The var keyword is used to declare a local variable but if you omit it then it will become a global variable

msg = "Hello" // var is missing, it becomes global variable

Back to blog

Wordpress Developer Loader, Web Developer Loader , Front End Developer Loader Jack is thinking