Javascript Interview Question Flashcards
- What are the possible ways to create objects in JavaScript?
Object constructor:
var object = new Object();
Object’s create method:
var object = Object.create(null);
Object literal syntax:
var object = {
name: “Sudheer”,
age: 34
};
Function constructor:
function Person(name) {
this.name = name;
this.age = 21;
}
var object = new Person(“Sudheer”);
Function constructor with prototype:
function Person() {}
Person.prototype.name = “Sudheer”;
var object = new Person();
ES6 Class syntax
class Person {
constructor(name) {
this.name = name;
}
}
var object = new Person(“Sudheer”);
Singleton pattern
var object = new (function () {
this.name = “Sudheer”;
})();
1.A What is object constructor? Using Constructor object create object.
The simplest way to create an empty object is using the Object constructor. Currently this approach is not recommended.
The Object constructor turns the input into an object. Its behaviour depends on the input’s type.
const o = new Object();
o.foo = 42;
console.log(o);
// Object { foo: 42 }
Object() can be called with or without new. Both create a new object.
1.B What is Object’s create method?
The create method of Object creates a new object by passing the prototype object as a parameter.
var object = Object.create(null);
1.C What is 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 an easiest way to create an object
1.D What is Function constructor? What are the basic rules of constructor function?
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”);
Remember: Contractor function always starts with a Capital and has to be Titlecased.
Rules:
1. Use “this” keyword to store the data.
2. Title casing for the function
3. using new, else the object assigned won’t be assinged to this.
4. Using bind, in the closures of the prototype functions.
1.D.A What are the basic rules of Function constructor:
Rules:
1. Use “this” keyword to store the data.
2. Title casing for the function
3. using new, else the object assigned won’t be assinged to this.
4. Using bind, in the closures of the prototype functions.
1.E How to use prototype in function constructor?
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();
1.F How to create object with ES6 Class Syntax?
ES6 introduces a class feature to create the objects, so using constructor.
class Person {
constructor(name) {
this.name = name;
}
}
var object = new Person(“Sudheer”);
1.G How to create object using 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”;
})();
- What is a prototype chain?
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.
let human = { mortal: true }
let socrates = Object.create(human)
socrates.age = 45
console.log(human.isPrototypeOf(socrates))
- 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
Apply: Invokes the function with a given this value and allows you to pass in arguments as an array
bind: returns a new function, allowing you to pass any number of arguments.
Example:
var employee1 = { firstName: “John”, lastName: “Rodson” };
var employee2 = { firstName: “Jimmy”, lastName: “Baily” };
function invite(greeting1, greeting2) {
console.log(
greeting1 + “ “ + this.firstName + “ “ + this.lastName + “, “ + greeting2
);
}
Call:
invite.call(employee1, “Hello”, “How are you?”); // Hello John Rodson, How are you?
Apply:
invite.apply(employee1, [“Hello”, “How are you?”]); // Hello John Rodson, How are you?
Bind:
var inviteEmployee1 = invite.bind(employee1);
inviteEmployee1(“Hello”, “How are you?”); // Hello John Rodson, How are you?
3.A What is call() in Function prototype?
The call() method calls the function with a given “this” value and arguments provided individually.
Example:
function Product(name, price) {
this.name = name;
this.price = price;
}
function Food(name, price) {
Product.call(this, name, price);
this.category = ‘food’;
}
console.log(new Food(‘cheese’, 5).name);
// expected output: “cheese”
Here we are assigning product to food with call.
3.B What does bind argument do in general?
The bind() method creates a new function that, when called, has its “this” keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
- What is JSON and its common operations?
JSON is a text-based data format following JavaScript object syntax,
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);
- What is the difference between slice and splice?
Slice
Doesn’t modify the original array(immutable)
Returns the subset of the original array
Used to pick the elements from an array
Splice
Modifies the original array(mutable)
Returns the deleted elements as an array
Used to insert or delete elements to/from an array
- How do you compare Object and Map?
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.
Differences:
1. The keys of an Object are Strings and Symbols, whereas they can be any value for a Map, including functions, objects, and any primitive.
2. 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.
3. 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.
4. 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.
5. 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.
6. A Map may perform better in scenarios involving frequent addition and removal of key pairs.
- What is the difference between == and === operators?
Equality comparison. Because of coercion is always better and recommend to using ===
Strict(===, !==)
Type-converting(==, !=)
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
- What are lambda or arrow functions?
- An arrow function is a shorter syntax for a function expression
- Do 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.
10.A What is new.target?
The new.target pseudo-property lets you detect whether a function or constructor was called using the new operator.
function Foo() {
if (!new.target) { throw ‘Foo() must be called with new’; }
}
10.B What is super?
The super keyword is used to access properties on an object literal or class’s [[Prototype]], or invoke a superclass’s constructor.
- What is a first class function?
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.
Example:
const handler = () => console.log(“This is a click handler function”);
document.addEventListener(“click”, handler);
- What is a first order function?
The first-order function is a function that doesn’t accept another function as an argument and doesn’t return a function as its return value.
const firstOrder = () => console.log(“I am a first order function!”);
- What is a higher order function?
Higher-order function is a function that accepts another function as an argument or returns a function as a return value or both.
const firstOrderFunc = () =>
console.log(“Hello, I am a First order function”);
const higherOrder = (ReturnFirstOrderFunc) => ReturnFirstOrderFunc();
higherOrder(firstOrderFunc);
- What is a unary function?
A unary function (i.e. monadic) is a function that accepts exactly one argument. It stands for a single argument accepted by a function.
const unaryFunction = (a) => console.log(a + 10); // Add 10 to the given argument and display the value
- What is the currying function?
Currying is the process of taking a function with multiple arguments and turning it into a sequence of functions each with only a single argument. Currying is named after mathematician Haskell Curry. By applying currying, a n-ary function turns it into a unary function.
Example for normal function:
const multiArgFunction = (a, b, c) => a + b + c;
console.log(multiArgFunction(1, 2, 3)); // 6
Example of curry function:
const curryUnaryFunction = (a) => (b) => (c) => a + b + c;
15.A What is the use of currying function
Curried functions are great to improve code reusability and functional composition.
- What is a pure function?
A Pure function is a function where the return value is only determined by its arguments without any side effects. i.e, If you call a function with the same arguments ‘n’ number of times and ‘n’ number of places in the application then it will always return the same value.
Let’s take an example to see the difference between pure and impure functions,
//Impure
let numberArray = [];
const impureAddNumber = (number) => numberArray.push(number);
//Pure
const pureAddNumber = (number) => (argNumberArray) =>
argNumberArray.concat([number]);
//Display the results
console.log(impureAddNumber(6)); // returns 1
console.log(numberArray); // returns [6]
console.log(pureAddNumber(7)(numberArray)); // returns [6, 7]
console.log(numberArray); // returns [6]
16.A What is the purpose for pure function?
Pure functions are important as they simplify unit testing without any side effects and no need for dependency injection. They also avoid tight coupling and make it harder to break your application by not having any side effects. These principles are coming together with the Immutability concept of ES6 by giving preference to const over let usage.
- What is the purpose of the let keyword?
The let statement declares a block scope local variable. Hence the variables defined with “let” keyword are limited in scope to the block, statement, or expression on which it is used. Whereas variables declared with the var keyword are used to define a variable globally, or locally to an entire function regardless of block scope.
let counter = 30;
if (counter === 30) {
let counter = 31;
console.log(counter); // 31
}
console.log(counter); // 30 (because the variable in if block won’t exist here)
- What is the difference between let and var?
var let
It is been available from the beginning of JavaScript
It has function scope
Variables will be hoisted
let
Introduced as part of ES6
It has block scope
Hoisted but not initialized
Example:
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”);
- How do you redeclare variables in switch block without an error?
Instead of
case 0:
let name;
using a block
case 0: {
let name
}
- What is the Temporal Dead Zone?
The Temporal Dead Zone is a behaviour in JavaScript that occurs when declaring a variable with the let and const keywords, but not with var.
In ECMAScript 6, accessing a let or const variable before its declaration (within its scope) causes a ReferenceError.
The time span when that happens, between the creation of a variable’s binding and its declaration, is called the temporal dead zone.
- What is IIFE(Immediately Invoked Function Expression)?
IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.
(function () {
// logic here
})();
22A. What is the purpose of IIFE?
The primary reason to use an IIFE is to obtain data privacy because any variables declared within the IIFE cannot be accessed by the outside world. i.e, If you try to access variables with IIFE then it throws an error as below,
- How do you decode or encode a URL in JavaScript?
encodeURI()
decodeURI()
- What is memoization?
Memoization is a programming technique which attempts to increase a function’s performance by caching its previously computed results. Each time a memoized function is called, its parameters are used to index the cache. If the data is present, then it can be returned, without executing the entire function. Otherwise the function is executed and then the result is added to the cache.
- What is Hoisting?
Hoisting is a JavaScript mechanism where variables, function declarations and classes are moved to the top of their scope before code execution. Remember that JavaScript only hoists declarations, not initialisation.
Example:
console.log(message); //output : undefined
var message = “The variable Has been hoisted”;
In the same fashion, function declarations are hoisted too
message(“Good morning”); //Good morning
function message(name) {
console.log(name);
}
This hoisting makes functions to be safely used in code before they are declared.
- What are classes in ES6?
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”;
}
}
- What are closures?
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 variables
- Global variables
Example:
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.
- What are modules?
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
- Why do we need modules?
Maintainability
Reusability
Namespacing
- What is scope in Javascript?
The 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.
- What is a service worker?
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.