You are on page 1of 18

70 JAVASCRIPT INTERVIEW QUESTIONS...

1.What's the difference between undefined and null?


Undefined is a type and null is an object.
undefined is the default value of a variable that has not been assigned a specific value. Or a
function that has no explicit return value ex. console.log(1). Or a property that does not exist in
an object. The JavaScript engine does this for us the assigning of undefined value.
null is "a value that represents no value". null is value that has been explicitly defined to a
variable. In this example we get a value of null when the fs.readFile method does not throw an
error.
When comparing null and undefined we get true when using == and false when using ===.
2.What does the && operator do?
The && or Logical AND operator finds the first falsy expression in its operands and returns it
and if it does not find any falsy expression it returns the last expression. It employs short-
circuiting to prevent unnecessary work.
&& is the logic operator. Both conditions should be met at the same time.
3.What does the || operator do?
The || or Logical OR operator finds the first truthy expression in its operands and returns it. This
too employs short-circuiting to prevent unnecessary work. It was used before to initialize default
parameter values IN functions before ES6 Default function parameters was supported.
4. Is using the + or unary plus operator the fastest way in converting a string to a number?
the + is the fastest way of converting a string to a number because it does not perform any
operations on the value if it is already a number.
Yes. It is used to avoid getting errors.
5. What is the DOM?
DOM stands for Document Object Model is an interface (API) for HTML and XML documents.
When the browser first reads (parses) our HTML document it creates a big object, a really big
object based on the HTML document this is the DOM. It is a tree-like structure that is modeled
from the HTML document. The DOM is used for interacting and modifying the DOM structure
or specific Elements or Nodes
6. What is Event Propagation?
How event travel through dom tree (Event propagation is a way to describe the “stack” of events
that are fired in a web browser)
 Event Propagation has three phases:
 Capturing Phase-the event starts from the window down until it reaches the event.target.
 Target Phase-the event has reached the event.target.
 Bubling Phase-the event bubbles up from the event.target element up until it reaches the
window.

7. What's Event Bubbling?


When an event occurs on a DOM element, that event does not entirely occur on that just one
element. In the Bubbling Phase, the event bubbles up or it goes to its parent, to its grandparents,
to its grandparent's parent until it reaches all the way to the window.
Event travel from inner and go to up (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 of the target element in the same nesting hierarchy till it reaches the outermost DOM
element or document object.)
8. What's Event Capturing?
When an event occurs on a DOM element, that event does not entirely occur on that just one
element. In Capturing Phase, the event starts from the window all the way down to the element
that triggered the event.
Event capturing is the event starts from top element to the target element. It is the opposite of
Event bubbling, which starts from target element to the top element.
9. What's the difference between event.preventDefault() and event.stopPropagation() methods?
The event.preventDefault() method prevents the default behavior of an element. If used in a form
element it prevents it from submitting. If used in an anchor element it prevents it from
navigating. If used in a contextmenu it prevents it from showing or displaying. While the
event.stopPropagation() method stops the propogation of an event or it stops the event from
occurring in the bubbling or capturing phase.
event.preventDefault() – default behavior/ event.stopPropagation() – stops event from
propagating
The event. preventDefault() will not allow the user to leave the page and open the URL.
The event. stopPropagation() method stops the propagation of an event from occurring in
the bubbling or capturing phase
The event.preventDefault() method prevents the default behavior of an element. If we
use form element it prevents form submitting. If we use a href element it prevents navigating. If
we use contextMenu element it prevents displaying.

10. How to know if the event.preventDefault() method was used in an element?


We can use the event.defaultPrevented property in the event object. It returns a boolean
indicating if the event.preventDefault() was called in a particular element.
It is used for event canceling
11. Why does this code obj.someprop.x throw an error?
x property in the someprop property which have an undefined value. Remember properties in an
object which does not exist in itself and its prototype has a default value of undefined and
undefined has no property x.
12. What is event.target ?
Event.target – return element that triggered the event
13. What is event.currentTarget?
event.currentTarget - shows the element that triggered the event
14. What's the difference between == and ===?
The difference between ==(abstract equality) and ===(strict equality) is that the == compares by
value after coercion and === compares by value and type without coercion.
15. Why does it return false when comparing two similar objects in JavaScript?
JavaScript compares objects and primitives differently. In primitives it compares them by value
while in objects it compares them by reference or the address in memory where the variable is
stored.
Operators are bolean
16. What does the !! operator do?
The Double NOT operator or !! coerces the value on the right side into a boolean. basically it's a
fancy way of converting a value into a boolean.
17. How to evaluate multiple expressions in one line?
We can use the , or comma operator to evaluate multiple expressions in one line. It evaluates
from left-to-right and returns the value of the last item on the right or the last operand.
18. What is Hoisting?
Hoisting is a JavaScript mechanism where variables and function declarations are moved to
the top of their scope before code execution. Inevitably, this means that no matter where
functions and variables are declared, they are moved to the top of their scope regardless of
whether their scope is global or local.
19. What is Scope?
Scope in JavaScript refers to the current context of code, which determines the accessibility
of variables to JavaScript. The two types of scope are local and global: Global variables are
those declared outside of a block. Local variables are those declared inside of a block
(accessibility)
20. What are Closures?
A closure is the combination of a function bundled together (enclosed) with references to its
surrounding state (the lexical environment). ... In JavaScript, closures are created every time
a function is created, at function creation time (combination)
21. What are the falsy values in JavaScript?
 the number 0

 the BigInt 0n

 the keyword null

 the keyword undefined

 the boolean false

 the number NaN

 the empty string "" (equivalent to '' or ``)

