| No. | Questions |
|---|
| 301 | How do you create an infinite loop | | 302 | Why do you need to avoid with statement | | 303 | What is the output of below for loops | | 304 | List down some of the features of ES6 | | 305 | What is ES6 | | 306 | Can I redeclare let and const variables | | 307 | Is const variable makes the value immutable | | 308 | What are default parameters | | 309 | What are template literals | | 310 | How do you write multi-line strings in template literals | | 311 | What are nesting templates | | 312 | What are tagged templates | | 313 | What are raw strings | | 314 | What is destructuring assignment | | 315 | What are default values in destructuring assignment | | 316 | How do you swap variables in destructuring assignment | | 317 | What are enhanced object literals | | 318 | What are dynamic imports | | 319 | What are the use cases for dynamic imports | | 320 | What are typed arrays | | 321 | What are the advantages of module loaders | | 322 | What is collation | | 323 | What is for...of statement | | 324 | What is the output of below spread operator array | | 325 | Is PostMessage secure | | 326 | What are the problems with postmessage target origin as wildcard | | 327 | How do you avoid receiving postMessages from attackers | | 328 | Can I avoid using postMessages completely | | 329 | Is postMessages synchronous | | 330 | What paradigm is Javascript | | 331 | What is the difference between internal and external javascript | | 332 | Is JavaScript faster than server side script | | 333 | How do you get the status of a checkbox | | 334 | What is the purpose of double tilde operator | | 335 | How do you convert character to ASCII code | | 336 | What is ArrayBuffer | | 337 | What is the output of below string expression | | 338 | What is the purpose of Error object | | 339 | What is the purpose of EvalError object | | 340 | What are the list of cases error thrown from non-strict mode to strict mode | | 341 | Do all objects have prototypes | | 342 | What is the difference between a parameter and an argument | | 343 | What is the purpose of some method in arrays | | 344 | How do you combine two or more arrays | | 345 | What is the difference between Shallow and Deep copy | | 346 | How do you create specific number of copies of a string | | 347 | How do you return all matching strings against a regular expression | | 348 | How do you trim a string at the beginning or ending | | 349 | What is the output of below console statement with unary operator | | 350 | Does javascript uses mixins |
-
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) {}
-
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
withit turns this into:with (a.b.c) { greeting = "welcome"; age = 32; }
But this
withstatement creates performance problems since one cannot predict whether an argument will refer to a real variable or to a property inside the with argument. -
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
setTimeoutcallback function is called after the loop has been executed. Since the variable i is declared with thevarkeyword it became a global variable and the value was equal to 4 using iteration when the timesetTimeoutfunction is invoked. Hence, the output of the first loop is4 4 4 4.Whereas in the second loop, the variable i is declared as the
letkeyword 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. -
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
-
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.
-
No, you cannot redeclare let and const variables. If you do, it throws below error
Uncaught SyntaxError: Identifier 'someVariable' has already been declaredExplanation: The variable declaration with
varkeyword 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);
-
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']
-
In ES5, 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
-
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 ES6, 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.
-
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`);
-
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'}`;
-
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
-
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]); }
-
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
-
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
-
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
-
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}
-
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());
-
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.
-
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);
-
The module loaders provides the below features,
- Dynamic loading
- State isolation
- Global namespace isolation
- Compilation hooks
- Nested virtualization
-
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", "ä" ]
-
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 }
-
[..."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.
-
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.
-
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, "*");
-
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); } });
-
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.
-
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.
-
JavaScript is a multi-paradigm language, supporting imperative/procedural programming, Object-Oriented Programming and functional programming. JavaScript supports Object-Oriented Programming with prototypical inheritance.
-
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.
-
Yes, JavaScript is faster than server side scripts. 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.
-
You can apply the
checkedproperty on the selected checkbox in the DOM. If the value istrueit 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" id="checkboxname" value="Agree" /> Agree the conditions<br />
console.log(document.getElementById(‘checkboxname’).checked); // true or false
-
The double tilde operator(~~) is known as double NOT bitwise operator. This operator is a slightly quicker substitute for Math.floor().
-
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'
-
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);
-
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.
-
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); }
-
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"
-
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
withstatement - 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.
-
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.
-
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");
-
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)
-
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
-
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 -
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'
-
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
-
The
trimmethod 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/trimLeftandtrimEnd/trimRightmethods. 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!"
-
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.
-
Mixin is a generic object-oriented programming term - is a class containing methods that can be used by other classes without a need to inherit from it. In JavaScript we can only inherit from a single object. ie. There can be only one
[[prototype]]for an object.But sometimes we require to extend more than one, to overcome this we can use Mixin which helps to copy methods to the prototype of another class.
Say for instance, we've two classes
UserandCleanRoom. Suppose we need to addCleanRoomfunctionality toUser, so that user can clean the room at demand. Here's where concept called mixins comes into picture.// mixin let cleanRoomMixin = { cleanRoom() { alert(`Hello ${this.name}, your room is clean now`); }, sayBye() { alert(`Bye ${this.name}`); }, }; // usage: class User { constructor(name) { this.name = name; } } // copy the methods Object.assign(User.prototype, cleanRoomMixin); // now User can clean the room new User("Dude").cleanRoom(); // Hello Dude, your room is clean now!