General Interview Questions Flashcards

1
Q

What is difference between document.getElementById() and document.querySelector()?

A
  • document.getElementById()

Returns an element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they’re a useful way to get access to a specific element quickly.

element = document.getElementById(id);

  • document.querySelector()

Returns the first matching Element node within the node’s subtree. If no matching node is found, null is returned.

element = document.querySelector(selectors);

  • document.querySelectorAll()

Returns a NodeList containing all matching Element nodes within the node’s subtree, or an empty NodeList if no matches are found.

element = document.querySelectorAll(selectors);

Note: querySelector() is more useful when we want to use more complex selectors.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

When to use reduce(), map(), foreach() and filter() in JavaScript?

A
  • forEach()

It takes a callback function and run that callback function on each element of array one by one.

Basically forEach works as a traditional for loop looping over the array and providing array elements to do operations on them.

var arr = [10, 20, 30];

arr. forEach(function (elem, index){
console. log(elem + ‘ comes at ‘ + index);

})

Output

10 comes at 0

20 comes at 1

30 comes at 2

  • filter()

The main difference between forEach() and filter() is that forEach just loop over the array and executes the callback but filter executes the callback and check its return value. If the value is true element remains in the resulting array but if the return value is false the element will be removed for the resulting array.

Note: filter does not update the existing array it will return a new filtered array every time.

var arr = [10, 20, 30];

var result = arr.filter(function(elem){

return elem !== 20;

})

console.log(result)

Output

[10, 30]

  • map()

map() like filter() & forEach() takes a callback and run it against every element on the array but whats makes it unique is it generate a new array based on your existing array.

Like filter(), map() also returns an array. The provided callback to map modifies the array elements and save them into the new array upon completion that array get returned as the mapped array.

var arr = [10, 20, 30];

var mapped = arr.map(function(elem) {

return elem * 10;

});

console.log(mapped)

Output

[100, 200, 300]

  • reduce()

reduce() method of the array object is used to reduce the array to one single value.

var arr = [10, 20, 30];

var sum = arr.reduce(function(sum, elem) {

return sum + elem; });

console.log(sum); // Output: 60

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is Hoisting in JavaScript?

A

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.

Example 01: Variable Hoisting

console.log(message); // output : undefinedvar message = “The variable Has been hoisted”;

The above code looks like as below to the interpreter,

var message;console.log(message); message = “The variable Has been hoisted”;

Example 02: Function Hoisting

function hoist() { a = 20; var b = 100; }hoist();console.log(a);/* Accessible as a global variable outside hoist() functionOutput: 20*/console.log(b);/*Since it was declared, it is confined to the hoist() function scope.We can’t print it out outside the confines of the hoist() function.Output: ReferenceError: b is not defined*/

All declarations (function, var, let, const and class) are hoisted in JavaScript, while the var declarations are initialized with undefined, but let and const declarations remain uninitialized.

console.log(a);let a = 3;// Output: ReferenceError: a is not defined

They will only get initialized when their lexical binding (assignment) is evaluated during runtime by the JavaScript engine. This means we can’t access the variable before the engine evaluates its value at the place it was declared in the source code. This is what we call Temporal Dead Zone, A time span between variable creation and its initialization where they can’t be accessed.

Note: JavaScript only hoists declarations, not initialisation

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are closures?

A

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’s variables
  • Global variables

function Welcome(name) { var greetingInfo = function(message) { console.log(message+’ ‘+name); } return greetingInfo; }var myFunction = Welcome(‘John’); myFunction(‘Welcome ‘); // Output: Welcome JohnmyFunction(‘Hello Mr.’); // output: Hello Mr.John

As per the above code, the inner function greetingInfo() has access to the variables in the outer function Welcome() even after outer function has returned.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you clone an object in JavaScript?

A

Using the object spread operator …, the object own enumerable properties can be copied into the new object. This creates a shallow clone of the object.

const obj = { a: 1, b: 2 }const shallowClone = { …obj }

With this technique, prototypes are ignored. In addition, nested objects are not cloned, but rather their references get copied, so nested objects still refer to the same objects as the original. Deep-cloning is much more complex in order to effectively clone any type of object (Date, RegExp, Function, Set, etc) that may be nested within the object.

Other alternatives include:

  • JSON.parse(JSON.stringify(obj)) can be used to deep-clone a simple object, but it is CPU-intensive and only accepts valid JSON (therefore it strips functions and does not allow circular references).
  • Object.assign({}, obj) is another alternative.
  • Object.keys(obj).reduce((acc, key) => (acc[key] = obj[key], acc), {}) is another more verbose alternative that shows the concept in greater depth.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are the possible ways to create objects in JavaScript?

A