22. How to check if a value is falsy?


It is possible to check for a falsy value in a variable with a simple conditional:
if (!variable) {
// When the variable has a falsy value the condition is true.
}
23. What does “use strict" do?
The "use strict" directive was new in ECMAScript version 5. It is not a statement, but a literal
expression, ignored by earlier versions of JavaScript. The purpose of "use strict" is to indicate
that the code should be executed in "strict mode". With strict mode, you can not, for example,
use undeclared variables.
24. What's the value of 'this' in JavaScript?
this keyword refers to an object, that object which is executing the current bit
of javascript code. In other words, every javascript function while executing has a reference
to its current execution context, called this. Execution context means here is how the function
is called.
25. What is the prototype of an object?
The prototype is an object that is associated with every functions and objects by default in
JavaScript, where function's prototype property is accessible and modifiable and object's
prototype property (aka attribute) is not visible. The prototype object is special type of
enumerable object to which additional properties can be attached to it which will be shared
across all the instances of its constructor function.
26. What is an IIFE, what is the use of it?
An Immediately-invoked Function Expression (IIFE for friends) is a way to execute functions
immediately, as soon as they are created. IIFEs are very useful because they don't pollute the
global object, and they are a simple way to isolate variables declarations.
27. What is the use Function.prototype.apply method?
prototype. apply() The apply() method calls a function with a given this value, and
arguments provided as an array (or an array-like object).
28. What is the use Function.prototype.call method?
The call() allows for a function/method belonging to one object to be assigned and called for
a different object. call() provides a new value of this to the function/method. With call() , you
can write a method once and then inherit it in another object, without having to rewrite
the method for the new object.
29. What's the difference between Function.prototype.apply and Function.prototype.call?
The difference is that call() takes the function arguments separately, and apply() takes
the function arguments in an array. CALL : A function with argument provide individually.
If you know the arguments to be passed or there are no argument to pass you can use  call.
30. What is the usage of Function.prototype.bind?7
function. prototype. bind() accepts an Object. It binds the calling function to the passed
Object and the returns the same. When an object is bound to a function, it means you will be
able to access the values of that object from within the function using 'this' keyword
31. What is Functional Programming and what are the features of JavaScript that makes it a
candidate as a functional language?
JavaScript is a multi-paradigm language that allows you to freely mix and match object-oriented,
procedural, and functional paradigms. Functional programming (often abbreviated FP) is the
process of building software by composing pure functions, avoiding shared state, mutable
data, and side-effects. Functional programming is declarative rather than imperative, and
application state flows through pure functions. Contrast with object oriented programming, where
application state is usually shared and collocated with methods in objects.
32. What are Higher Order Functions?
Functions that operate on other functions, either by taking them as arguments or by returning
them. Higher-order functions allow us to abstract over actions, not just values. They come in
several forms. For example, we can have functions that create new functions.
33. Why are functions called First-class Objects?
In JavaScript, functions are first-class objects, because they can have properties and methods
just like any other object. A function is composed of a sequence of
statements called the function body. Values can be passed to a function, and the function will
return a value
34. Implement the Array.prototype.map method by hand.
function map(arr, mapCallback) {
// First, we check if the parameters passed are right.
if (!Array.isArray(arr) || !arr.length || typeof mapCallback !== 'function') {
return [];
} else {
let result = [];
// We're making a results array every time we call this function
// because we don't want to mutate the original array.
for (let i = 0, len = arr.length; i < len; i++) {
result.push(mapCallback(arr[i], i, arr));
// push the result of the mapCallback in the 'result' array
}
return result; // return the result array
}
}
35. Implement the Array.prototype.filter method by hand.
function filter(arr, filterCallback) {
// First, we check if the parameters passed are right.
if (!Array.isArray(arr) || !arr.length || typeof filterCallback !== 'function')
{
return [];
} else {
let result = [];
// We're making a results array every time we call this function
// because we don't want to mutate the original array.
for (let i = 0, len = arr.length; i < len; i++) {
// check if the return value of the filterCallback is true or "truthy"
if (filterCallback(arr[i], i, arr)) {
// push the current item in the 'result' array if the condition is true
result.push(arr[i]);
}
}
return result; // return the result array
}
}
36. Implement the Array.prototype.reduce method by hand.
function reduce(arr, reduceCallback, initialValue) {
// First, we check if the parameters passed are right.
if (!Array.isArray(arr) || !arr.length || typeof reduceCallback !== 'function')
{
return [];
} else {
// If no initialValue has been passed to the function we're gonna use the
let hasInitialValue = initialValue !== undefined;
let value = hasInitialValue ? initialValue : arr[0];
// first array item as the initialValue

// Then we're gonna start looping at index 1 if there is no


// initialValue has been passed to the function else we start at 0 if
// there is an initialValue.
for (let i = hasInitialValue ? 0 : 1, len = arr.length; i < len; i++) {
// Then for every iteration we assign the result of the
// reduceCallback to the variable value.
value = reduceCallback(value, arr[i], i, arr);
}
return value;
}
}
37. What is the arguments object?
The arguments object is a local variable available within all non-arrow functions. You can
refer to a function's arguments inside that function by using its arguments object. It has
entries for each argument the function was called with, with the first entry's index at 0.
38. How to create an object without a prototype?
const o1 = {};
console.log(o1.toString());
// logs [object Object] get this method to the Object.prototype

