60 JavaScript Interview Questions

60 JavaScript Interview Questions

I Have been working with JS, in beginning it was hard but lately, I fell in love with Javascript, my love for JS is growing to .

Also would love to listen to your all story with JS


Let's Begin With 60 Js Interview Questions

Alt Text


Table Of Context
1. What is the difference between Call & Apply?
2. How to empty an array in JavaScript?
3. What is the difference between the function declarations below?
4. How do you check if an object is an array or not?
5. What is the difference between undefined and not defined in JavaScript?
6. What are JavaScript Data Types?
7. What is Callback?
8. What is Closure?
9.How to create a cookie using JavaScript?
10. List out the different ways an HTML element can be accessed in a JavaScript code
11. What is the difference between Local storage & Session storage?
12. What is the difference between the operators ‘==‘ & ‘===‘?
13. What is the purpose of the array slice method?
14. What is the purpose of the array splice method?
15. Difference between attributes and property?
16. What do you mean by Event Bubbling and Event Capturing?
17. What is a first-class function?
18. What is a higher-order function?
19. What is a pure function?
20. Difference between let and var?
21. What is memorization?
22. What is Hoisting?
23. What are closures?
24. What is a service worker?
25. What is a strict mode in javascript?
26. What is the difference between the window and the document?
27. What is the use of the preventDefault method?
28. What are the pros and cons of functional programming vs object-oriented programming?
29. What is the purpose JSON stringify?
30. What are js labels
31. What is a spread operator?
32. How do you copy properties from one object to other
33. What is V8 JavaScript engine
34. What is a destructuring assignment
35. What are dynamic imports?
36. How do you combine two or more arrays
37. How do you create a specific number of copies of a string
Some Array Methods
38. every()
39. filter()
40. forEach()
41. copyWithin()
42. entries()
43. every()
44. filter()
45. find()
46. forEach()
47. indexOf()
48. map()
49. push()
50. reduce()
51. sort()
52. slice
53. How do you prevent promises swallowing errors
54. How do you check an object is a promise or not?
55. How to detect if a function is called as a constructor
56. What are the d####ifferences between the arguments object and the rest parameter?
57. What are the differences between the spread operator and the rest parameter?
58. What are the built-in iterables
59. What are the differences between for...of and for...in statements
60. How do you create a specific number of copies of a string

1. What is the difference between Call and Apply?


A. The call() method calls a function with a given value and arguments provided individually. Syntax- fun.call(thisArg[, arg1[, arg2[, ...]]])
The apply() method calls a function with a given this value, and arguments provided as an array. Syntax-
fun.apply(thisArg, [argsArray])

2. How To Empty An Array in Javascript?


A. There are a number of methods you can use to empty an array: Method 1 –
javascript arrayList = []
The above code will set the variable ArrayList to a new empty array. This is recommended if you don’t have references to the original array ArrayList anywhere else because it will actually create a new, empty array. You should be careful with this method of emptying the array, because if you have referenced this array from another variable, then the original reference array will remain unchanged.
Method 2 –
arrayList.length = 0;
The code above will clear the existing array by setting its length to 0. This way of emptying the array also updates all the reference variables that point to the original array. Therefore, this method is useful when you want to update all reference variables pointing to arrayList.
Method 3 –
arrayList.splice(0, arrayList.length);
The implementation above will also work perfectly. This way of emptying the array will also update all the references to the original array.
Method 4 –
while(arrayList.length) { arrayList.pop(); }
The implementation above can also empty arrays, but it is usually not recommended to use this method often.

3. What is the difference between the function declarations below?