a.) Object constructor: The simpliest way to create an empty object is using Object constructor. Currently this approach is not recommended.

var object = new Object();

b.) Object create method: The create method of Object creates a new object by passing the prototype object as a parameter

var object = Object.create(null);

c.) Object literal syntax: The object literal syntax is equivalent to create method when it passes null as parameter

var object = {};

d.) Function constructor: Create any function and apply the new operator to create object instances,

function Person(name) { var object = {}; object.name = name; object.age = 26; return object; } var object = new Person(“Alex”);

e.) Function constructor with prototype: This is similar to function constructor but it uses prototype for their properties and methods,

function Person(){}Person.prototype.name = “Alex”;var object = new Person();

This is equivalent to an instance created with an object create method with a function prototype and then call that function with an instance and parameters as arguments.

function func {};new func(x, y, z);// **(OR)**// Create a new instance using function prototype.var newInstance = Object.create(func.prototype)// Call the functionvar result = func.call(newInstance, x, y, z),// If the result is a non-null object then use it otherwise just use the new instance.console.log(result && typeof result === ‘object’ ? result : newInstance);

f.) ES6 Class syntax: ES6 introduces class feature to create the objects

class Person { constructor(name) { this.name = name; } }var object = new Person(“Alex”);

g.) 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 = “Alex”; }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are the javascript data types?

A

There are eight basic data types in JavaScript.

String

String is used to store text. In JavaScript, strings are surrounded by quotes:

  • Single quotes: ‘Hello’
  • Double quotes: “Hello”
  • Backticks: Hello

Example:

//Strings const firstName = ‘John’; const lastName = “K”; const result = The names are ${firstName} and ${lastName};

Number

Number represents integer and floating numbers (decimals and exponentials). A number type can also be +Infinity, -Infinity, and NaN (not a number).

const number1 = 3; const number2 = 3.433; const number3 = 3e5 // 3 * 10^5 const number1 = 3/0; console.log(number1); // Infinity const number2 = -3/0; console.log(number2); // -Infinity // strings can’t be divided by numbersconst number3 = “abc”/3; console.log(number3); // NaN

BigInt

In JavaScript, Number type can only represent numbers less than (253 - 1) and more than -(253 - 1). However, if you need to use a larger number than that, you can use the BigInt data type.

A BigInt number is created by appending n to the end of an integer.

// BigInt valueconst num1 = 900719925124740998n; const num2 = 900719925124740998n; const num3 = 10; // Adding two big integersconst result1 = num1 + num2; console.log(result1); // “1801439850249481996n” // Error! BitInt and number cannot be addedconst result2 = num1 + num2 + num3; console.log(result2); // Uncaught TypeError: Cannot mix BigInt and other types

Boolean

This data type represents logical entities. Boolean represents one of two values: true or false.

const dataChecked = true; const valueCounted = false;

undefined

The undefined data type represents value that is not assigned. If a variable is declared but the value is not assigned, then the value of that variable will be undefined.

let name; console.log(name); // undefined let name = undefined; console.log(name); // undefined

null

In JavaScript, null is a special value that represents empty or unknown value.

const number = null;

Symbol

A value having the data type Symbol can be referred to as a symbol value. Symbol is an immutable primitive value that is unique.

// Two symbols with the same description const value1 = Symbol(‘hello’); const value2 = Symbol(‘hello’); let result = (value1 === value2) ? true : false; // false; // Note: Though value1 and value2 both contain ‘hello’, they are different as they are of the Symbol type.

Object

An object is a complex data type that allows us to store collections of data.

const employee = { firstName: ‘John’, lastName: ‘K’, email: ‘john.k@gmail.com’ };

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are global variables?

A

Global variables are declared outside of a function or declared with a window object for accessibility throughout the program (unless shadowed by locals). If you declare a variable without using var, even if it’s inside a function, it will still be seen as global:

var x = 5; // globalfunction someThing(y) { var z = x + y; console.log(z); }someThing(4); // 9console.log(x); // 5

Note:Using Undeclared Variables

  • In strict mode, if you attempt to use an undeclared variable, you’ll get a reference error when you run your code.
  • Outside of strict mode, however, if you assign a value to a name that has not been declared with let, const, or var, you’ll end up creating a new global variable. It will be global no matter how deeply nested within functions and blocks your code is, which is almost certainly not what you want, is bug-prone, and is one of the best reasons for using strict mode!
  • Global variables created in this accidental way are like global variables declared with var: they define properties of the global object. But unlike the properties defined by proper var declarations, these properties can be deleted with the delete operator.

var x = 5; // globalfunction someThing(y) { x = 1; // still global!var z = x + y; console.log(z); }someThing(4) // 5console.log(x) // 1