const o2 = Object.create(null);
// the first parameter is the prototype of the object "o2" which in this
// case will be null specifying we don't want any prototype
console.log(o2.toString());
// throws an error o2.toString is not a function
39. Why does b in this code become a global variable when you call this function?
function myFunc(){
let a = b = 0;
}
myFunc();

The reason for this is that assignment operator or = has right-to-left associativity or evaluation.
What this means is that when multiple assignment operators appear in a single expression they
evaluated from right to left. So our code becomes likes this.
function myFunc(){
let a = (b = 0);
}
myFunc();

First, the expression b = 0 evaluated and in this example b is not declared. So, The JS Engine
makes a global variable b outside this function after that the return value of the expression b = 0
would be 0 and it's assigned to the new local variable a with a let keyword.
We can solve this problem by declaring the variables first before assigning them with value.
function myFunc() {
let a,b;
a = b = 0;
}
myFunc();

40. What is ECMAScript?


ECMAScript is a general-purpose programming language, standardized by Ecma International
according to the document ECMA-262. It is a JavaScript standard meant to ensure the
interoperability of Web pages across different Web browsers
41. What are the new features in ES6 or ECMAScript2015?
The let keyword
The const keyword
JavaScript Arrow Functions
JavaScript For/of
JavaScript Classes
JavaScript Promises
JavaScript Symbol
Default Parameters
Function Rest Parameter
Array.find()
Array.findIndex()
New Math Methods
New Number Properties
New Number Methods
New Global Methods
JavaScript Modules

42. What's the difference between var, let and const keywords?
var declarations are globally scoped or function scoped while let and const are block
scoped. var variables can be updated and re-declared within its scope; let variables can be
updated but not re-declared; const variables can neither be updated nor re-declared. They are
all hoisted to the top of their scope
43. What are Arrow functions?
An arrow function expression is a compact alternative to a traditional function expression, but is
limited and can't be used in all situations.

Differences & Limitations:

 Does not have its own bindings to this or super, and should not be used as methods.
 Does not have arguments, or new.target keywords.
 Not suitable for call, apply and bind methods, which generally rely on establishing
a scope.
 Can not be used as constructors.
 Can not use yield, within its body.

44. What are Classes?


A class is an extensible program-code-template for creating objects, providing initial values for
state (member variables) and implementations of behavior (member functions or methods)
45. What are Template Literals?
Template literals are string literals allowing embedded expressions. You can use multi-line strings
and string interpolation features with them.
Template literals are enclosed by the backtick (` `) (grave accent) character instead of double or
single quotes.

Template literals can contain placeholders. These are indicated by the dollar sign and curly braces
(${expression}). The expressions in the placeholders and the text between the backticks (` `) get
passed to a function.

