Javascript Interview Questions
1. What is Javascript
Javascript is a scripting language built by Brendan Eich in the year 1995. It was formerly known as Mocha. Javascript has several applications in the domains including web development, mobile development, game development and many more.
2. How does Javascript runs on browser?
Javascript run on the engine specified by browser. The engines have the parser which generates the syntax tree. There are several engines that are used currently. Few of them are -
- Chrome V8
- Spider Monkey
- Javascript Core Webkit
- Chakra
3. What are the data types in Javascript?
Following are the datatypes in Javascript -
- Number - To store integers (24, 3.5, 1000)
- String - To store text. Strings are immutable ("Hello World")
- Boolean - To store either true or false
- Null - To store only one value i.e., null
- Undefined - To store only one value i.e., undefined
- BigInt - To store large integers beyond safe integer limit. "n" is added at the end (9007199254741000n)
- Symbol - Symbol is a primitive type for unique identifiers
4. What is difference between null and undefined?
null means the value of any variable is empty. On the other side, undefined means the value is not yet assigned.
E.g:
let unassigned;
let obj = {
key1: null
}
console.log(unassigned); // undefined
console.log(obj.key1) // null
5. What is isNaN?
isNaN is function that returns true if the argument passed is "Not a Number".
E.g:
console.log(isNaN(2)) // false
console.log(isNaN('javascript')) // true
6. What is a function?
A function in Javascript is a block of code to store and execute specific type of task.
function sayHello() {
return 'Hello';
}
console.log(sayHello()); // Hello
7. Explain the different types of functions in Javascript
Following are the types of functions -
- Named Function - a function with a name
- Anonymous Function - a function without a name and is assigned to a variable
- Immediately Invoked Function Expression - immediately invoked when defined
- Higher Order Function - takes function as parameter and returns a function
// Named function
function myFunction() {}
// Anonymous function
var myFunction = function() {}
// Immediately Invoked Function Expression
(function() {
console.log('Hello')
})();
// Higher Order Function
function myFunction(f) {
return f;
}
function sayHello() {
return 'Hello';
}
myFunction(sayHello)() // Hello
8. What is call, apply and bind?
- Call invokes a function for the current object (this)
E.g.
const obj1 = {name: 'Tom'};
const obj2 = {name: 'Bruce'};
function fullName(lastName) {
console.log(`${this.name} ${lastName}`);
}
fullName.call(obj1, 'Cruise'); // Tom Cruise
fullName.call(obj2, 'Wayne'); // Bruce Wayne
- Apply is same as Call except that it accepts argument in the form of array
E.g.
const obj1 = {name: 'Tom'};
const obj2 = {name: 'Bruce'};
function fullName(lastName) {
console.log(`${this.name} ${lastName}`);
}
fullName.apply(obj1, ['Cruise']); // Tom Cruise
fullName.apply(obj2, ['Wayne']); // Bruce Wayne
- Bind return a function which is binded with the current object
E.g.
const obj1 = {name: 'Tom'};
const obj2 = {name: 'Bruce'};
function fullName(lastName) {
console.log(`${this.name} ${lastName}`);
}
const tomFull = fullName.bind(obj1);
const bruceFull = fullName.bind(obj2);
tomFull('Cruise'); // Tom Cruise
bruceFull('Wayne'); // Bruce Wayne
9. What is DOM?
DOM stands for Document Object Model. It is a representation of HTML nodes/objects as a tree. It allows JavaScript to dynamically create, update, delete and access the HTML elements.
HTML elements can be accessed using document
object which is a child of window
object.
Following are few methods from document object -
- createElement
- removeChild
- getElementById
- appendChild
10. What is Web Storage?
Web Storage is used to store data on client (browser). The storage limit is 5MB more than tranditional cookies (4KB).
Web Storage is a great way to store and persist data on client side which may include (theme preference, tokens etc).
11. What is localStorage?
localStorage is an object provided by Web Storage API for storing data on browser which stays forever, unless deleted.
12. How to use localStorage?
It can be used as follows -
// To save data
localStorage.setItem('theme', 'dark');
// To retrieve data
localStorage.getItem('theme'); // dark
11. What is sessionStorage?
sessionStorage is an object similar to localStorage. However, it is used for storing data on browser for a specific session. The data is deleted once the browser is closed.
12. How to use sessionStorage?
It can be used as follows -
// To save data
sessionStorage.setItem('theme', 'dark');
// To retrieve data
sessionStorage.getItem('theme'); // dark
Web Storage is stored as key, value pairs. The key and value is always stored as strings.
13. What is a cookie?
Cookie is a data stored on machine in text files as name, value pairs. Cookies are used to send information to server to remember user session data.
// create a cookie
document.cookie = "name=Bruce";
// list all cookies
console.log(document.cookie) // name=Bruce
// delete a cookie (by providing any past date)
document.cookie = "name=Bruce; expires=Thu, 01 Jan 1970 00:00:00 UTC;"
14. What is JSON?
JSON stands for JavaScript Object Notation. It is a format to store and transmit data across client and server.
It is stores as text with file extension .json
.
It is written as follows -
{
"name": "Tom Hunt",
"age": "40",
}
// To convert JSON string into JavaScript object
JSON.parse(str);
// To convert Javascript object into JSON string
JSON.stringify(obj);
15. What is typeof operator?
typeof is used to find the type of a variable.
typeof 1 // "number"
typeof "hello" // "string"
typeof { id: '1' } // object
16. What is the difference between null and undefined?
null | undefined |
---|---|
It means no value is pointed. It is a representation of no value | It means variable is declared no value is assigned yet |
null is an object | undefined is not an object |
let name; // name is undefined | let name = null; // name is null |
17. How to print all keys of an object?
const obj = {
id: 1,
name: "John Doe",
age: "35"
}
console.log(Object.keys(obj)) // ['id', 'name', 'age']
18. How to print all values of an object?
const obj = {
id: 1,
name: "John Doe",
age: "35"
}
console.log(Object.values(obj)) // [1, 'John Doe', '35']
19. What is the difference between Object.seal and Object.freeze?
Object.seal prevents an object from being extended. If an object is defined as Object.seal, it can't be extended with a new key, value pair. However, the existing values can be updated.
let obj = Object.seal({id: 1});
obj.id = 2;
obj.name = "name";
console.log(obj) // {id: 2}
// existing value is updated but new value is not added
Object.freeze prevents an object from being extended and updated. If an object is defined as Object.seal, it can neither extended with a new key, value pair nor the existing values can be updated.
let obj = Object.freeze({id: 1});
obj.id = 2;
obj.name = "name";
console.log(obj) // {id: 1}
// object is same as it was originally defined
To check if an object is frozen or sealed, use isFrozen() and isSealed() methods respectively
20. What is a polyfill?
Polyfill is a code that is written to implement a functionality that in not present in the current browser. Polyfills can be written for any feature that is not present natively in any browser. For example, polyfill for web storage, canvas in old browsers like IE.
21. What is ECMAScript?
It is a scripting language that provide specification to JavaScript. It sets the blueprint for syntax and semantics of the scripting language. ECMAScript was released in 1997.
22. Explain ES6
ES6 or ECMAScript6 is the 6th version of specification of JavaScript language. It was released in 2015. It is also known as ECMAScript 2015. It is the latest specification for JavaScript.
23. What are the features of ES6?
Following are the features of ES6 -
- Arrow functions
- Template literals
- Promise
- Rest parameter
- Spread operator
- Default parameter
- let and const
- Property shorthand
- Destructuring
- Classes
24. What are template literals?
Template literals allows concat strings with variables. The template literals or template strings is written between back ticks (``)
const language = "JavaScript";
const fullString = `${language} is awesome!`;
console.log(fullString); // JavaScript is awesome
25. What is an Arrow function?
- Arrow function is a new and concise way of writing functions in JavaScript as per ES6
- It allow us to write function in a single line
- It by default inherits enclosing scope for binding current reference (this)
- It is also known as lambda function
// Syntax
const sayHello = () => 'Hello';
console.log(sayHello()); // Hello
const printName = (name) => {
console.log(`Hello ${name}`);
}
printName('David'); // Hello David
26. Explain let and const
- let and const are ways to create block scoped variables
- let is used to create varibles which need reassignment in future
- const allows us to define read-only variable
- let and const cannot be re-declared in its scope
- let and const are hoisted but not initialized
- let can be declared without initialization
- const needs to be initialized when declared
let name = 'John';
const greetText = 'Hello'; // cannot be updated
name = 'David'; // can be updated
console.log(`${greetText} ${name}`);
27. What are the difference between let, const and var
let | const | var |
---|---|---|
Block scoped | Block scoped | Function/Global scoped |
Cannot be re-declared within scope | Cannot be re-declared | Can be re-declared |
Can be updated | Cannot be updated | Can be updated |
Not initialized during hoisting | Not initialized during hoisting | Initialized with undefined during hoisting |
Can be declared without initialization | Cannot be declared without initialization | Can be declared without initialization |
28. What is difference between '==' and '==='?
The simple difference between these two operators is that '==' compares value however, '===' compares both value and type of the variable.
const a = 1;
const b = '1';
console.log(a==b); // true (because value is same even if types are different)
console.log(a===b) // false (because type is different)
'===' is always recommended for value comparisons
29. What is Temporal Dead Zone?
Temporal Dead Zone is a scenario when we try to access variables defined with let and const before they are declared. When let and const variables are accessed before their declaration, an error is thrown which is known as ReferenceError.
function greet() {
console.log(`Hello ${name}`); // ReferenceError
let name = 'Martin';
}
greet();
30. What is Scope in JavaScript?
Scope defines the visibility of variables and where they will be accessible.
There are three types of scope -
- Global
- Function
- Block
let var1 = 'global'; // global scope
function myFunction() {
const var2 = 'function'; // function scope (cannot be used outside function)
if(someCondition) {
let var3 = 'block'; // block scope (cannot be used outside {} block)
var var4 = 'no block' // accessible outside {} block as 'var' does not support block scope
}
}
31. Explain Callback
A Callback is a function which is passed to another function as an argument. The callback function is called certain task is completed. It is called from inside the function where it is passed as argument.
const greet = (greeting) => {
console.log(greeting);
}
const makeGreeting = (name, greetFn) => {
const greeting = `Hello ${name}`;
greetFn(greeting);
}
makeGreeting('David', greet);
Callbacks are useful during asyn operation where some function/task needs to be executed after certain interval.
32. What is Callback Hell?
Callback Hell is a scenario where multiple nested callbacks are used which leads to inefficient and bad code pattern.
const func1 = ((data1) => {
func2(data1, (data2) {
func3(data2, (data3) {
// more nested callbacks
});
});
});
33. Explain Promise
A Promise in JavaScript is an object which will produce some value in future. The value can be either data or error. It is used in asynchronous operations. A Promise can have 3 states -
- Pending - Promise has not returned either of resolved value of rejected value
- Fulfilled - Promise is resolved and has returned expected result
- Rejected - Promise is rejected and has returned error
Promise works as follows -
new Promise((resolve, reject) => {
if(someError) {
reject('Error');
} else {
resolve('Success');
}
})
.then(data => console.log(data)) // Success (this would execute when promise is fulfilled)
.catch(error => console.log(error)); // Error (this would execute when promise is rejected)
34. Explain Closure
A Closure is created when current function is grouped with outer scope. In Closure, variables of outer scope or lexical environment can be accessed in inner function.
const outer = () => {
let text = "Hello World";
return function() {
console.log(text);
}
}
const outerFn = outer(); // inner function has access to outer scope variable
outerFn(); // Hello World
35. What is Hoisting?
Hoisting is a process of moving variable declarations and function declarations to top of the current scope.
E.g.
- function hoisting
printSomething();
function printSomething(){ // prints Hello as declaration will be moved to top
console.log("Hello");
}
- variable hoisting
text = 'Hello';
console.log(text); // prints Hello as declaration will be moved to top
var text;
Only declarations are hoisted, not initialization
36. Explain Currying
Currying in JavaScript is transforming a function into multiple functions with multiple arguments.
In Currying, main function returns a function which returns another function and so on.
E.g. fn(a, b, c)
is written as fn(a)(b)(c)
Currying helps in reducing repeated passing of arguments.
const greet = (greeting) => {
return (name) => {
return `${greeting} ${name}`;
}
}
greet('Hello')('David'); // Hello David
greet('Hi')('Tom'); // Hi Tom
37. What is Implicit Type Coercion?
Implicit Type Coercion is a process of automatic convertion of one data type into another. E.g.
console.log(1+'1') // '11'
1 is automatically converted into string because of + operator
console.log(1-'1') // 0
'1' is automatically converted into number because of - operator
38. What is a Generator Function?
A Generator function is a special function that returns an object when invoked.
It is written as function* functionName
function* genFn() {
yield 1;
yield 2;
yield 3;
return 'complete';
}
const fn = genFn();
console.log(fn.next()); // {value: 1, done: false}
console.log(fn.next()); // {value: 2, done: false}
console.log(fn.next()); // {value: 3, done: false}
console.log(fn.next()); // {value: 'complete', done: true}
next() return an object with value and done. Once the function is completed and returns final value, done is set as true.
39. What is memoization?
Memoization is a process of caching results of expensive computation and return the cached results for previously passed arguments. This improves efficiency and function's performance.
const cache = {};
const calculateSquare = (num) => {
if(num in cache) {
console.log('cached');
console.log(cache[num]);
} else {
const square = num * num;
cache[num] = square;
console.log(square);
}
}
calculateSquare(10); // 100
calculateSquare(20); // 400
calculateSquare(10); // cached 100
In above example, result is stored when computing first time and later for all previously passed arguments/inputs cached value is used.
40. What is Event Capturing?
It is a type of event propagation in which event flows from outermost DOM node/element all the way down to target DOM node/element.
41. What is Event Bubbling?
It is a type of event propagation in which event flows from target DOM node/element all the way up to outermost DOM node/element.
42. What is Rest Parameter?
Rest Parameter converts multiple arguments into an array. It is written as function fn(...rest)
const sum = (...rest) => {
let sum = 0;
for(let num of rest) {
sum += num;
}
return sum;
}
console.log(sum(10, 20, 30)); // 60
In above example, all parameters are converted into an array.
We can also use rest operator as follows-
const sum = (num1, num2, ...rest) => {
let sum = num1 + num2;
for(let num of rest) {
sum += num;
}
return sum;
}
console.log(sum(10, 20, 30)); // 60
43. What is Spread Operator?
Spread Operator allows us to expand iterables like objects, arrays etc into individual elements
// Example 1
const sum = (num1, num2) => {
return num1 + num2;
}
const args = [2, 4];
console.log(sum(...args)); // 6
// Example 2
const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = [...arr1, ...arr2];
console.log(arr3); // [1, 2, 3, 4]
44. What is Default Parameter?
In ES6, Default Parameter can be assigned to function parameter if no value or undefined is expected.
const greet = (name = 'Developer') => {
console.log(`Hello ${name}`);
}
greet('David'); // Hello David
greet('Tom'); // Hello Tom
greet(); // Hello Developer
'Developer' is assigned as default value for name parameter when no argument is passed
45. What is babel?
Babel is a transpiler that converts ES6 code into browser compatible code. This enables new JavaScript features to run in older or unsupported browsers.