var x = 5; // globalfunction someThing(y) { var x = 3; // localvar z = x + y; console.log(z); }someThing(4); // 7console.log(x); // 5

A global variable is also an object of the current scope, such as the browser window:

var dog = “Fluffy”;console.log(dog); // Fluffy;var dog = “Fluffy”;console.log(window.dog); // Fluffy

To declare JavaScript global variables inside the function, you need to use a window object. For example:

window.value = 90;

Now it can be declared inside any function and can be accessed from any function. For example:

function m() { window.value = 100; //declaring global variable by window object } function n() { console.log(window.value); //accessing global variable from other function }

It’s a best practice to minimize global variables. Since the variable can be accessed anywhere in the program, they can cause strange behavior.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is variable shadowing in javascript?

A

Variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. This outer variable is said to be shadowed.

If there is a variable in the global scope, and you’d like to create a variable with the same name in a function. The variable in the inner scope will temporarily shadow the variable in the outer scope.

var val = 10;function Hoist(val) { alert(val); }Hoist(20);

Output

20

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is an event flow?

A

Event flow is the order in which event is received on the web page. When you click an element that is nested in various other elements, before your click actually reaches its destination, or target element, it must trigger the click event each of its parent elements first, starting at the top with the global window object.

There are two ways of event flow

  • Top to Bottom(Event Capturing)
  • Bottom to Top (Event Bubbling)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is event bubbling?

A

Event bubbling is a type of event propagation where the event first triggers on the innermost target element, and then successively triggers on the ancestors (parents) of the target element in the same nesting hierarchy till it reaches the outermost DOM element.

Example: If you click on EM, the handler on DIV runs.

<div onclick=”alert(‘The handler!’)”> <em>If you click on <code>EMcode>, the handler on <code>DIVcode> runs.em>div>

  • Stopping bubbling

<body onclick=”alert(the bubbling doesn\'t reach here)”> <button onclick=”event.stopPropagation()”>Click mebutton>body>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is event capturing?

A

Event capturing is a type of event propagation where the event is first captured by the outermost element and then successively triggers on the descendants (children) of the target element in the same nesting hierarchy till it reaches the inner DOM element.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is prototype chain?

A

Nearly all objects in JavaScript are instances of Object. That means all the objects in JavaScript inherit the properties and methods from Object.prototype. This is called Prototype chaining.

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.

function Person(firstName, lastName, age) { this.firstName = firstName; this.lastName = lastName; this.age = age; }//Person class createdPerson.prototype.getFullName = function() { return this.firstName + “ “ + this.lastName; }// we have added getFullName method in Person’s prototype.var person = new Person(“John”, “K”, 25);// It will create an instance of the Person class> person.hasOwnProperty(“firstName”); // true> person.hasOwnProperty(“getFullName”); // false> person.getFullName(); // John K

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the difference between Call, Apply and Bind?

A

a.) call()

The call() method invokes a function with a given this value and arguments provided one by one

var employee1 = {firstName: ‘John’, lastName: ‘Rodson’};var employee2 = {firstName: ‘Jimmy’, lastName: ‘Baily’};function invite(greeting1, greeting2) { console.log(greeting1 + ‘ ‘ + this.firstName + ‘ ‘ + this.lastName+ ‘, ‘+ greeting2); } invite.call(employee1, ‘Hello’, ‘How are you?’); // Hello John Rodson, How are you?invite.call(employee2, ‘Hello’, ‘How are you?’); // Hello Jimmy Baily, How are you?

b.) apply()

Invokes the function and allows you to pass in arguments as an array

var employee1 = {firstName: ‘John’, lastName: ‘Rodson’};var employee2 = {firstName: ‘Jimmy’, lastName: ‘Baily’};function invite(greeting1, greeting2) { console.log(greeting1 + ‘ ‘ + this.firstName + ‘ ‘ + this.lastName+ ‘, ‘+ greeting2); } invite.apply(employee1, [‘Hello’, ‘How are you?’]); // Hello John Rodson, How are you?invite.apply(employee2, [‘Hello’, ‘How are you?’]); // Hello Jimmy Baily, How are you?

c.) bind()

returns a new function, allowing you to pass in an array and any number of arguments

var employee1 = {firstName: ‘John’, lastName: ‘Rodson’};var employee2 = {firstName: ‘Jimmy’, lastName: ‘Baily’};function invite(greeting1, greeting2) { console.log(greeting1 + ‘ ‘ + this.firstName + ‘ ‘ + this.lastName+ ‘, ‘+ greeting2); }var inviteEmployee1 = invite.bind(employee1);var inviteEmployee2 = invite.bind(employee2); inviteEmployee1(‘Hello’, ‘How are you?’); // Hello John Rodson, How are you?inviteEmployee2(‘Hello’, ‘How are you?’); // Hello Jimmy Baily, How are you?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the difference between == and === operators?

