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

Javascript Interview Questions & Answers (Part 5)

Article index:

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);
localStorage.getItem('logo');

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
sessionStorage.removeItem('key');

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

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.');
  callback(name);
}

outerFunction(callbackFunction);

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

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



Back to blog

</html>
Wordpress Developer Loader, Web Developer Loader , Front End Developer Loader Jack is thinking