Part-4 : 500 JavaScript Important Questions with Answers and Explanation
301-400 JS questions
JavaScript Interview Questions & Answers
Table of Contents
How do you create an infinite loop
You can create infinite loops using for and while loops without using any expressions. The for loop construct or syntax is better approach in terms of ESLint and code optimizer tools,
for (;;) {} while(true) { }
Why do you need to avoid with statement
JavaScript's with statement was intended to provide a shorthand for writing recurring accesses to objects. So it can help reduce file size by reducing the need to repeat a lengthy object reference without performance penalty. Let's take an example where it is used to avoid redundancy when accessing an object several times.
a.b.c.greeting = 'welcome'; a.b.c.age = 32;
Using
with
it turns this into:with(a.b.c) { greeting = "welcome"; age = 32; }
But this
with
statement creates performance problems since one cannot predict whether an argument will refer to a real variable or to a property inside the with argument.What is the output of below for loops
for (var i = 0; i < 4; i++) { // global scope setTimeout(() => console.log(i)); } for (let i = 0; i < 4; i++) { // block scope setTimeout(() => console.log(i)); }
The output of the above for loops is 4 4 4 4 and 0 1 2 3 Explanation: Due to the event queue/loop of javascript, the
setTimeout
callback function is called after the loop has been executed. Since the variable i is declared with thevar
keyword it became a global variable and the value was equal to 4 using iteration when the time setTimeout function is invoked. Hence, the output of the first loop is4 4 4 4
. Whereas in the second loop, the variable i is declared as thelet
keyword it becomes a block scoped variable and it holds a new value(0, 1 ,2 3) for each iteration. Hence, the output of the first loop is0 1 2 3
.List down some of the features of ES6
Below are the list of some new features of ES6,
- Support for constants or immutable variables
- Block-scope support for variables, constants and functions
- Arrow functions
- Default parameters
- Rest and Spread Parameters
- Template Literals
- Multi-line Strings
- Destructuring Assignment
- Enhanced Object Literals
- Promises
- Classes
- Modules
What is ES6
ES6 is the sixth edition of the javascript language and it was released in June 2015. It was initially known as ECMAScript 6 (ES6) and later renamed to ECMAScript 2015. Almost all the modern browsers support ES6 but for the old browsers there are many transpilers, like Babel.js etc.
Can I redeclare let and const variables
No, you cannot redeclare let and const variables. If you do, it throws below error
Uncaught SyntaxError: Identifier 'someVariable' has already been declared
Explanation: The variable declaration with
var
keyword refers to a function scope and the variable is treated as if it were declared at the top of the enclosing scope due to hoisting feature. So all the multiple declarations contributing to the same hoisted variable without any error. Let's take an example of re-declaring variables in the same scope for both var and let/const variables.var name = 'John'; function myFunc() { var name = 'Nick'; var name = 'Abraham'; // Re-assigned in the same function block alert(name); // Abraham } myFunc(); alert(name); // John
The block-scoped multi-declaration throws syntax error,
let name = 'John'; function myFunc() { let name = 'Nick'; let name = 'Abraham'; // Uncaught SyntaxError: Identifier 'name' has already been declared alert(name); } myFunc(); alert(name);
Is const variable makes the value immutable
No, the const variable doesn't make the value immutable. But it disallows subsequent assignments(i.e, You can declare with assignment but can't assign another value later)
const userList = []; userList.push('John'); // Can mutate even though it can't re-assign console.log(userList); // ['John']
What are default parameters
In E5, we need to depend on logical OR operators to handle default values of function parameters. Whereas in ES6, Default function parameters feature allows parameters to be initialized with default values if no value or undefined is passed. Let's compare the behavior with an examples,
//ES5 var calculateArea = function(height, width) { height = height || 50; width = width || 60; return width * height; } console.log(calculateArea()); //300
The default parameters makes the initialization more simpler,
//ES6 var calculateArea = function(height = 50, width = 60) { return width * height; } console.log(calculateArea()); //300
What are template literals
Template literals or template strings are string literals allowing embedded expressions. These are enclosed by the back-tick (`) character instead of double or single quotes. In E6, this feature enables using dynamic expressions as below,
var greeting = `Welcome to JS World, Mr. ${firstName} ${lastName}.`
In ES5, you need break string like below,
var greeting = 'Welcome to JS World, Mr. ' + firstName + ' ' + lastName.`
Note: You can use multi-line strings and string interpolation features with template literals.
How do you write multi-line strings in template literals
In ES5, you would have to use newline escape characters('\n') and concatenation symbols(+) in order to get multi-line strings.
console.log('This is string sentence 1\n' + 'This is string sentence 2');
Whereas in ES6, You don't need to mention any newline sequence character,
console.log(`This is string sentence 'This is string sentence 2`);
What are nesting templates
The nesting template is a feature supported within template literals syntax to allow inner backticks inside a placeholder ${ } within the template. For example, the below nesting template is used to display the icons based on user permissions whereas outer template checks for platform type,
const iconStyles = `icon ${ isMobilePlatform() ? '' : `icon-${user.isAuthorized ? 'submit' : 'disabled'}` }`;
You can write the above use case without nesting template features as well. However, the nesting template feature is more compact and readable.
//Without nesting templates const iconStyles = `icon ${ isMobilePlatform() ? '' : (user.isAuthorized ? 'icon-submit' : 'icon-disabled'}`;
What are tagged templates
Tagged templates are the advanced form of templates in which tags allow you to parse template literals with a function. The tag function accepts the first parameter as an array of strings and remaining parameters as expressions. This function can also return manipulated strings based on parameters. Let's see the usage of this tagged template behavior of an IT professional skill set in an organization,
var user1 = 'John'; var skill1 = 'JavaScript'; var experience1 = 15; var user2 = 'Kane'; var skill2 = 'JavaScript'; var experience2 = 5; function myInfoTag(strings, userExp, experienceExp, skillExp) { var str0 = strings[0]; // "Mr/Ms. " var str1 = strings[1]; // " is a/an " var str2 = strings[2]; // "in" var expertiseStr; if (experienceExp > 10){ expertiseStr = 'expert developer'; } else if(skillExp > 5 && skillExp <= 10) { expertiseStr = 'senior developer'; } else { expertiseStr = 'junior developer'; } return ${str0}${userExp}${str1}${expertiseStr}${str2}${skillExp}; } var output1 = myInfoTag`Mr/Ms. ${ user1 } is a/an ${ experience1 } in ${skill1}`; var output2 = myInfoTag`Mr/Ms. ${ user2 } is a/an ${ experience2 } in ${skill2}`; console.log(output1);// Mr/Ms. John is a/an expert developer in JavaScript console.log(output2);// Mr/Ms. Kane is a/an junior developer in JavaScript
What are raw strings
ES6 provides a raw strings feature using the
String.raw()
method which is used to get the raw string form of template strings. This feature allows you to access the raw strings as they were entered, without processing escape sequences. For example, the usage would be as below,var calculationString = String.raw `The sum of numbers is \n${1+2+3+4}!`; console.log(calculationString); // The sum of numbers is 10
If you don't use raw strings, the newline character sequence will be processed by displaying the output in multiple lines
var calculationString = `The sum of numbers is \n${1+2+3+4}!`; console.log(calculationString); // The sum of numbers is // 10
Also, the raw property is available on the first argument to the tag function
function tag(strings) { console.log(strings.raw[0]); }
What is destructuring assignment
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 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
What are default values in destructuring assignment
A variable can be assigned a default value when the value unpacked from the array or object is undefined during destructuring assignment. It helps to avoid setting default values separately for each assignment. Let's take an example for both arrays and object use cases,
Arrays destructuring:
var x, y, z; [x=2, y=4, z=6] = [10]; console.log(x); // 10 console.log(y); // 4 console.log(z); // 6
Objects destructuring:
var {x=2, y=4, z=6} = {x: 10}; console.log(x); // 10 console.log(y); // 4 console.log(z); // 6
How do you swap variables in destructuring assignment
If you don't use destructuring assignment, swapping two values requires a temporary variable. Whereas using a destructuring feature, two variable values can be swapped in one destructuring expression. Let's swap two number variables in array destructuring assignment,
var x = 10, y = 20; [x, y] = [y, x]; console.log(x); // 20 console.log(y); // 10
What are enhanced object literals
Object literals make it easy to quickly create objects with properties inside the curly braces. For example, it provides shorter syntax for common object property definition as below.
//ES6 var x = 10, y = 20 obj = { x, y } console.log(obj); // {x: 10, y:20} //ES5 var x = 10, y = 20 obj = { x : x, y : y} console.log(obj); // {x: 10, y:20}
What are dynamic imports
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 stage4 proposal. The main advantage of dynamic imports is 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());
What are the use cases for dynamic imports
Below are some of the use cases of using dynamic imports over static imports,
- Import a module on-demand or conditionally. For example, if you want to load a polyfill on legacy browser
if (isLegacyBrowser()) { import(···) .then(···); }
- Compute the module specifier at runtime. For example, you can use it for internationalization.
import(`messages_${getLocale()}.js`).then(···);
- Import a module from within a regular script instead a module.
What are typed arrays
Typed arrays are array-like objects from ECMAScript 6 API for handling binary data. JavaScript provides 8 Typed array types,
- Int8Array: An array of 8-bit signed integers
- Int16Array: An array of 16-bit signed integers
- Int32Array: An array of 32-bit signed integers
- Uint8Array: An array of 8-bit unsigned integers
- Uint16Array: An array of 16-bit unsigned integers
- Uint32Array: An array of 32-bit unsigned integers
- Float32Array: An array of 32-bit floating point numbers
- Float64Array: An array of 64-bit floating point numbers
For example, you can create an array of 8-bit signed integers as below
const a = new Int8Array(); // You can pre-allocate n bytes const bytes = 1024 const a = new Int8Array(bytes)
What are the advantages of module loaders
The module loaders provides the below features,
- Dynamic loading
- State isolation
- Global namespace isolation
- Compilation hooks
- Nested virtualization
What is collation
Collation is used for sorting a set of strings and searching within a set of strings. It is parameterized by locale and aware of Unicode. Let's take comparison and sorting features,
- Comparison:
var list = [ "ä", "a", "z" ]; // In German, "ä" sorts with "a" Whereas in Swedish, "ä" sorts after "z" var l10nDE = new Intl.Collator("de"); var l10nSV = new Intl.Collator("sv"); console.log(l10nDE.compare("ä", "z") === -1); // true console.log(l10nSV.compare("ä", "z") === +1); // true
- Sorting:
var list = [ "ä", "a", "z" ]; // In German, "ä" sorts with "a" Whereas in Swedish, "ä" sorts after "z" var l10nDE = new Intl.Collator("de"); var l10nSV = new Intl.Collator("sv"); console.log(list.sort(l10nDE.compare)) // [ "a", "ä", "z" ] console.log(list.sort(l10nSV.compare)) // [ "a", "z", "ä" ]
What is for...of statement
The for...of statement creates a loop iterating over iterable objects or elements such as built-in String, Array, Array-like objects (like arguments or NodeList), TypedArray, Map, Set, and user-defined iterables. The basic usage of for...of statement on arrays would be as below,
let arrayIterable = [10, 20, 30, 40, 50]; for (let value of arrayIterable) { value ++; console.log(value); // 11 21 31 41 51 }
What is the output of below spread operator array
[...'John Resig']
The output of the array is ['J', 'o', 'h', 'n', '', 'R', 'e', 's', 'i', 'g'] Explanation: The string is an iterable type and the spread operator within an array maps every character of an iterable to one element. Hence, each character of a string becomes an element within an Array.
Is PostMessage secure
Yes, postMessages can be considered very secure as long as the programmer/developer is careful about checking the origin and source of an arriving message. But if you try to send/receive a message without verifying its source will create cross-site scripting attacks.
What are the problems with postmessage target origin as wildcard
The second argument of postMessage method specifies which origin is allowed to receive the message. If you use the wildcard “*” as an argument then any origin is allowed to receive the message. In this case, there is no way for the sender window to know if the target window is at the target origin when sending the message. If the target window has been navigated to another origin, the other origin would receive the data. Hence, this may lead to XSS vulnerabilities.
targetWindow.postMessage(message, '*');
How do you avoid receiving postMessages from attackers
Since the listener listens for any message, an attacker can trick the application by sending a message from the attacker’s origin, which gives an impression that the receiver received the message from the actual sender’s window. You can avoid this issue by validating the origin of the message on the receiver's end using the “message.origin” attribute. For examples, let's check the sender's origin http://www.some-sender.com on receiver side www.some-receiver.com,
//Listener on http://www.some-receiver.com/ window.addEventListener("message", function(message){ if(/^http://www\.some-sender\.com$/.test(message.origin)){ console.log('You received the data from valid sender', message.data); } });
Can I avoid using postMessages completely
You cannot avoid using postMessages completely(or 100%). Even though your application doesn’t use postMessage considering the risks, a lot of third party scripts use postMessage to communicate with the third party service. So your application might be using postMessage without your knowledge.
Is postMessages synchronous
The postMessages are synchronous in IE8 browser but they are asynchronous in IE9 and all other modern browsers (i.e, IE9+, Firefox, Chrome, Safari).Due to this asynchronous behaviour, we use a callback mechanism when the postMessage is returned.
What paradigm is Javascript
JavaScript is a multi-paradigm language, supporting imperative/procedural programming, Object-Oriented Programming and functional programming. JavaScript supports Object-Oriented Programming with prototypical inheritance.
What is the difference between internal and external javascript
Internal JavaScript: It is the source code within the script tag. External JavaScript: The source code is stored in an external file(stored with .js extension) and referred with in the tag.
Is JavaScript faster than server side script
Yes, JavaScript is faster than server side script. Because JavaScript is a client-side script it does not require any web server’s help for its computation or calculation. So JavaScript is always faster than any server-side script like ASP, PHP, etc.
How do you get the status of a checkbox
You can apply the
checked
property on the selected checkbox in the DOM. If the value isTrue
means the checkbox is checked otherwise it is unchecked. For example, the below HTML checkbox element can be access using javascript as below,<input type="checkbox" name="checkboxname" value="Agree"> Agree the conditions<br>
console.log(document.getElementById(‘checkboxname’).checked); // true or false
What is the purpose of double tilde operator
The double tilde operator(~~) is known as double NOT bitwise operator. This operator is going to be a quicker substitute for Math.floor().
How do you convert character to ASCII code
You can use the
String.prototype.charCodeAt()
method to convert string characters to ASCII numbers. For example, let's find ASCII code for the first letter of 'ABC' string,"ABC".charCodeAt(0) // returns 65
Whereas
String.fromCharCode()
method converts numbers to equal ASCII characters.String.fromCharCode(65,66,67); // returns 'ABC'
What is ArrayBuffer
An ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. You can create it as below,
let buffer = new ArrayBuffer(16); // create a buffer of length 16 alert(buffer.byteLength); // 16
To manipulate an ArrayBuffer, we need to use a “view” object.
//Create a DataView referring to the buffer let view = new DataView(buffer);
What is the output of below string expression
console.log("Welcome to JS world"[0])
The output of the above expression is "W". Explanation: The bracket notation with specific index on a string returns the character at a specific location. Hence, it returns the character "W" of the string. Since this is not supported in IE7 and below versions, you may need to use the .charAt() method to get the desired result.
What is the purpose of Error object
The Error constructor creates an error object and the instances of error objects are thrown when runtime errors occur. The Error object can also be used as a base object for user-defined exceptions. The syntax of error object would be as below,
new Error([message[, fileName[, lineNumber]]])
You can throw user defined exceptions or errors using Error object in try...catch block as below,
try { if(withdraw > balance) throw new Error("Oops! You don't have enough balance"); } catch (e) { console.log(e.name + ': ' + e.message); }
What is the purpose of EvalError object
The EvalError object indicates an error regarding the global
eval()
function. Even though this exception is not thrown by JavaScript anymore, the EvalError object remains for compatibility. The syntax of this expression would be as below,new EvalError([message[, fileName[, lineNumber]]])
You can throw EvalError with in try...catch block as below,
try { throw new EvalError('Eval function error', 'someFile.js', 100); } catch (e) { console.log(e.message, e.name, e.fileName); // "Eval function error", "EvalError", "someFile.js"
What are the list of cases error thrown from non-strict mode to strict mode
When you apply 'use strict'; syntax, some of the below cases will throw a SyntaxError before executing the script
- When you use Octal syntax
var n = 022;
- Using
with
statement - When you use delete operator on a variable name
- Using eval or arguments as variable or function argument name
- When you use newly reserved keywords
- When you declare a function in a block
if (someCondition) { function f() {} }
Hence, the errors from above cases are helpful to avoid errors in development/production environments.
Is all objects have prototypes
No. All objects have prototypes except for the base object which is created by the user, or an object that is created using the new keyword.
What is the difference between a parameter and an argument
Parameter is the variable name of a function definition whereas an argument represents the value given to a function when it is invoked. Let's explain this with a simple function
function myFunction(parameter1, parameter2, parameter3) { console.log(arguments[0]) // "argument1" console.log(arguments[1]) // "argument2" console.log(arguments[2]) // "argument3" } myFunction("argument1", "argument2", "argument3")
What is the purpose of some method in arrays
The some() method is used to test whether at least one element in the array passes the test implemented by the provided function. The method returns a boolean value. Let's take an example to test for any odd elements,
var array = [1, 2, 3, 4, 5, 6 ,7, 8, 9, 10]; var odd = element ==> element % 2 !== 0; console.log(array.some(odd)); // true (the odd element exists)
How do you combine two or more arrays
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
What is the difference between Shallow and Deep copy
There are two ways to copy an object,
Shallow Copy: Shallow copy is a bitwise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.
Example
var empDetails = { name: "John", age: 25, expertise: "Software Developer" }
to create a duplicate
var empDetailsShallowCopy = empDetails //Shallow copying!
if we change some property value in the duplicate one like this:
empDetailsShallowCopy.name = "Johnson"
The above statement will also change the name of
empDetails
, since we have a shallow copy. That means we're losing the original data as well.Deep copy: A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.
Example
var empDetails = { name: "John", age: 25, expertise: "Software Developer" }
Create a deep copy by using the properties from the original object into new variable
var empDetailsDeepCopy = { name: empDetails.name, age: empDetails.age, expertise: empDetails.expertise }
Now if you change
empDetailsDeepCopy.name
, it will only affectempDetailsDeepCopy
& notempDetails
How do you create specific number of copies of a string
The
repeat()
method is used to construct and return a new string which 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'
How do you return all matching strings against a regular expression
The
matchAll()
method can be used to return an iterator of all results matching a string against a regular expression. For example, the below example returns an array of matching string results against a regular expression,let regexp = /Hello(\d?))/g; let greeting = 'Hello1Hello2Hello3'; let greetingList = [...greeting.matchAll(regexp)]; console.log(greetingList[0]); //Hello1 console.log(greetingList[1]); //Hello2 console.log(greetingList[2]); //Hello3
How do you trim a string at the beginning or ending
The
trim
method of string prototype is used to trim on both sides of a string. But if you want to trim especially at the beginning or ending of the string then you can usetrimStart/trimLeft
andtrimEnd/trimRight
methods. Let's see an example of these methods on a greeting message,var greeting = ' Hello, Goodmorning! '; console.log(greeting); // " Hello, Goodmorning! " console.log(greeting.trimStart()); // "Hello, Goodmorning! " console.log(greeting.trimLeft()); // "Hello, Goodmorning! " console.log(greeting.trimEnd()); // " Hello, Goodmorning!" console.log(greeting.trimRight()); // " Hello, Goodmorning!"
What is the output of below console statement with unary operator
Let's take console statement with unary operator as given below,
console.log(+ 'Hello');
The output of the above console log statement returns NaN. Because the element is prefixed by the unary operator and the JavaScript interpreter will try to convert that element into a number type. Since the conversion fails, the value of the statement results in NaN value.
Does javascript uses mixins
What is a thunk function
A thunk is just a function which delays the evaluation of the value. It doesn’t take any arguments but gives the value whenever you invoke the thunk. i.e, It is used not to execute now but it will be sometime in the future. Let's take a synchronous example,
const add = (x,y) => x + y; const thunk = () => add(2,3); thunk() // 5
What are asynchronous thunks
The asynchronous thunks are useful to make network requests. Let's see an example of network requests,
function fetchData(fn){ fetch('https://jsonplaceholder.typicode.com/todos/1') .then(response => response.json()) .then(json => fn(json)) } const asyncThunk = function (){ return fetchData(function getData(data){ console.log(data) }) } asyncThunk()
The
getData
function won't be called immediately but it will be invoked only when the data is available from API endpoint. The setTimeout function is also used to make our code asynchronous. The best real time example is redux state management library which uses the asynchronous thunks to delay the actions to dispatch.What is the output of below function calls
Code snippet:
const circle = { radius: 20, diameter() { return this.radius * 2; }, perimeter: () => 2 * Math.PI * this.radius };
console.log(circle.diameter()); console.log(circle.perimeter());
Output:
The output is 40 and NaN. Remember that diameter is a regular function, whereas the value of perimeter is an arrow function. The
this
keyword of a regular function(i.e, diameter) refers to the surrounding scope which is a class(i.e, Shape object). Whereas this keyword of perimeter function refers to the surrounding scope which is a window object. Since there is no radius property on window objects it returns an undefined value and the multiple of number value returns NaN value.How to remove all line breaks from a string
The easiest approach is using regular expressions to detect and replace newlines in the string. In this case, we use replace function along with string to replace with, which in our case is an empty string.
function remove_linebreaks( var message ) { return message.replace( /[\r\n]+/gm, "" ); }
In the above expression, g and m are for global and multiline flags.
What is the difference between reflow and repaint
A repaint occurs when changes are made which affect the visibility of an element, but not its layout. Examples of this include outline, visibility, or background color. A reflow involves changes that affect the layout of a portion of the page (or the whole page). Resizing the browser window, changing the font, content changing (such as user typing text), using JavaScript methods involving computed styles, adding or removing elements from the DOM, and changing an element's classes are a few of the things that can trigger reflow. Reflow of an element causes the subsequent reflow of all child and ancestor elements as well as any elements following it in the DOM.
What happens with negating an array
Negating an array with
!
character will coerce the array into a boolean. Since Arrays are considered to be truthy So negating it will returnfalse
.console.log(![]); // false
What happens if we add two arrays
If you add two arrays together, it will convert them both to strings and concatenate them. For example, the result of adding arrays would be as below,
console.log(['a'] + ['b']); // "ab" console.log([] + []); // "" console.log(![] + []); // "false", because ![] returns false.
What is the output of prepend additive operator on falsy values
If you prepend the additive(+) operator on falsy values(null, undefined, NaN, false, ""), the falsy value converts to a number value zero. Let's display them on browser console as below,
console.log(+null); // 0 console.log(+undefined);// NaN console.log(+false); // 0 console.log(+NaN); // NaN console.log(+""); // 0
How do you create self string using special characters
The self string can be formed with the combination of
[]()!+
characters. You need to remember the below conventions to achieve this pattern.- Since Arrays are truthful values, negating the arrays will produce false: ![] === false
- As per JavaScript coercion rules, the addition of arrays together will toString them: [] + [] === ""
- Prepend an array with + operator will convert an array to false, the negation will make it true and finally converting the result will produce value '1': +(!(+[])) === 1
By applying the above rules, we can derive below conditions
![] + [] === "false" +!+[] === 1
Now the character pattern would be created as below,
s e l f ^^^^^^^^^^^^^ ^^^^^^^^^^^^^ ^^^^^^^^^^^^^ ^^^^^^^^^^^^^ (![] + [])[3] + (![] + [])[4] + (![] + [])[2] + (![] + [])[0] ^^^^^^^^^^^^^ ^^^^^^^^^^^^^ ^^^^^^^^^^^^^ ^^^^^^^^^^^^^ (![] + [])[+!+[]+!+[]+!+[]] + (![] + [])[+!+[]+!+[]+!+[]+!+[]] + (![] + [])[+!+[]+!+[]] + (![] + [])[+[]] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ (![]+[])[+!+[]+!+[]+!+[]]+(![]+[])[+!+[]+!+[]+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+[]]
How do you remove falsy values from an array
You can apply the filter method on the array by passing Boolean as a parameter. This way it removes all falsy values(0, undefined, null, false and "") from the array.
const myArray = [false, null, 1,5, undefined] myArray.filter(Boolean); // [1, 5] // is same as myArray.filter(x => x);
How do you get unique values of an array
You can get unique values of an array with the combination of
Set
and rest expression/spread(...) syntax.console.log([...new Set([1, 2, 4, 4, 3])]); // [1, 2, 4, 3]
What is destructuring aliases
Sometimes you would like to have a destructured variable with a different name than the property name. In that case, you'll use a
: newName
to specify a name for the variable. This process is called destructuring aliases.const obj = { x: 1 }; // Grabs obj.x as as { otherName } const { x: otherName } = obj;
How do you map the array values without using map method
You can map the array values without using the
map
method by just using thefrom
method of Array. Let's map city names from Countries array,const countries = [ { name: 'India', capital: 'Delhi' }, { name: 'US', capital: 'Washington' }, { name: 'Russia', capital: 'Moscow' }, { name: 'Singapore', capital: 'Singapore' }, { name: 'China', capital: 'Beijing' }, { name: 'France', capital: 'Paris' }, ]; const cityNames = Array.from(countries, ({ capital}) => capital); console.log(cityNames); // ['Delhi, 'Washington', 'Moscow', 'Singapore', 'Beijing', 'Paris']
How do you empty an array
You can empty an array quickly by setting the array length to zero.
let cities = ['Singapore', 'Delhi', 'London']; cities.length = 0; // cities becomes []
How do you rounding numbers to certain decimals
You can round numbers to a certain number of decimals using
toFixed
method from native javascript.let pie = 3.141592653; pie = pie.toFixed(3); // 3.142
What is the easiest way to convert an array to an object
You can convert an array to an object with the same data using spread(...) operator.
var fruits = ["banana", "apple", "orange", "watermelon"]; var fruitsObject = {...fruits}; console.log(fruitsObject); // {0: "banana", 1: "apple", 2: "orange", 3: "watermelon"}
How do you create an array with some data
You can create an array with some data or an array with the same values using
fill
method.var newArray = new Array(5).fill("0"); console.log(newArray); // ["0", "0", "0", "0", "0"]
What are the placeholders from console object
Below are the list of placeholders available from console object,
- %o — It takes an object,
- %s — It takes a string,
- %d — It is used for a decimal or integer These placeholders can be represented in the console.log as below
const user = { "name":"John", "id": 1, "city": "Delhi"}; console.log("Hello %s, your details %o are available in the object form", "John", user); // Hello John, your details {name: "John", id: 1, city: "Delhi"} are available in object
Is it possible to add CSS to console messages
Yes, you can apply CSS styles to console messages similar to html text on the web page.
console.log('%c The text has blue color, with large font and red background', 'color: blue; font-size: x-large; background: red');
The text will be displayed as below,
Note: All CSS styles can be applied to console messages.
What is the purpose of dir method of console object
The
console.dir()
is used to display an interactive list of the properties of the specified JavaScript object as JSON.const user = { "name":"John", "id": 1, "city": "Delhi"}; console.dir(user);
The user object displayed in JSON representation
Is it possible to debug HTML elements in console
Yes, it is possible to get and debug HTML elements in the console just like inspecting elements.
const element = document.getElementsByTagName("body")[0]; console.log(element);
It prints the HTML element in the console,
How do you display data in a tabular format using console object
The
console.table()
is used to display data in the console in a tabular format to visualize complex arrays or objects.const users = [{ "name":"John", "id": 1, "city": "Delhi"}, { "name":"Max", "id": 2, "city": "London"}, { "name":"Rod", "id": 3, "city": "Paris"} ]; console.table(users);
The data visualized in a table format,
Not: Remember that
console.table()
is not supported in IE.How do you verify that an argument is a Number or not
The combination of IsNaN and isFinite methods are used to confirm whether an argument is a number or not.
function isNumber(n){ return !isNaN(parseFloat(n)) && isFinite(n); }
How do you create copy to clipboard button
You need to select the content(using .select() method) of the input element and execute the copy command with execCommand (i.e, execCommand('copy')). You can also execute other system commands like cut and paste.
document.querySelector("#copy-button").onclick = function() { // Select the content document.querySelector("#copy-input").select(); // Copy to the clipboard document.execCommand('copy'); };
What is the shortcut to get timestamp
You can use
new Date().getTime()
to get the current timestamp. There is an alternative shortcut to get the value.console.log(+new Date()); console.log(Date.now());
How do you flattening multi dimensional arrays
Flattening bi-dimensional arrays is trivial with Spread operator.
const biDimensionalArr = [11, [22, 33], [44, 55], [66, 77], 88, 99]; const flattenArr = [].concat(...biDimensionalArr); // [11, 22, 33, 44, 55, 66, 77, 88, 99]
But you can make it work with multi-dimensional arrays by recursive calls,
function flattenMultiArray(arr) { const flattened = [].concat(...arr); return flattened.some(item => Array.isArray(item)) ? flattenMultiArray(flattened) : flattened; } const multiDimensionalArr = [11, [22, 33], [44, [55, 66, [77, [88]], 99]]]; const flatArr = flattenMultiArray(multiDimensionalArr); // [11, 22, 33, 44, 55, 66, 77, 88, 99]
What is the easiest multi condition checking
You can use
indexOf
to compare input with multiple values instead of checking each value as one condition.// Verbose approach if (input === 'first' || input === 1 || input === 'second' || input === 2) { someFunction(); } // Shortcut if (['first', 1, 'second', 2].indexOf(input) !== -1) { someFunction(); }
How do you capture browser back button
The
window.onbeforeunload
method is used to capture browser back button events. This is helpful to warn users about losing the current data.window.onbeforeunload = function() { alert("You work will be lost"); };
How do you disable right click in the web page
The right click on the page can be disabled by returning false from the
oncontextmenu
attribute on the body element.<body oncontextmenu="return false;">
What are wrapper objects
Primitive Values like string,number and boolean don't have properties and methods but they are temporarily converted or coerced to an object(Wrapper object) when you try to perform actions on them. For example, if you apply toUpperCase() method on a primitive string value, it does not throw an error but returns uppercase of the string.
let name = "john"; console.log(name.toUpperCase()); // Behind the scenes treated as console.log(new String(name).toUpperCase());
i.e, Every primitive except null and undefined have Wrapper Objects and the list of wrapper objects are String,Number,Boolean,Symbol and BigInt.
What is AJAX
AJAX stands for Asynchronous JavaScript and XML and it is a group of related technologies(HTML, CSS, JavaScript, XMLHttpRequest API etc) used to display data asynchronously. i.e. We can send data to the server and get data from the server without reloading the web page.
What are the different ways to deal with Asynchronous Code
Below are the list of different ways to deal with Asynchronous code.
- Callbacks
- Promises
- Async/await
- Third-party libraries such as async.js,bluebird etc
How to cancel a fetch request
Until a few days back, One shortcoming of native promises is no direct way to cancel a fetch request. But the new
AbortController
from js specification allows you to use a signal to abort one or multiple fetch calls. The basic flow of cancelling a fetch request would be as below,- Create an
AbortController
instance - Get the signal property of an instance and pass the signal as a fetch option for signal
- Call the AbortController's abort property to cancel all fetches that use that signal For example, let's pass the same signal to multiple fetch calls will cancel all requests with that signal,
const controller = new AbortController(); const { signal } = controller; fetch("http://localhost:8000", { signal }).then(response => { console.log(`Request 1 is complete!`); }).catch(e => { if(e.name === "AbortError") { // We know it's been canceled! } }); fetch("http://localhost:8000", { signal }).then(response => { console.log(`Request 2 is complete!`); }).catch(e => { if(e.name === "AbortError") { // We know it's been canceled! } }); // Wait 2 seconds to abort both requests setTimeout(() => controller.abort(), 2000);
- Create an
What is web speech API
Web speech API is used to enable modern browsers recognize and synthesize speech(i.e, voice data into web apps). This API has been introduced by W3C Community in the year 2012. It has two main parts,
- SpeechRecognition (Asynchronous Speech Recognition or Speech-to-Text): It provides the ability to recognize voice context from an audio input and respond accordingly. This is accessed by the
SpeechRecognition
interface. The below example shows on how to use this API to get text from speech,
window.SpeechRecognition = window.webkitSpeechRecognition || window.SpeechRecognition; // webkitSpeechRecognition for Chrome and SpeechRecognition for FF const recognition = new window.SpeechRecognition(); recognition.onresult = (event) => { // SpeechRecognitionEvent type const speechToText = event.results[0][0].transcript; console.log(speechToText); } recognition.start();
In this API, browser is going to ask you for permission to use your microphone
- SpeechSynthesis (Text-to-Speech): It provides the ability to recognize voice context from an audio input and respond. This is accessed by the
SpeechSynthesis
interface. For example, the below code is used to get voice/speech from text,
if('speechSynthesis' in window){ var speech = new SpeechSynthesisUtterance('Hello World!'); speech.lang = 'en-US'; window.speechSynthesis.speak(speech); }
The above examples can be tested on chrome(33+) browser's developer console. Note: This API is still a working draft and only available in Chrome and Firefox browsers(ofcourse Chrome only implemented the specification) ⬆ Back to Top
- SpeechRecognition (Asynchronous Speech Recognition or Speech-to-Text): It provides the ability to recognize voice context from an audio input and respond accordingly. This is accessed by the
What is minimum timeout throttling
Both browser and NodeJS javascript environments throttles with a minimum delay that is greater than 0ms. That means even though setting a delay of 0ms will not happen instantaneously. Browsers: They have a minimum delay of 4ms. This throttle occurs when successive calls are triggered due to callback nesting(certain depth) or after a certain number of successive intervals. Note: The older browsers have a minimum delay of 10ms. Nodejs: They have a minimum delay of 1ms. This throttle happens when the delay is larger than 2147483647 or less than 1. The best example to explain this timeout throttling behavior is the order of below code snippet.
function runMeFirst() { console.log('My script is initialized'); } setTimeout(runMeFirst, 0); console.log('Script loaded');
and the output would be in
Script loaded My script is initialized
If you don't use
setTimeout
, the order of logs will be sequential.function runMeFirst() { console.log('My script is initialized'); } runMeFirst(); console.log('Script loaded');
and the output is,
My script is initialized Script loaded
How do you implement zero timeout in modern browsers
You can't use setTimeout(fn, 0) to execute the code immediately due to minimum delay of greater than 0ms. But you can use window.postMessage() to achieve this behavior.
What are tasks in event loop
A task is any javascript code/program which is scheduled to be run by the standard mechanisms such as initially starting to run a program, run an event callback, or an interval or timeout being fired. All these tasks are scheduled on a task queue. Below are the list of use cases to add tasks to the task queue,
- When a new javascript program is executed directly from console or running by the
<script>
element, the task will be added to the task queue. - When an event fires, the event callback added to task queue
- When a setTimeout or setInterval is reached, the corresponding callback added to task queue
- When a new javascript program is executed directly from console or running by the
What is microtask
Microtask is the javascript code which needs to be executed immediately after the currently executing task/microtask is completed. They are kind of blocking in nature. i.e, The main thread will be blocked until the microtask queue is empty. The main sources of microtasks are Promise.resolve, Promise.reject, MutationObservers, IntersectionObservers etc
Note: All of these microtasks are processed in the same turn of the event loop. ⬆ Back to Top
What are different event loops
What is the purpose of queueMicrotask
How do you use javascript libraries in typescript file
It is known that not all JavaScript libraries or frameworks have TypeScript declaration files. But if you still want to use libraries or frameworks in our TypeScript files without getting compilation errors, the only solution is
declare
keyword along with a variable declaration. For example, let's imagine you have a library calledcustomLibrary
that doesn’t have a TypeScript declaration and have a namespace calledcustomLibrary
in the global namespace. You can use this library in typescript code as below,declare var customLibrary;
In the runtime, typescript will provide the type to the
customLibrary
variable asany
type. The another alternative without using declare keyword is belowvar customLibrary: any;
What are the differences between promises and observables
Some of the major difference in a tabular form
| Promises | Observables | |---- | --------- | Emits only a single value at a time | Emits multiple values over a period of time(stream of values ranging from 0 to multiple) | | Eager in nature; they are going to be called immediately | Lazy in nature; they require subscription to be invoked | | Promise is always asynchronous even though it resolved immediately | Observable can be either synchronous or asynchronous| | Doesn't provide any operators | Provides operators such as map, forEach, filter, reduce, retry, and retryWhen etc | | Cannot be canceled | Canceled by using unsubscribe() method |
What is heap
Heap(Or memory heap) is the memory location where objects are stored when we define variables. i.e, This is the place where all the memory allocations and de-allocation take place. Both heap and call-stack are two containers of JS runtime. Whenever runtime comes across variables and function declarations in the code it stores them in the Heap.
What is an event table
Event Table is a data structure that stores and keeps track of all the events which will be executed asynchronously like after some time interval or after the resolution of some API requests. i.e Whenever you call a setTimeout function or invoke async operation, it is added to the Event Table. It doesn't not execute functions on it’s own. The main purpose of the event table is to keep track of events and send them to the Event Queue as shown in the below diagram.
What is a microTask queue
Microtask Queue is the new queue where all the tasks initiated by promise objects get processed before the callback queue. The microtasks queue are processed before the next rendering and painting jobs. But if these microtasks are running for a long time then it leads to visual degradation.
What is the difference between shim and polyfill
A shim is a library that brings a new API to an older environment, using only the means of that environment. It isn't necessarily restricted to a web application. For example, es5-shim.js is used to emulate ES5 features on older browsers (mainly pre IE9). Whereas polyfill is a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively. In a simple sentence, A polyfill is a shim for a browser API.
How do you detect primitive or non primitive value type
In JavaScript, primitive types include boolean, string, number, BigInt, null, Symbol and undefined. Whereas non-primitive types include the Objects. But you can easily identify them with the below function,
var myPrimitive = 30; var myNonPrimitive = {}; function isPrimitive(val) { return Object(val) !== val; } isPrimitive(myPrimitive); isPrimitive(myNonPrimitive);
If the value is a primitive data type, the Object constructor creates a new wrapper object for the value. But If the value is a non-primitive data type (an object), the Object constructor will give the same object.
What is babel
Babel is a JavaScript transpiler to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments. Some of the main features are listed below,
- Transform syntax
- Polyfill features that are missing in your target environment (using @babel/polyfill)
- Source code transformations (or codemods)
Is Node.js completely single threaded
Node is a single thread, but some of the functions included in the Node.js standard library(e.g, fs module functions) are not single threaded. i.e, Their logic runs outside of the Node.js single thread to improve the speed and performance of a program.
What are the common use cases of observables
Some of the most common use cases of observables are web sockets with push notifications, user input changes, repeating intervals, etc