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