A

JavaScript provides both strict(===, !==) and type-converting(==, !=) equality comparison. The strict operators takes type of variable in consideration, while non-strict operators make type correction/conversion based upon values of variables. The strict operators follow the below conditions for different types,

  1. Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
  2. Two numbers are strictly equal when they are numerically equal. i.e, Having the same number value. There are two special cases in this,
    1. NaN is not equal to anything, including NaN.
    2. Positive and negative zeros are equal to one another.
  3. Two Boolean operands are strictly equal if both are true or both are false.
  4. Two objects are strictly equal if they refer to the same Object.
  5. Null and Undefined types are not equal with ===, but equal with ==. i.e, null===undefined –> false but null==undefined –> true

Examples

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is a first class function?

A

JavaScript functions are first-class functions meaning functions and objects are treated as the same thing. Functions can be stored as a variable inside an object or an array as well as it can be passed as an argument or be returned by another function. That makes function “first-class citizens in JavaScript”

Example: Assign a function to a variable

const message = function() { console.log(“Hello World!”); }message(); // Invoke it using the variable

Example: Pass a function as an Argument

function sayHello() { return “Hello, “; }function greeting(helloMessage, name) { console.log(helloMessage() + name); }// Pass sayHello as an argument to greeting functiongreeting(sayHello, “JavaScript!”);

Example: Return a function

function sayHello() { return function() { console.log(“Hello!”); } }

Example: Using a variable

const sayHello = function() { return function() { console.log(“Hello!”); } }const myFunc = sayHello(); myFunc();

Example: Using double parentheses

function sayHello() { return function() { console.log(“Hello!”); } }sayHello()();

We are using double parentheses ()() to invoke the returned function as well.

17
Q

What is a higher order function?

A

A Higher-Order function is a function that receives a function as an argument or returns the function as output.

For example, Array.prototype.map(), Array.prototype.filter() and Array.prototype.reduce() are some of the Higher-Order functions in javascript.

const arr1 = [1, 2, 3];const arr2 = arr1.map(function(item) { return item * 2; });console.log(arr2);

18
Q

What is a unary function?

A

Unary function (i.e. monadic) is a function that accepts exactly one argument. Let us take an example of unary function. It stands for single argument accepted by a function.

const unaryFunction = a => console.log (a + 10); //Add 10 to the given argument and display the value

19
Q

What is a unary function?

A

Unary function (i.e. monadic) is a function that accepts exactly one argument. Let us take an example of unary function. It stands for single argument accepted by a function.

const unaryFunction = a => console.log (a + 10); //Add 10 to the given argument and display the value

20
Q

What is currying function?

A

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.

function volume(length) {

return function(width) {

return function(height) {

return height * width * length;

}

}

}

volume(2)(3)(4); // 24

Curried functions are great to improve code re-usability and functional composition.

21
Q

What is a pure function?

A

Pure functions are functions that accept an input and returns a value without modifying any data outside its scope(Side Effects). Its output or return value must depend on the input/arguments and pure functions must return a value.

Example

function impure(arg) { finalR.s = 90return arg * finalR.s}

The above function is not a pure function because it modified a state finalR.s outside its scope.

function pure(arg) { return arg * 4}

Here is a pure function. It didn’t side effect any external state and it returns an output based on the input.

A function must pass two tests to be considered “pure”:

  1. Same inputs always return same outputs
  2. No side-effects

1. Same Input => Same Output
Compare this:

const add = (x, y) => x + y;add(2, 4); // 6

To this

let x = 2;const add = (y) => { x += y; };add(4); // x === 6 (the first time)

2. Pure Functions = Consistent Results
The first example returns a value based on the given parameters, regardless of where/when you call it.

If you pass 2 and 4, you’ll always get 6.

Nothing else affects the output.

Benefits

  • One of the major benefits of using pure functions is they are immediately testable. They will always produce the same result if you pass in the same arguments.
  • The pure functions are easier to parallelize
  • They also makes maintaining and refactoring code much easier.
22
Q

What is memoization in JavaScript?

A

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.

// A simple memoized function to Add Number

const memoizedAdd = () => {

let cache = {};

return (number) => {

if (number in cache) {

console.log(‘Fetching from cache: ‘);

return cache[number];

}

else {

console.log(‘Calculating result: ‘);

let result = number + 10;

cache[number] = result;

return result;

}

}

} // returned function from memoizedAdd

const sum = memoizedAdd();

console. log(sum(10)); // Calculating result: 20
console. log(sum(10)); // Fetching from cache: 20