The default function just concatenates the parts into a single string. If there is an expression
preceding the template literal (tag here), this is called a tagged template. In that case, the tag
expression (usually a function) gets called with the template literal, which you can then
manipulate before outputting.

To escape a backtick in a template literal, put a backslash (\) before the backtick.

46. What is Object Destructuring?


Destructuring is a JavaScript expression that allows us to extract data from arrays, objects,
and maps and set them into new, distinct variables. Destructuring allows us to extract multiple
properties, or items, from an array at a time.
47. What are ES6 Modules?
 A module organizes a related set of JavaScript code. A module can contain variables and
functions. ... Variables and functions within a module should be exported so that they can be
accessed from within other files. Modules in ES6 work only in strict mode.
48. What is the Set object and how does it work?
 The Set object allows you store unique values of any type, whether they are primitive data
types like strings, booleans, symbols, null, etc or even objects
49. What is a Callback function?
A callback is a function that is to be executed after another function has finished executing
50. What are Promises?
The Promise object represents the eventual completion (or failure) of an asynchronous
operation and its resulting value
51. What is async/await and How does it work?
An async function can contain an await expression, that pauses the execution of
the function and waits for the passed Promise's resolution, and then resumes the async
function's execution and returns the resolved value. ... The purpose of async/await is to
simplify the behavior of using promises.
52. What's the difference between Spread operator and Rest operator?
The spread operator allows us to spread the value of an array (or any iterable) across zero or
more arguments in a function or elements in an array (or any iterable). The rest
parameter allows us to pass an indefinite number of parameters to a function and access
them in an array.
53. What are Default Parameters?
Default function parameters allow named parameters to be initialized with default values if no
value or undefined is passed.
54. What are Wrapper Objects?
 Whenever you try to access a property of a string str, JavaScript coerces the string value to an
object, by new String(str). This object is called a wrapper object. It inherits all string
methods, and is used to resolve the property reference.
55. What is the difference between Implicit and Explicit Coercion?
There are two types of coercion in JavaScript: Implicit Coercion: Type conversion is
done implicitly by JavaScript. Explicit Coercion: Type conversion is done explicitly in code
using the inbuilt functions like Number(), String(), Boolean(), etc.
Implicit Coercion
In this case, the coercion is done implicitly. When JavaScript operates in a wrong data type, it will
try to convert the value to the right data type. Sometimes, the result is different from the one
expected. Whenever we pass a different data type as an operand in a numeric expression
involving operators like -, *, /, %, the conversion process is similar to calling the in-
built Number function on the operand. If the conversion to number isn’t possible, NaN is
returned. The + operator works differently than the other numerical operators. It can work as both
concatenation and numerical operator depending on the type of operand passed. Implicit
coercion is also done by the if() condition and == operator.If the value in the if() condition
isn’t a Boolean, then it will be implicitly tried to be converted to a Boolean type. All data types
can be converted to Boolean. All the values except the ones mentioned below are converted to a
true Boolean value.

1. “ ”

2. 0

3. -0

4. undefined

5. null

6. NaN

Explicit Coercion

In this case, type conversion is explicitly done in the code by the developer. JavaScript provides

inbuilt methods for type conversion.

Converting to Number

The Number() global method is used to convert any other data type value to numeric values.

parseInt() and parseFloat() methods can also be used to convert numbers stored as a string to a

number. For all other data types, it will return NaN.

Converting to String

The String() global method is used to convert any other data type value to string values.

Converting to Boolean

The Boolean() global method is used to convert any other data type value to Boolean values.
56. What is NaN? and How to check if a value is NaN?
isNaN() method determines whether a value is NaN (Not-A-Number). This method returns
true if the value is of the type Number, and equates to NaN. Otherwise it returns false.
57. How to check if a value is an Array?
In JavaScript, we can check if a variable is an array by using 3 methods, using the  isArray
method, using the instanceof operator and using checking the constructor type if it matches
an Array object.
 Method 1: Using the isArray method
The Array.isArray() method checks whether the passed variable is an Array object.
Method 2: Using the instanceof operator
The instanceof operator is used to test whether the prototype property of a constructor appears
anywhere in the prototype chain of an object. This can be used to evaluate if an the given
variable has a prototype of ‘Array’.
Method 3: Checking the constructor property of the variable
Another method to check a variable is an array is by checking it’s constructor with Array.
58. How to check if a number is even without using the % or modulo operator?
Method 1: By using the bitwise (&) operator, a number can be checked if it is odd or even.
Method 2: By multiplying and dividing the number by 2. Divide the number by 2 and multiply it
by 2. If the result is the same as that of the input, then it is an even number otherwise, it is an odd
number.
Method 3: By switching temporary variable n times with the initial value of the variable being
true.If the flag variable gets its original value (which is true) back, then n is even. Else, n is false.
59. How to check if a certain property exists in an object?
JavaScript provides you with three common ways to check if a property exists in an object:

 Use the hasOwnProperty() method - hat returns true if a property exists in an object


 Use the in operator : propertyName in targetObject
 Compare property with undefined - When you access a non-existing property of an object,
