| No. | Questions |
|---|
| 141 | What is the way to find the number of parameters expected by a function | | 142 | What is a polyfill | | 143 | What are break and continue statements | | 144 | What are js labels | | 145 | What are the benefits of keeping declarations at the top | | 146 | What are the benefits of initializing variables | | 147 | What are the recommendations to create new object | | 148 | How do you define JSON arrays | | 149 | How do you generate random integers | | 150 | Can you write a random integers function to print integers with in a range | | 151 | What is tree shaking | | 152 | What is the need of tree shaking | | 153 | Is it recommended to use eval | | 154 | What is a Regular Expression | | 155 | What are the string methods available in Regular expression | | 156 | What are modifiers in regular expression | | 157 | What are regular expression patterns | | 158 | What is a RegExp object | | 159 | How do you search a string for a pattern | | 160 | What is the purpose of exec method | | 161 | How do you change the style of a HTML element | | 162 | What would be the result of 1+2+'3' | | 163 | What is a debugger statement | | 164 | What is the purpose of breakpoints in debugging | | 165 | Can I use reserved words as identifiers | | 166 | How do you detect a mobile browser | | 167 | How do you detect a mobile browser without regexp | | 168 | How do you get the image width and height using JS | | 169 | How do you make synchronous HTTP request | | 170 | How do you make asynchronous HTTP request | | 171 | How do you convert date to another timezone in javascript | | 172 | What are the properties used to get size of window | | 173 | What is a conditional operator in javascript | | 174 | Can you apply chaining on conditional operator | | 175 | What are the ways to execute javascript after page load | | 176 | What is the difference between proto and prototype | | 177 | Give an example where do you really need semicolon | | 178 | What is a freeze method | | 179 | What is the purpose of freeze method | | 180 | Why do I need to use freeze method | | 181 | How do you detect a browser language preference | | 182 | How to convert string to title case with javascript | | 183 | How do you detect javascript disabled in the page | | 184 | What are various operators supported by javascript | | 185 | What is a rest parameter | | 186 | What happens if you do not use rest parameter as a last argument | | 187 | What are the bitwise operators available in javascript | | 188 | What is a spread operator | | 189 | How do you determine whether object is frozen or not | | 190 | How do you determine two values same or not using object |
-
You can use
function.lengthsyntax to find the number of parameters expected by a function. Let's take an example ofsumfunction to calculate the sum of numbers,function sum(num1, num2, num3, num4) { return num1 + num2 + num3 + num4; } sum.length; // 4 is the number of parameters expected.
-
A polyfill is a piece of JS code used to provide modern functionality on older browsers that do not natively support it. For example, Silverlight plugin polyfill can be used to mimic the functionality of an HTML Canvas element on Microsoft Internet Explorer 7.
-
The break statement is used to "jump out" of a loop. i.e, It breaks the loop and continues executing the code after the loop.
for (i = 0; i < 10; i++) { if (i === 5) { break; } text += "Number: " + i + "<br>"; }
The continue statement is used to "jump over" one iteration in the loop. i.e, It breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
for (i = 0; i < 10; i++) { if (i === 5) { continue; } text += "Number: " + i + "<br>"; }
-
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 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"
-
It is recommended to keep all declarations at the top of each script or function. The benefits of doing this are,
- Gives cleaner code
- It provides a single place to look for local variables
- Easy to avoid unwanted global variables
- It reduces the possibility of unwanted re-declarations
-
It is recommended to initialize variables because of the below benefits,
- It gives cleaner code
- It provides a single place to initialize variables
- Avoid undefined values in the code
-
It is recommended to avoid creating new objects using
new Object(). Instead you can initialize values based on it's type to create the objects.- Assign {} instead of new Object()
- Assign "" instead of new String()
- Assign 0 instead of new Number()
- Assign false instead of new Boolean()
- Assign [] instead of new Array()
- Assign /()/ instead of new RegExp()
- Assign function (){} instead of new Function()
You can define them as an example,
var v1 = {}; var v2 = ""; var v3 = 0; var v4 = false; var v5 = []; var v6 = /()/; var v7 = function () {};
-
JSON arrays are written inside square brackets and arrays contain javascript objects. For example, the JSON array of users would be as below,
"users":[ {"firstName":"John", "lastName":"Abrahm"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Shane", "lastName":"Warn"} ]
-
You can use Math.random() with Math.floor() to return random integers. For example, if you want generate random integers between 1 to 10, the multiplication factor should be 10,
Math.floor(Math.random() * 10) + 1; // returns a random integer from 1 to 10 Math.floor(Math.random() * 100) + 1; // returns a random integer from 1 to 100
Note: Math.random() returns a random number between 0 (inclusive), and 1 (exclusive)
-
Yes, you can create a proper random function to return a random number between min and max (both included)
function randomInteger(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } randomInteger(1, 100); // returns a random integer from 1 to 100 randomInteger(1, 1000); // returns a random integer from 1 to 1000
-
Tree shaking is a form of dead code elimination. It means that unused modules will not be included in the bundle during the build process and for that it relies on the static structure of ES2015 module syntax,( i.e. import and export). Initially this has been popularized by the ES2015 module bundler
rollup. -
Tree Shaking can significantly reduce the code size in any application. i.e, The less code we send over the wire the more performant the application will be. For example, if we just want to create a “Hello World” Application using SPA frameworks then it will take around a few MBs, but by tree shaking it can bring down the size to just a few hundred KBs. Tree shaking is implemented in Rollup and Webpack bundlers.
-
No, it allows arbitrary code to be run which causes a security problem. As we know that the eval() function is used to run text as code. In most of the cases, it should not be necessary to use it.
-
A regular expression is a sequence of characters that forms a search pattern. You can use this search pattern for searching data in a text. These can be used to perform all types of text search and text replace operations. Let's see the syntax format now,
/pattern/modifiers;
For example, the regular expression or search pattern with case-insensitive username would be,
/John/i;
-
Regular Expressions has two string methods: search() and replace(). The search() method uses an expression to search for a match, and returns the position of the match.
var msg = "Hello John"; var n = msg.search(/John/i); // 6
The replace() method is used to return a modified string where the pattern is replaced.
var msg = "Hello John"; var n = msg.replace(/John/i, "Buttler"); // Hello Buttler
-
Modifiers can be used to perform case-insensitive and global searches. Let's list down some of the modifiers,
Modifier Description i Perform case-insensitive matching g Perform a global match rather than stops at first match m Perform multiline matching Let's take an example of global modifier,
var text = "Learn JS one by one"; var pattern = /one/g; var result = text.match(pattern); // one,one
-
Regular Expressions provide a group of patterns in order to match characters. Basically they are categorized into 3 types,
- Brackets: These are used to find a range of characters.
For example, below are some use cases,
- [abc]: Used to find any of the characters between the brackets(a,b,c)
- [0-9]: Used to find any of the digits between the brackets
- (a|b): Used to find any of the alternatives separated with |
- Metacharacters: These are characters with a special meaning
For example, below are some use cases,
- \d: Used to find a digit
- \s: Used to find a whitespace character
- \b: Used to find a match at the beginning or ending of a word
- Quantifiers: These are useful to define quantities
For example, below are some use cases,
- n+: Used to find matches for any string that contains at least one n
- n*: Used to find matches for any string that contains zero or more occurrences of n
- n?: Used to find matches for any string that contains zero or one occurrences of n
- Brackets: These are used to find a range of characters.
For example, below are some use cases,
-
RegExp object is a regular expression object with predefined properties and methods. Let's see the simple usage of RegExp object,
var regexp = new RegExp("\\w+"); console.log(regexp); // expected output: /\w+/
-
You can use the test() method of regular expression in order to search a string for a pattern, and return true or false depending on the result.
var pattern = /you/; console.log(pattern.test("How are you?")); //true
-
The purpose of exec method is similar to test method but it executes a search for a match in a specified string and returns a result array, or null instead of returning true/false.
var pattern = /you/; console.log(pattern.exec("How are you?")); //["you", index: 8, input: "How are you?", groups: undefined]
-
You can change inline style or classname of a HTML element using javascript
- Using style property: You can modify inline style using style property
document.getElementById("title").style.fontSize = "30px";
- Using ClassName property: It is easy to modify element class using className property
document.getElementById("title").className = "custom-title";
-
The output is going to be
33. Since1and2are numeric values, the result of the first two digits is going to be a numeric value3. The next digit is a string type value because of that the addition of numeric value3and string type value3is just going to be a concatenation value33. -
The debugger statement invokes any available debugging functionality, such as setting a breakpoint. If no debugging functionality is available, this statement has no effect. For example, in the below function a debugger statement has been inserted. So execution is paused at the debugger statement just like a breakpoint in the script source.
function getProfile() { // code goes here debugger; // code goes here }
-
You can set breakpoints in the javascript code once the debugger statement is executed and the debugger window pops up. At each breakpoint, javascript will stop executing, and let you examine the JavaScript values. After examining values, you can resume the execution of code using the play button.
-
No, you cannot use the reserved words as variables, labels, object or function names. Let's see one simple example,
var else = "hello"; // Uncaught SyntaxError: Unexpected token else
-
You can use regex which returns a true or false value depending on whether or not the user is browsing with a mobile.
window.mobilecheck = function () { var mobileCheck = false; (function (a) { if ( /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test( a ) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test( a.substr(0, 4) ) ) mobileCheck = true; })(navigator.userAgent || navigator.vendor || window.opera); return mobileCheck; };
-
You can detect mobile browsers by simply running through a list of devices and checking if the useragent matches anything. This is an alternative solution for RegExp usage,
function detectmob() { if ( navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i) ) { return true; } else { return false; } }
-
You can programmatically get the image and check the dimensions(width and height) using Javascript.
var img = new Image(); img.onload = function () { console.log(this.width + "x" + this.height); }; img.src = "http://www.google.com/intl/en_ALL/images/logo.gif";
-
Browsers provide an XMLHttpRequest object which can be used to make synchronous HTTP requests from JavaScript
function httpGet(theUrl) { var xmlHttpReq = new XMLHttpRequest(); xmlHttpReq.open("GET", theUrl, false); // false for synchronous request xmlHttpReq.send(null); return xmlHttpReq.responseText; }
-
Browsers provide an XMLHttpRequest object which can be used to make asynchronous HTTP requests from JavaScript by passing the 3rd parameter as true.
function httpGetAsync(theUrl, callback) { var xmlHttpReq = new XMLHttpRequest(); xmlHttpReq.onreadystatechange = function () { if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) callback(xmlHttpReq.responseText); }; xmlHttp.open("GET", theUrl, true); // true for asynchronous xmlHttp.send(null); }
-
You can use the toLocaleString() method to convert dates in one timezone to another. For example, let's convert current date to British English timezone as below,
console.log(event.toLocaleString("en-GB", { timeZone: "UTC" })); //29/06/2019, 09:56:00
-
You can use innerWidth, innerHeight, clientWidth, clientHeight properties of windows, document element and document body objects to find the size of a window. Let's use them combination of these properties to calculate the size of a window or document,
var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
-
The conditional (ternary) operator is the only JavaScript operator that takes three operands which acts as a shortcut for if statements.
var isAuthenticated = false; console.log( isAuthenticated ? "Hello, welcome" : "Sorry, you are not authenticated" ); //Sorry, you are not authenticated
-
Yes, you can apply chaining on conditional operators similar to if … else if … else if … else chain. The syntax is going to be as below,
function traceValue(someParam) { return condition1 ? value1 : condition2 ? value2 : condition3 ? value3 : value4; } // The above conditional operator is equivalent to: function traceValue(someParam) { if (condition1) { return value1; } else if (condition2) { return value2; } else if (condition3) { return value3; } else { return value4; } }
-
You can execute javascript after page load in many different ways,
- window.onload:
window.onload = function ...
- document.onload:
document.onload = function ...
- body onload:
<body onload="script();">
-
The
__proto__object is the actual object that is used in the lookup chain to resolve methods, etc. Whereasprototypeis the object that is used to build__proto__when you create an object with new.new Employee().__proto__ === Employee.prototype; new Employee().prototype === undefined;
There are few more differences,
feature Prototype proto Access All the function constructors have prototype properties. All the objects have __proto__ property Purpose Used to reduce memory wastage with a single copy of function Used in lookup chain to resolve methods, constructors etc. ECMAScript Introduced in ES6 Introduced in ES5 Usage Frequently used Rarely used -
It is recommended to use semicolons after every statement in JavaScript. For example, in the below case it throws an error ".. is not a function" at runtime due to missing semicolon.
// define a function var fn = (function () { //... })( // semicolon missing at this line // then execute some code inside a closure function () { //... } )();
and it will be interpreted as
var fn = (function () { //... })(function () { //... })();
In this case, we are passing the second function as an argument to the first function and then trying to call the result of the first function call as a function. Hence, the second function will fail with a "... is not a function" error at runtime.
-
The freeze() method is used to freeze an object. Freezing an object does not allow adding new properties to an object,prevents from removing and prevents changing the enumerability, configurability, or writability of existing properties. i.e, It returns the passed object and does not create a frozen copy.
const obj = { prop: 100, }; Object.freeze(obj); obj.prop = 200; // Throws an error in strict mode console.log(obj.prop); //100
Remember freezing is only applied to the top-level properties in objects but not for nested objects. For example, let's try to freeze user object which has employment details as nested object and observe that details have been changed.
const user = { name: 'John', employment: { department: 'IT' } }; Object.freeze(user); user.employment.department = 'HR';
Note: It causes a TypeError if the argument passed is not an object.
-
Below are the main benefits of using freeze method,
- It is used for freezing objects and arrays.
- It is used to make an object immutable.
-
In the Object-oriented paradigm, an existing API contains certain elements that are not intended to be extended, modified, or re-used outside of their current context. Hence it works as the
finalkeyword which is used in various languages. -
You can use navigator object to detect a browser language preference as below,
var language = (navigator.languages && navigator.languages[0]) || // Chrome / Firefox navigator.language || // All browsers navigator.userLanguage; // IE <= 10 console.log(language);
-
Title case means that the first letter of each word is capitalized. You can convert a string to title case using the below function,
function toTitleCase(str) { return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substring(1).toLowerCase(); }); } toTitleCase("good morning john"); // Good Morning John
-
You can use the
<noscript>tag to detect javascript disabled or not. The code block inside<noscript>gets executed when JavaScript is disabled, and is typically used to display alternative content when the page generated in JavaScript.<script type="javascript"> // JS related code goes here </script> <noscript> <a href="next_page.html?noJS=true">JavaScript is disabled in the page. Please click Next Page</a> </noscript>
-
An operator is capable of manipulating(mathematical and logical computations) a certain value or operand. There are various operators supported by JavaScript as below,
- Arithmetic Operators: Includes + (Addition),– (Subtraction), * (Multiplication), / (Division), % (Modulus), + + (Increment) and – – (Decrement)
- Comparison Operators: Includes = =(Equal),!= (Not Equal), ===(Equal with type), > (Greater than),> = (Greater than or Equal to),< (Less than),<= (Less than or Equal to)
- Logical Operators: Includes &&(Logical AND),||(Logical OR),!(Logical NOT)
- Assignment Operators: Includes = (Assignment Operator), += (Add and Assignment Operator), – = (Subtract and Assignment Operator), *= (Multiply and Assignment), /= (Divide and Assignment), %= (Modules and Assignment)
- Ternary Operators: It includes conditional(: ?) Operator
- typeof Operator: It uses to find type of variable. The syntax looks like
typeof variable
-
Rest parameter is an improved way to handle function parameters which allows us to represent an indefinite number of arguments as an array. The syntax would be as below,
function f(a, b, ...theArgs) { // ... }
For example, let's take a sum example to calculate on dynamic number of parameters,
function total(…args){ let sum = 0; for(let i of args){ sum+=i; } return sum; } console.log(fun(1,2)); //3 console.log(fun(1,2,3)); //6 console.log(fun(1,2,3,4)); //13 console.log(fun(1,2,3,4,5)); //15
Note: Rest parameter is added in ES2015 or ES6
-
The rest parameter should be the last argument, as its job is to collect all the remaining arguments into an array. For example, if you define a function like below it doesn’t make any sense and will throw an error.
function someFunc(a,…b,c){ //You code goes here return; }
-
Below are the list of bitwise logical operators used in JavaScript
- Bitwise AND ( & )
- Bitwise OR ( | )
- Bitwise XOR ( ^ )
- Bitwise NOT ( ~ )
- Left Shift ( << )
- Sign Propagating Right Shift ( >> )
- Zero fill Right Shift ( >>> )
-
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
-
Object.isFrozen() method is used to determine if an object is frozen or not.An object is frozen if all of the below conditions hold true,
- If it is not extensible.
- If all of its properties are non-configurable.
- If all its data properties are non-writable. The usage is going to be as follows,
const object = { property: "Welcome JS world", }; Object.freeze(object); console.log(Object.isFrozen(object));
-
The Object.is() method determines whether two values are the same value. For example, the usage with different types of values would be,
Object.is("hello", "hello"); // true Object.is(window, window); // true Object.is([], []); // false
Two values are the same if one of the following holds:
- both undefined
- both null
- both true or both false
- both strings of the same length with the same characters in the same order
- both the same object (means both object have same reference)
- both numbers and both +0 both -0 both NaN both non-zero and both not NaN and both have the same value.