function bar(){ // Some code };
var foo = function(){ // Some code };
A. The main difference is the function foo is defined at run-time whereas the function bar is defined at parse time. To understand this in a better way, let's take a look at the code below:
Run-Time function declaration
<script> foo(); // Calling foo function here will give an Error var foo = function(){ console.log("Hi I am inside Foo"); }; </script>
<script> Parse-Time function declaration bar(); // Calling foo function will not give an Error function bar(){ console.log("Hi I am inside Foo"); }; </script>
Another advantage of this first-one way of declaration is that you can declare functions based on certain conditions. For example:
<script> if(testCondition) {// If testCondition is true then var foo = function(){ console.log("inside Foo with testCondition True value"); }; }else{ var foo = function(){ console.log("inside Foo with testCondition false value"); }; } </script>
However, if you try to run similar code using the format below, you'd get an error:
<script> if(testCondition) {// If testCondition is true then function foo(){ console.log("inside Foo with testCondition True value"); }; }else{ function foo(){ console.log("inside Foo with testCondition false value"); }; } </script>

4. How do you check if an object is an array or not?


A. The best way to find out whether or not an object is an instance of a particular class is to use the toString method from Object.prototype:
var arrayList = [1,2,3];
One of the best use cases of type-checking an object is when we do method overloading in JavaScript. For example, let's say we have a method called greet, which takes one single string and also a list of strings. To make our greet method workable in both situations, we need to know what kind of parameter is being passed. Is it a single value or a list of values?
function greet(param){ if(){ // here have to check whether param is array or not }else{ } }
However, as the implementation above might not necessarily check the type for arrays, we can check for a single value string and put some array logic code in the else block. For example:
function greet(param){ if(typeof param === 'string'){ }else{ // If param is of type array then this block of code would execute } }
Now it's fine we can go with either of the aforementioned two implementations, but when we have a situation where the parameter can be a single value, array, and object type, we will be in trouble.
Coming back to check the type of an object, as mentioned previously we can use Object.prototype.toString
if( Object.prototype.toString.call( arrayList ) === '[object Array]' ) { console.log('Array!'); }
If you are using jQuery, then you can also use the jQuery isArray method:
if($.isArray(arrayList)){ console.log('Array'); }else{ console.log('Not an array'); }
FYI, jQuery uses Object.prototype.toString.call internally to check whether an object is an array or not.
In modern browsers, you can also use
Array.isArray(arrayList);
Array.isArray is supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5, and Safari 5

5. What is the difference between undefined and not defined in JavaScript?


A. In JavaScript, if you try to use a variable that doesn't exist and has not been declared, then JavaScript will throw an error var name is not defined and the script will stop executing. However, if you use typeof undeclared_variable, then it will return undefined.
Before getting further into this, let's first understand the difference between declaration and definition.
Let's say var x is a declaration because you have not defined what value it holds yet, but you have declared its existence and the need for memory allocation.
var x; // declaring x console.log(x); //output: undefined
Here var x = 1 is both a declaration and definition (also we can say we are doing an initialization). In the example above, the declaration and assignment of value happen inline for variable x. In JavaScript, every variable or function declaration you bring to the top of its current scope is called hoisting.
The assignment happens in order, so when we try to access a variable that is declared but not defined yet, we will get the result undefined.
var x; // Declaration if(typeof x === 'undefined') // Will return true
If a variable is neither declared nor defined, when we try to reference such a variable we'd get the result not defined.
console.log(y); // Output: ReferenceError: y is not defined

6. What are JavaScript Data Types?


A.
Number String Boolean Object Undefined

7. What is Callback?


A. A callback is a plain JavaScript function passed to some method as an argument or option. It is a function that is to be executed after another function has finished executing, hence the name ‘call back‘. In JavaScript, functions are objects. Because of this, functions can take functions as arguments and can be returned by other functions.

8. What is Closure?


A. A closure is a function defined inside another function (called the parent function) and has access to variables that are declared and defined in the parent function scope.
The closure has access to variables in three scopes:
Variables declared in their own scope Variables declared in a parent function scope Variables declared in the global namespace
var globalVar = "abc"; // Parent self invoking function (function outerFunction (outerArg) { // begin of scope outerFunction // Variable declared in outerFunction function scope var outerFuncVar = 'x'; // Closure self-invoking function (function innerFunction (innerArg) { // begin of scope innerFunction // variable declared in innerFunction function scope var innerFuncVar = "y"; console.log( "outerArg = " + outerArg + "\n" + "outerFuncVar = " + outerFuncVar + "\n" + "innerArg = " + innerArg + "\n" + "innerFuncVar = " + innerFuncVar + "\n" + "globalVar = " + globalVar); }// end of scope innerFunction)(5); // Pass 5 as parameter }// end of scope outerFunction )(7); // Pass 7 as parameter
innerfunction is a closure that is defined inside outerFunction and has access to all variables declared and defined in the outerFunction scope. In addition, the function defined inside another function as a closure will have access to variables declared in the global namespace.
Thus, the output of the code above would be:
outerArg = 7 outerFuncVar = x innerArg = 5 innerFuncVar = y globalVar = abc

9. How to create a cookie using JavaScript?


A. The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this-
Syntax : document.cookie = "key1 = value1; key2 = value2; expires = date";

10. List out the different ways an HTML element can be accessed in a JavaScript code.


A. Here are the list of ways an HTML element can be accessed in a Javascript code:
getElementById(‘idname’): Gets an element by its ID name getElementsByClass(‘classname’): Gets all the elements that have the given classname. getElementsByTagName(‘tagname’): Gets all the elements that have the given tag name. querySelector(): This function takes css style selector and returns the first selected element.

11. What is the difference between Local storage & Session storage?


A. Local Storage – The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) – reducing the amount of traffic between client and server. It will stay until it is manually cleared through settings or programs.
Session Storage – It is similar to local storage; the only difference is while data stored in local storage has no expiration time, data stored in session storage gets cleared when the page session ends. Session Storage will leave when the browser is closed.

12. What is the difference between the operators ‘==‘ & ‘===‘?


A. The main difference between “==” and “===” operator is that formerly compares variable by making type correction e.g. if you compare a number with a string with numeric literal, == allows that, but === doesn’t allow that, because it not only checks the value but also the type of two variable if two variables are not of the same type “===” return false, while “==” returns true.

13. What is the purpose of the array slice method?


A. The slice() method returns the selected elements in an array as a new array object. It selects the elements starting at the given start argument, and ends at the given optional end argument without including the last element. If you omit the second argument then it selects till the end. Some of the examples of this method are:
let arrayIntegers = [1, 2, 3, 4, 5]; let arrayIntegers1 = arrayIntegers.slice(0,2); // returns [1,2] let arrayIntegers2 = arrayIntegers.slice(2,3); // returns [3] let arrayIntegers3 = arrayIntegers.slice(4); //returns [5]

14. What is the purpose of the array splice method?


A. The splice() method is used either adds/removes items to/from an array, and then returns the removed item. The first argument specifies the array position for insertion or deletion whereas the optional second argument indicates the number of elements to be deleted. Each additional argument is added to the array. Some of the examples of this method are
let arrayIntegersOriginal1 = [1, 2, 3, 4, 5]; let arrayIntegersOriginal2 = [1, 2, 3, 4, 5]; let arrayIntegersOriginal3 = [1, 2, 3, 4, 5]; let arrayIntegers1 = arrayIntegersOriginal1.splice(0,2); // returns [1, 2]; original array: [3, 4, 5] let arrayIntegers2 = arrayIntegersOriginal2.splice(3); // returns [4, 5]; original array: [1, 2, 3] let arrayIntegers3 = arrayIntegersOriginal3.splice(3, 1, "a", "b", "c"); //returns [4]; original array: [1, 2, 3, "a", "b", "c", 5]

15. Difference between attributes and property?


A. JS DOM objects have properties that are like instance variables for particular elements. A property can be of various data types. Properties are accessible by interacting with the object in Vanilla JS or using jQuery’s prop() method.
Rather than in the DOM, attributes are in the HTML. They are similar to properties but not as capable. It’s recommended to work with properties rather than attributes if the former is available. Unlike a property, an attribute is of the string data type

16. What do you mean by Event Bubbling and Event Capturing?


A. There are two ways for accomplishing event propagation and the order in which an event is received in the HTML DOM API.
These are Event Bubbling and Event Capturing. In the former, the event is directed towards its intended target, whereas the event goes down to the element in the latter.
Event Capturing – Also known as trickling, Event Capturing is rarely used. The process starts with the outermost element capturing the event and then propagating the same to the innermost element.
Event Bubbling – In this process, the event gets handled by the innermost element first and then propagated to the outermost element.

17. What is a first-class function?


A. 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.
const handler = () => console.log ('This is a click handler function'); document.addEventListener ('click', handler);

18. What is a higher-order function?


A. Higher-order function is a function that accepts another function as an argument or returns a function as a return value.
const firstOrderFunc = () => console.log ('Hello I am a First order function'); const higherOrder = ReturnFirstOrderFunc => ReturnFirstOrderFunc (); higherOrder (firstOrderFunc);

19. What is a pure function?


A. 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 6 console.log (numberArray); // returns [6] console.log (pureAddNumber (7) (numberArray)); // returns [6, 7] console.log (numberArray); // returns [6]
As per the above code snippets, the Push function is impures itself by altering the array and returning a push number index which is independent of the parameter value. Whereas Concat on the other hand takes the array and concatenates it with the other array producing a whole new array without side effects. Also, the return value is a concatenation of the previous array. Remember that 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.

20. Difference between let and var?


A. You can list out the differences in a tabular format
var let It is been available from the beginning of JavaScript Introduced as part of ES6 It has function scope It has block scope Variables will be hoisted Hoisted but not initialized Let's take an example to see the difference,
function userDetails(username) { if(username) { console.log(salary); // undefined(due to hoisting) console.log(age); // error: age is not defined 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) }

21. What is memorization?


A. Memoization is a programming technique that 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. Let's take an example of adding function with memoization,
const memoizAddition = () => { let cache = {}; return (value) => { if (value in cache) { console.log('Fetching from cache'); return cache[value]; // Here, cache.value cannot be used as the property name starts with the number which is not a valid JavaScript identifier. Hence, can only be accessed using the square bracket notation. } else { console.log('Calculating result'); let result = value + 20; cache[value] = result; return result; } } } // returned function from memoizAddition const addition = memoizAddition(); console.log(addition(20)); //output: 40 calculated console.log(addition(20)); //output: 40 cached

22. What is Hoisting?


A. Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. Remember that JavaScript only hoists declarations, not initialization. Let's take a simple example of variable hoisting,
console.log(message); //output : undefined var 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';

23. 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 Let's take an example of the closure concept
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(greetingInfo) has access to the variables in the outer function scope(Welcome) even after the outer function has returned.

24. What is a service worker?


A. 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.

25. What is a strict mode in javascript?


A. Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a “strict” operating context. This way it prevents certain actions from being taken and throws more exceptions. The literal expression "use strict"; instructs the browser to use the javascript code in the Strict mode.

26. What is the difference between the window and the document?


A.

Window


- It is the root level element on any web page - By default window object is available implicitly in the page - It has methods like alert(), confirm() and properties like document, location

Document

- It is the direct child of the window object. This is also known as Document Object Model(DOM) - You can access it via window.document or document. - It provides methods like getElementById, getElementByTagName, createElement etc

27. What is the use of preventDefault method?


A. The preventDefault() method cancels the event if it is cancelable, meaning that the default action or behavior that belongs to the event will not occur. For example, prevent form submission when clicking on the submit button and prevent opening the page URL when clicking on hyperlink are some common use cases.
document.getElementById("link").addEventListener("click", function(event){ event.preventDefault(); });
Note: Remember that not all events are cancelable.

28. What are the pros and cons of functional programming vs object-oriented programming?


OOP Pros: It’s easy to understand the basic concept of objects and easy to interpret the meaning of method calls. OOP tends to use an imperative style rather than a declarative style, which reads like a straightforward set of instructions for the computer to follow. OOP Cons: OOP Typically depends on the shared state. Objects and behaviors are typically tacked together on the same entity, which may be accessed at random by any number of functions with non-deterministic order, which may lead to undesirable behavior such as race conditions.
FP Pros: Using the functional paradigm, programmers avoid any shared state or side-effects, which eliminates bugs caused by multiple functions competing for the same resources. With features such as the availability of point-free style (aka tacit programming), functions tend to be radically simplified and easily recomposed for more generally reusable code compared to OOP.
FP also tends to favor declarative and denotational styles, which do not spell out step-by-step instructions for operations but instead concentrate on what to do, letting the underlying functions take care of the how. This leaves tremendous latitude for refactoring and performance optimization, even allowing you to replace entire algorithms with more efficient ones with very little code change. (e.g., memoize, or use lazy evaluation in place of eager evaluation.) The computation that makes use of pure functions is also easy to scale across multiple processors, or across distributed computing clusters without fear of threading resource conflicts, race conditions, etc…
FP Cons: Overexploitation of FP features such as point-free style and large compositions can potentially reduce readability because the resulting code is often more abstractly specified, terser, and less concrete.
More people are familiar with OO and imperative programming than functional programming, so even common idioms in functional programming can be confusing to new team members. FP has a much steeper learning curve than OOP because the broad popularity of OOP has allowed the language and learning materials of OOP to become more conversational, whereas the language of FP tends to be much more academic and formal. FP concepts are frequently written about using idioms and notations from lambda calculus, algebras, and category theory, all of which require a prior knowledge foundation in those domains to be understood.

29. What is the purpose JSON stringify?

A. When sending data to a web server, the data has to be in a string format. You can achieve this by converting a JSON object into a string using the stringify() method.
var userJSON = {'name': 'John', age: 31} var userString = JSON.stringify(user); console.log(userString); //"{"name":"John","age":31}"

30. What are js labels


A. The label statement allows us to name loops and blocks in JavaScript. We can then use these labels to refer back to the code later. For example, the below code with labels avoids printing the numbers when they are the same,
var i, j; loop1: for (i = 0; i < 3; i++) { loop2: for (j = 0; j < 3; j++) { if (i === j) { continue loop1; } console.log('i = ' + i + ', j = ' + j); } } // Output is: // "i = 1, j = 0" // "i = 2, j = 0" // "i = 2, j = 1"

31. What is a spread operator?


A. Spread operator allows iterables( arrays / objects / strings ) to be expanded into single arguments/elements. Let's take an example to see this behavior.
function calculateSum(x, y, z) { return x + y + z; } const numbers = [1, 2, 3]; console.log(calculateSum(...numbers)); // 6

32. How do you copy properties from one object to other


A. You can use the Object.assign() method which is used to copy the values and properties from one or more source objects to a target object. It returns the target object which has properties and values copied from the target object. The syntax would be as below.
Object.assign(target, ...sources)
Let's take an example with one source and one target object,
const target = { a: 1, b: 2 }; const source = { b: 3, c: 4 }; const returnedTarget = Object.assign(target, source); console.log(target); // { a: 1, b: 3, c: 4 } console.log(returnedTarget); // { a: 1, b: 3, c: 4 }
As observed in the above code, there is common property(b) from source to target so its value has been overwritten.

33. What is V8 JavaScript engine


A. V8 is an open-source high-performance JavaScript engine used by the Google Chrome browser, written in C++. It is also being used in the node.js project. It implements ECMAScript and WebAssembly, and runs on Windows 7 or later, macOS 10.12+, and Linux systems that use x64, IA-32, ARM, or MIPS processors. Note: It can run standalone, or can be embedded into any C++ application.

34. What is a destructuring assignment


A. The destructuring assignment is a JavaScript expression that makes it possible to unpack values from arrays or properties from objects into distinct variables. Let's get the month values from an array using a destructuring assignment.
var [one, two, three] = ['JAN', 'FEB', 'MARCH']; console.log(one); // "JAN" console.log(two); // "FEB" console.log(three); // "MARCH"
and you can get user properties of an object using destructuring assignment,
var {name, age} = {name: 'John', age: 32}; console.log(name); // John console.log(age); // 32

35. What are dynamic imports?


A. The dynamic imports using import() function syntax allows us to load modules on demand by using promises or the async/await syntax. Currently, this feature is in the stage4 proposal. The main advantage of dynamic imports is the reduction of our bundle's sizes, the size/payload response of our requests, and overall improvements in the user experience. The syntax of dynamic imports would be as below,
import('./Module').then(Module => Module.method());

36. How do you combine two or more arrays


A. The concat() method is used to join two or more arrays by returning a new array containing all the elements. The syntax would be as below,
array1.concat(array2, array3, ..., arrayX)
Let's take an example of array's concatenation with veggies and fruits arrays,
var veggies = ["Tomato", "Carrot", "Cabbage"]; var fruits = ["Apple", "Orange", "Pears"]; var veggiesAndFruits = veggies.concat(fruits); console.log(veggiesAndFruits); // Tomato, Carrot, Cabbage, Apple, Orange, Pears

37. How do you create a specific number of copies of a string


A. The repeat() method is used to construct and return a new string that contains the specified number of copies of the string on which it was called, concatenated together. Remember that this method has been added to the ECMAScript 2015 specification. Let's take an example of Hello string to repeat it 4 times,
'Hello'.repeat(4); // 'HelloHelloHelloHello'
** Some Array Methods

38. every()


A. JavaScript array every method tests whether all the elements in an array pass the test implemented by the provided function.
Syntax Its syntax is as follows −
array.every(callback[, thisObject]); Parameter Details callback − Function to test for each element.
thisObject − Object to use as this when executing callback. Return Value Returns true if every element in this array satisfies the provided testing function.
Here is a quick example:
if (!Array.prototype.every) { Array.prototype.every = function(fun /*, thisp*/) { var len = this.length; if (typeof fun != "function") throw new TypeError(); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this && !fun.call(thisp, this[i], i, this)) return false; } return true; }; } function isBigEnough(element, index, array) { return (element >= 10); } var passed = [12, 5, 8, 130, 44].every(isBigEnough); document.write("First Test Value : " + passed ); passed = [12, 54, 18, 130, 44].every(isBigEnough); document.write("Second Test Value : " + passed );
Output First Test Value : falseSecond Test Value : true

39. filter()


A. Javascript array filter() method creates a new array with all elements that pass the test implemented by the provided function.
Syntax Its syntax is as follows −
array.filter(callback[, thisObject]); Parameter Details callback − Function to test each element of the array. thisObject − Object to use as this when executing callback. Return Value Returns created array. Quick Example:
if (!Array.prototype.filter) { Array.prototype.filter = function(fun /*, thisp*/) { var len = this.length; if (typeof fun != "function") throw new TypeError(); var res = new Array(); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this) { var val = this[i]; // in case fun mutates this if (fun.call(thisp, val, i, this)) res.push(val); } } return res; }; } function isBigEnough(element, index, array) { return (element >= 10); } var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); document.write("Filtered Value : " + filtered );
Output Filtered Value : 12,130,44

40. forEach()


A. Javascript array forEach() method calls a function for each element in the array.
Syntax Its syntax is as follows −
array.forEach(callback[, thisObject]); Parameter Details callback − Function to test for each element of an array.
thisObject − Object to use as this when executing callback.
Return Value Returns the created array..
var sum = 0; var numbers = [65, 44, 12, 4]; numbers.forEach(myFunction); function myFunction(item) { sum += item; document.getElementById("demo").innerHTML = sum; }
Outputs: Get the sum of the numbers in the array. 125

41. copyWithin()


A. The copyWithin() method copies array elements to another position in the array, overwriting the existing values.


This method will never add more items to the array.


var fruits = ["Banana", "Orange", "Apple", "Mango"];

function myFunction() {  
  document.getElementById("demo").innerHTML = fruits.copyWithin(2,0);
}


Output: Banana, Orange, Banana, Orange


42. entries()


A. The entries() method returns an Array Iterator object with key/value pairs.
For each item in the original array, the new iteration object will contain an array with the index as the key and the item value as the value:
var fruits = ["Banana", "Orange", "Apple", "Mango"]; var f = fruits.entries(); for (x of f) { document.getElementById("demo").innerHTML += x + "<br>"; } Output: 0,Banana 1,Orange 2,Apple 3,Mango

43. every()


A. Every() method checks if all elements in an array pass a test (provided as a function).
The every() method executes the function once for each element present in the array:
If it finds an array element where the function returns a false value, every() returns false (and does not check the remaining values) If no false occur, every() returns true.
var ages = [32, 33, 16, 40]; function checkAdult(age) { return age >= 18; } function myFunction() { ages.every(checkAdult); // Output is false }

44. filter()


A. The filter() method creates an array filled with all array elements that pass a test.
var ages = [32, 33, 16, 40]; function checkAdult(age) { return age >= 18; } function myFunction() { ages.filter(checkAdult); // 32,33,40 is the Output }

45. find()


A. The find() method returns the value of the first element in an array that passes a test. The find() method executes the function once for each element present in the array
var ages = [3, 10, 18, 20]; function checkAdult(age) { return age >= 18; } function myFunction() { ages.find(checkAdult); // 18 Output }

46. forEach()


A. The forEach() method calls a function once for each element in an array, in order. var fruits = ["apple", "orange", "cherry"]; fruits.forEach(myFunction); function myFunction(item, index) { index + ":" + item +"<br />" ; } Output // 1: apple // 2: orange // 3: cherry

47. indexOf()


A. The indexOf() method searches the array for the specified item, and returns its position.
var fruits = ["Banana", "Orange", "Apple", "Mango"]; var a = fruits.indexOf("Apple"); console.log('a') // 2

48. map()


A. The map() method creates a new array with the results of calling a function for every array element.
var numbers = [4, 9, 16, 25]; console.log(numbers.map(Math.sqrt)) // Output: [2, 3, 4, 5]

49. push()


A. The push() method adds new items to the end of an array and returns the new length.
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.push("kiwi") console.log(fruits) ["Banana", "Orange", "Apple", "Mango", "kiwi"]

50. reduce()


The reduce() method reduces the array to a single value
var numbers = [175, 50, 25]; function myFun(total, num){ return total-num;} numbers.reduce(myFun) // Output: 100

51. sort()


A. The sort() method sorts the items of an array.
The sort order can be either alphabetic or numeric, and either ascending (up) or descending (down).
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort() // Output: ["Apple", "Banana", "Mango", "Orange"]

52. slice


A. The slice() method returns the selected elements in an array, as a new array object.
The slice() method selects the elements starting at the given start argument, and ends at, but does not include, the given end argument.
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; console.log(fruits.slice(1,3)) //Output ["Orange", "Lemon"]

53. How do you prevent promises swallowing errors


A. While using asynchronous code, JavaScript’s ES6 promises can make your life a lot easier without having callback pyramids and error handling on every second line. But Promises have some pitfalls and the biggest one is swallowing errors by default.
Let's say you expect to print an error to the console for all the below cases,
Promise.resolve('promised value').then(function() { throw new Error('error'); }); Promise.reject('error value').catch(function() { throw new Error('error'); }); new Promise(function(resolve, reject) { throw new Error('error'); });
But there are many modern JavaScript environments that won't print any errors. You can fix this problem in different ways,
- Add catch block at the end of each chain: You can add catch block to the end of each of your promise chains
Promise.resolve('promised value').then(function() { throw new Error('error'); }).catch(function(error) { console.error(error.stack); });
But it is quite difficult to type for each promise chain and verbose too. - Add done method: You can replace first solution's then and catch blocks with done method
Promise.resolve('promised value').done(function() { throw new Error('error'); });
Let's say you want to fetch data using HTTP and later perform processing on the resulting data asynchronously. You can write done block as below,
getDataFromHttp() .then(function(result) { return processDataAsync(result); }) .done(function(processed) { displayData(processed); });
In the future, if the processing library API changed to synchronous then you can remove the done block as below,
getDataFromHttp() .then(function(result) { return displayData(processDataAsync(result)); })
and then you forgot to add done block to then block leads to silent errors.
- Extend ES6 Promises by Bluebird: Bluebird extends the ES6 Promises API to avoid the issue in the second solution. This library has a “default” onRejection handler which will print all errors from rejected Promises to stderr. After installation, you can process unhandled rejections
Promise.onPossiblyUnhandledRejection(function(error){ throw error; });
and discard a rejection, just handle it with an empty catch Promise.reject('error value').catch(function() {});

54. How do you check an object is a promise or not?


A. If you don't know if a value is a promise or not, wrapping the value as Promise.resolve(value) which returns a promise
function isPromise(object){ if(Promise && Promise.resolve){ return Promise.resolve(object) == object; }else{ throw "Promise not supported in your environment" } } var i = 1; var promise = new Promise(function(resolve,reject){ resolve() }); console.log(isPromise(i)); // false console.log(isPromise(p)); // true
Another way is to check for .then() handler type
function isPromise(value) { return Boolean(value && typeof value.then === 'function'); } var i = 1; var promise = new Promise(function(resolve,reject){ resolve() }); console.log(isPromise(i)) // false console.log(isPromise(promise)); // true.

55. How to detect if a function is called as a constructor


A. You can use new.target pseudo-property to detect whether a function was called as a constructor(using the new operator) or as a regular function call.
- If a constructor or function invoked using the new operator, new.target returns a reference to the constructor or function. - For function calls, new.target is undefined.
function Myfunc() { if (new.target) { console.log('called with new'); } else { console.log('not called with new'); } } new Myfunc(); // called with new Myfunc(); // not called with new Myfunc.call({}); not called with new

56. What are the differences between the argument object and rest parameter?


A. There are three main differences between arguments object and rest parameters


The arguments object is an array-like but not an array. Whereas the rest parameters are array instances. The arguments object does not support methods such as sort, map, forEach, or pop. Whereas these methods can be used in rest parameters. The rest parameters are only the ones that haven’t been given a separate name, while the arguments object contains all arguments passed to the function


57. What are the differences between the spread operator and the rest parameter?


A. The rest parameter collects all remaining elements into an array. Whereas Spread operator allows iterables( arrays / objects / strings ) to be expanded into single arguments/elements. i.e, the Rest parameter is opposite to the spread operator.


58. What are the built-in iterables

Below are the list of built-in iterables in javascript,


A. Arrays and TypedArrays


  • Strings: Iterate over each character or Unicode code-points
  • Maps: iterate over its key-value pairs
  • Sets: iterates over their elements
  • arguments: An array-like special variable in functions
  • DOM collection such as NodeList

59. What are the differences between for...of and for...in statements


A. Both for...in and for...of statements iterate over js data structures. The only difference is over what they iterate:

  • for..in iterates over all enumerable property keys of an object
  • for..of iterates over the values of an iterable object. Let's explain this difference with an example,
let arr = ['a', 'b', 'c'];
arr.newProp = 'newVlue';
// key are the property keys
for (let key in arr) {
  console.log(key);
}


// value are the property values
for (let value of arr) {
  console.log(value);
}


Since for..in loop iterates over the keys of the object, the first loop logs 0, 1, 2, and newProp while iterating over the array object. The for..of loop iterates over the values of an arr data structure and logs a, b, c in the console.


60. How do you create a specific number of copies of a string


A. The repeat() method is used to construct and return a new string that contains the specified number of copies of the string on which it was called, concatenated together. Remember that this method has been added to the ECMAScript 2015 specification. Let's take an example of the Hello string to repeat it 4 times.


'Hello'.repeat(4);  // 'HelloHelloHelloHello'


Disclamer

I have used multiple sources to collect the best of the answers and questions, to help you conquer your next javascript interview.

Refrences


-guru99.com/javascript-interview-questions-a..




Thank You for reading this and hope you liked the post, and if you have any suggestions please make sure to comment on them below.

In case of issue or help feel free to reach me out on twitter🐦

Or GitHub -> github.com/bornmay