you will get undefined. Therefore, you can compare the property with the undefined to
check if a property exists in an object. If an object has a property whose value is undefined,
then comparing the property with undefined will return an incorrect result.

60. What is AJAX?


Asynchronous JavaScript And XML. Ajax is a set of web development techniques using many
web technologies on the client-side to create asynchronous web applications. With Ajax, web
applications can send and retrieve data from a server asynchronously without interfering with
the display and behaviour of the existing page
61. What are the ways of making objects in JavaScript?
There are four ways to create an object in JavaScript
- using object literals
- using the function constructor
- using the Object.create method
- using the class keyword (which is almost the same as using a function constructor).

62. What's the difference between Object.seal and Object.freeze methods?


Object. freeze() makes an object immune to everything even little changes cannot be
made. Object. seal() prevents from deletion of existing properties but cannot prevent them
from external changes.

63. What's the difference between the in operator and the hasOwnProperty method in objects?
he key difference is that in will return true for inherited properties,
whereas hasOwnProperty() will return false for inherited properties

64. What are the ways to deal with Asynchronous Code in JavaScript?
async keyword placed before a function and the keyword await makes JavaScript wait until
that promise settles and returns its result. alert(result); // "done!" f(); Prepending
the async keyword to any function means that the function will return a promise and wraps
non-promises in it.

65. What's the difference between a function expression and function declaration?
The main difference between a function expression and a function declaration
is the function name, which can be omitted in function expressions to create
anonymous functions. A function expression can be used as an IIFE (Immediately
Invoked Function Expression) which runs as soon as it is defined.
66. How many ways can a function be invoked?
4 ways:
1. Invoking functions as functions
2.Invoking functions as object methods
3. Invoking functions as constructors: using the new keyword
4. Invoking function with  apply() and call() methods

67. What is memoization and what's the use it?


Memoization is a technique for improving the performance of recursive algorithms. It
involves rewriting the recursive algorithm so that as answers to problems are found, they are
stored in an array. Recursive calls can look up results in the array rather than having to
recalculate them.

68. Implement a memoization helper function.


function memoize(fn) {
const cache = {};
return function (param) {
if (cache[param]) {
console.log('cached');
return cache[param];
} else {
let result = fn(param);
cache[param] = result;
console.log(`not cached`);
return result;
}
}
}
const toUpper = (str ="")=> str.toUpperCase();
const toUpperMemoized = memoize(toUpper);
toUpperMemoized("abcdef");
toUpperMemoized("abcdef");
This memoize helper function only works on a function that accepts one argument. We need to
make a memoize helper function that accepts multiple arguments.

const slice = Array.prototype.slice;


function memoize(fn) {
const cache = {};
return (...args) => {
const params = slice.call(args);
console.log(params);
if (cache[params]) {
console.log('cached');
return cache[params];
} else {
let result = fn(...args);
cache[params] = result;
console.log(`not cached`);
return result;
}
}
}
const makeFullName = (fName, lName) => `${fName} ${lName}`;
const reduceAdd = (numbers, startingValue = 0) => numbers.reduce((total, cur) => total + cur,
startingValue);
const memoizedMakeFullName = memoize(makeFullName);
const memoizedReduceAdd = memoize(reduceAdd);
memoizedMakeFullName("Marko", "Polo");
memoizedMakeFullName("Marko", "Polo");
memoizedReduceAdd([1, 2, 3, 4, 5], 5);
memoizedReduceAdd([1, 2, 3, 4, 5], 5);
69. Why does typeof null return object? How to check if a value is null?
The value null represents the intentional absence of any object value. This contrasts null from the
similar primitive value undefined , which is an unintentional absence of any object value.That is
because a variable that has been declared but not assigned any value is undefined, not null.
The simplest way to check for null is to know that null evaluates to false in conditionals or if
coerced to a boolean value
70. What does the new keyword do?
The new keyword does the following things:
1. Creates a blank, plain JavaScript object.
2. Adds a property to the new object (__proto__) that links to the constructor function's
prototype object
3. Binds the newly created object instance as the this context (i.e. all references to this in the
constructor function now refer to the object created in the first step).
4. Returns this if the function doesn't return an object.

You might also like