InterviewSolution
This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
| 51. |
const innerFunc = function(_soap) { console.log(`Cleaning ${this. room} with ${_soap}`) } innerFunc(soap); } let harrysRoom = { room: "Harry's room" } cleanRoom.call(harrysRoom, "Harpic"); //Output - Cleaning undefined with Harpic |
|
Answer» 10
2 When INSIDE the method, fn() is called the “this” of the function fn is at window level. So, “this.length” will produce 10. |
|
| 52. |
What are the different way to access “this” inside an inner function for below code? |
|
Answer» The OUTPUT logged will be: undefined Johnny DeepThe first console.log prints undefined because heroIdentity()is been INVOKED in the GLOBAL context (i.e., the WINDOW object) where the _name property doesn’t exists. The way to fix it is by binding, it to hero object by USING bind. var heroIdentity = hero.getIdentity.bind(hero); |
|
| 53. |
Explain ”this” with call, apply and bind in JavaScript? |
|
Answer» One of the main use of “call” is to change an array like object to array. There is an array like object arguments available for every normal function(not arrow function). It is very useful in functions, as we can get the number of arguments passed to it. Let’s convert the arguments into array, because arrays have a lots of functionality. Consider the below example, where we console log arguments. If we expand it in dev console, it shows it’s not and array and it’s __proto__ doesn’t have array functionalities. let sumNumbers = function() { console.log(arguments); } sumNumbers(1, 2, 3, 4);Now to convert it we will take an empty array and use it’s slice method. Then call it through call, by passing the argument Object. Now it is CONVERTED into array and the __proto__ have all array functionalities. So, we are using the array reduce method available to do the SUM of the number of arguments passed to it. let sumNumbers = function() { const argsToArray = [].slice.call(arguments); console.log(argsToArray); return argsToArray.reduce((acc, curr) => acc + curr); } console.log(sumNumbers(1, 2, 3, 4)); //10 console.log(sumNumbers(1, 2, 3)); //6The second application of call is in inheritance , using constructor functions. Consider the below example. Here in the Cat function, we CALLED its parent Mammal using call method with “this” of Cat. let Mammal = function(legs) { this.legs = legs; } let Cat = function(legs, isDomesticated) { Mammal.call(this, legs); this.isDomesticated = isDomesticated; } let tiger = new Cat(4, false); let homeCat = new Cat(4, true); console.log(tiger); // { legs: 4, isDomesticated: false } console.log(homeCat); // { legs: 4, isDomesticated: true }One of the practical use of apply is to pass an array to a function, which expects arguments only. Consider the case of Math.max, which gives the maximum of the arguments passed. So, now to pass an array like in below code, we convert it through apply. Note the first argument is null because we are not passing any Object for “this” binding. let arr = [20, 6, 29, 12]; console.log(Math.max(20, 6, 29, 12)); // 29 console.log(Math.max.apply(null, arr)); // 29One of the practical use of bind is in React. In React whenever we call a function from render(), we have to bind it’s “this” in constructor. Consider the below code. We bind the “this” of the event handler to the component instance in the constructor, we can pass it as a callback without worrying about it losing its context. class Foo extends React.Component{ constructor( props ){ super( props ); this.state = { text: '' }this.handleChange = this.handleChange.bind(this); } handleChange(event){ this.setState({ text: event.target.value }) } render(){ return ( <input type="text" value={this.state.text} onChange={this.handleChange} /> ); } } ReactDOM.render( <Foo />, document.getElementById("app") ); |
|
| 54. |
Is JavaScript synchronous or asynchronous and what is event loop ? |
|
Answer» There are FOUR solutions to access “this” inside the innerFunc(). Solution 1 Solution 2 Solution 3 Solution 4 |
|
| 55. |
What is prototypal inheritance ? |
|
Answer» EVERY function in JavaScript have call, APPLY and bind methods. These methods can be used to set the CUSTOM value of “this” to the execution context of the function. call Now, in addNumbers we have this.num. But how do we pass the value obj.num to it. We need to pass it a context, which means the value of “this”. We will do this my call method by passing a first argument as obj, so the “this” is the obj now. let obj = {num: 3}; let addNumbers = function(a, b, c){ return this.num + a + b + c; }; console.log(addNumbers.call(obj, 1, 4, 6)); //14apply bind |
|
| 56. |
substr() vs substring() in JavaScript? |
|
Answer» JavaScript is a synchronous, blocking, single-threaded language. That just means that only one operation can be in progress at a time. Many PEOPLE think JavaScript is asynchronous because we can do async tasks like SETTIMEOUT, CALLBACKS, promises in it. But the asynchronous behaviour of JavaScript(setTimeout, callbacks, promises) is not a part of JavaScript itself and built on top of JavaScript language in browser and accessed through browser APIs. The browser have a Call Stack, Browser API and Message Queue and the ORDER of their processing is called event loop. We will see the working of the classic interview question to understand how the event loop and with it the asynchronous behaviour of JavaScript works. function main() { console.log('A'); setTimeout(function(){ console.log('B'); },0); console.log('C'); } main();//Output //A //C //BThe output will be A C B , even after the setTimeout() was set to display “b” after 0 ms. This happens because of the internal working of the browser. Let’s look into the step of execution. The main() is pushed into Call Stack, which then console logs A. Then it is popped out and the setTimeout is pushed into Call Stack. Now the setTimeout() uses Browser API, so it is pushed there and the console log C is pushed into Call Stack.
This is how event loop works and the asynchronous, non-blocking part of JavaScript comes from. |
|
| 57. |
What is a fat arrow function in JavaScript? |
|
Answer» Prototypal inheritance is to ADD NEW capabilities to a constructor function using Prototype. console.log(maryCar.getModel()); //nissan Now, the problem is that every time we create a new instance we get a new COPY of getModel(). Suppose we have 100 instances, then we will have 100 copies. Below console log shows the same thing. We should somehow move the logic for getModel() outside our Constructor function and that is where the concept of Prototype helps. In JavaScript as you know everything is an Object. Whenever a function is created there are two object ONE is the function object another is the prototype object. Now to access the Prototype object we have a property on the function object also known as “prototype”. Every instance created from the function have access to the Prototype object. Now, let’s move our getModel() outside our Constructor function using prototype. let Car = function(model) { this.model = model; } Car.prototype.getModel = function() { return this.model; } let harryCar = new Car('toyota'); console.log(harryCar.getModel()); //toyota let maryCar = new Car('nissan'); console.log(maryCar.getModel()); //nissanWe get the same result and this is known as Prototypal Inheritance. Also, each new instance don’t have its own getModel(), which we can see in below console log. |
|
| 58. |
What is the "double tilde" (~~) operator in JavaScript? |
|
Answer» The substr() and substring() methods are simpler, yet they have some differences. The 2nd argument of the substring() method is the index to halt the search, whereas the 2nd parameter of substr() is the maximum length. Note: We will be taking the same string and the same parameter value for both the functions to make it easier to understand substr() method The substr() method returns the characters in a string BEGINNING at the specified location. It goes through the number of characters which is specified by the user. The parameters of substr(start, len):
Let us see an example. We have the following string: var myStr = "Knowledge Hut!";Now, we will use substr() as discusses above with the parameters to GET 5 elements beginning from 3rd index: myStr.substr(3,5)The example: <html> <head> <TITLE>JavaScript substr()</title> </head> <body> <script> var myStr = "Knowledge Hut!"; document.write("(3,5): " + myStr.substr(3,5)); </script> </body> </html>The output from 3rd index. 5 is the length of elements after beginning with 3rd index: (3,5): wledgsubstring() method The substring() method returns subset of a string. The parameters of substring(i1, i2):
Let us see an example. We have the following string: var myStr = "Knowledge Hut!";Now, we will use substring() as discussed above with the parameters to get substring from 3 to 5, since we set the parameter as 3 and 5: myStr.substring(3,5)The example: <html> <head> <title>JavaScript substr()</title> </head> <body> <script> var myStr = "Knowledge Hut!"; document.write("(3,5): " + myStr.substring(3,5)); </script> </body> </html>The output from substring 3 to 5: (3,5): wl |
|
| 59. |
How to unset a JavaScript variable? |
|
Answer» Generally, in JavaScript we create functions USING the function KEYWORD: var points = [98, 45, 78, 65, 99]; var DEMO = points.map(function(val) { return val + val; })Using the Fat arrow function REDUCES line of code and even avoids you to write the keyword “function” again and again. The syntax of fat arrow function includes =>, wherein it shows fat arrow: ARG => expFor multiple arguments: (arg1 [, arg2]) => expLet’s see what you need to do with fat arrow function while implementing the code snippet we saw above: var points = [98, 45, 78, 65, 99]; var demo = points.map((val) => val+val); |
|
| 60. |
What is NaN in JavaScript? |
|
Answer» The double NOT Bitwise operator is a “double tilde” (~~) operator in JavaScript. Let’s SAY we have the following variable: var val1 = 3.7; var val2;Now, use the double tilde operator and assign it to another variable: val2 = ~~val1;The example to work with double tilde operator: <!DOCTYPE html> <html> <body> <script> var val1 = 3.7; var val2; val2 = ~~val1; document.write(val2); </script> </body> </html>The output: 3 You can ACHIEVE the same RESULT from Math.floor() in JavaScript, but double tilde is considered faster: <!DOCTYPE html> <html> <body> <script> var val1 = 3.7; document.write(Math.floor(val1)); </script> </body> </html>The same output is VISIBLE: 3 |
|
| 61. |
Why do we use the !! (not not) operator in JavaScript? |
|
Answer» The “undefined” is used to unset a variable in JavaScript. Declare and INITIALIZE a variable: ]var a = 50;Now reassign the variable with undefined SINCE we wish to unset it: a = undefined;The following is an example: <!DOCTYPE html> <html> <body> <script> var a = 50; a = undefined; document.write(a); </script> </body> </html>The output displays undefined: UndefinedIf you are implicitly declaring the variable without var keyword, then USE the delete to unset a variable: <!DOCTYPE html> <html> <body> <script> a = 10; delete a; </script> </body> </html> |
|
| 62. |
Can we add one or more element to the front of an array in JavaScript? |
|
Answer» NaN SUGGESTS that the entered VALUE is not a legal number. It is a JavaScript property, which can also be considered as a "Not-a-Number" value. To determine the entered value is a number or not, you can use the Number.isNaN() method. If the result is “True”, then it would that the given value is not a number, whereas “FALSE” would mean the value is a legal Number. Let US see an example: <!DOCTYPE html> <html> <body> <script> var a = "Grill"; document.write(isNaN(a)); </script> </body> </html>The OUTPUT displays True since the above value is not a legal number: TrueLet us see another example: <!DOCTYPE html> <html> <body> <script> var a = 10; document.write(isNaN(a)); </script> </body> </html>The output since the above value is a legal number: FalseLet us see another example: <!DOCTYPE html> <html> <body> <script> var a = 0/0; document.write(isNaN(a)); </script> </body> </html>The output generates True since 0/0 is not a legal number: True |
|
| 63. |
How to remove the last element from an array in JavaScript? |
|
Answer» The !! operator is the not operator twice. It is useful in working through the truth value and returns a Boolean value. <!DOCTYPE HTML> <html> <BODY> <script> var val1 = "This is an example"; var val2 = !!val1; document.write(val2); </script> </body> </html>The OUTPUT: TrueLet us see another example for integer and apply double not to it: <!DOCTYPE html> <html> <body> <script> var val1 = 10; var val2 = !!val1; document.write(val2); </script> </body> </html>The output: True |
|
| 64. |
Display a floating-point pseudo-random number between 0 and 1 in JavaScript |
|
Answer» Yes, we can add one or more element to the front of an array using the unshift() METHOD.<BR> Here, e1, e2, e3, … , en are the elements to be added in the front of the array. We added the FOLLOWING elements to the array: var arr = [20, 11, 44, 39, 88, 48, 89, 47 ];Let’s say we need to add a new element in the front of the above array. For that set the element value as a parameter in the unshift method as shown below: var len = arr.unshift("5");The following is an example wherein we are adding an element in the beginning of an array: <!DOCTYPE html> <html> <body> <script> var arr = [20, 11, 44, 39, 88, 48, 89, 47 ]; document.write("Array = "+arr); // adding element 5 in the front var len = arr.unshift("5"); // displaying the new array document.write("<br>New array = " + arr ); document.write("<br /> Length of the array = " + len ); </script> </body> </html>The output: Array = 20,11,44,39,88,48,89,47 New array = 5,20,11,44,39,88,48,89,47 Length of the array = 9 |
|
| 65. |
Convert a Date object to String in JavaScript? |
|
Answer» To remove the last element from an array in JavaScript, use the pop() method.<BR> Let’s say we have the following array: var arr = [20, 11, 44, 39, 88, 48, 89, 47 ];To remove an element, use the pop() method: var element = arr.pop();Let us see an example wherein we are removing 5 elements: The OUTPUT: Array = 20,11,44,39,88,48,89,47 Removing 5 elements... Popped Element = 47 Popped Element = 89 Popped Element = 48 Popped Element = 88 Popped Element = 39 |
|
| 66. |
Parse a string representation of date and time |
|
Answer» The Math.random() method displays a floating-point pseudo-random number between 0 and 1. The output displays any random number between 0 and 1: Random number = 0.8085646074894297When we will run the above program again, a new random value between 0 and 1 will get generated as shown below: Random number = 0.1117848013962992 |
|
| 67. |
Get today’s date in JavaScript |
|
Answer» To convert a date object to string in JavaScript, use the toLocaleString() method. Create a Date object: var date = new Date();Now convert the above date object to string: date.toLocaleString();The example demonstrates how to convert Date object to string: <!DOCTYPE html> <html> <body> <script> var date = new Date(); var RES = date.toLocaleString(); document.write(res); </script> </body> </html>The output: 12/14/2018, 8:25:52 PM |
|
| 68. |
Get the unicode of the character at a specified index in a string with JavaScript |
|
Answer» The Date.parse() method is USED in JavaScript to parse a string representation of date and time. Let us first see the syntax: Date.parse(STR)Here, str is the date string. The method parses the date and returns the number of MILLISECONDS SINCE midnight of January 1, 1970. Let us see an example now: <!DOCTYPE html> <html> <body> <script> var res = Date.parse( "Dec 14, 2018 16:45:00" ); document.write( "Number of milliseconds between the date MENTIONED above and 1970 = " + res ); </script> </body> </html>The output: Number of milliseconds between the date mentioned above and 1970 = 1544786100000 |
|
| 69. |
How to create a Boolean object using JavaScript? |
|
Answer» The Date() method is to be USED in JavaScript to GET today’s date and time. Date() Let us see the example to display the current date and time: <!DOCTYPE HTML> <html> <body> <script> var date = Date(); document.write("Date and Time = " + date ); </script> </body> </html>The output displays today’s date and time: Date and Time = Fri Dec 14 2018 20:16:22 GMT+0530 (India STANDARD Time)Let’s say you need to only fetch the time portion of the date. For that, use the toTimeString() method: <!DOCTYPE html> <html> <body> <script> var date = new Date(2018, 12, 14, 10, 11, 30); document.write( date.toTimeString() ); </script> </body> </html>The output displays only the current time: 10:11:30 GMT+0530 (India Standard Time) |
|
| 70. |
Boolean Typed Array exist in JavaScript? |
|
Answer» To display the unicode of the character at a specified index in a string with JavaScript, use the charCodeAt() method. Let us now see the syntax: string.charCodeAt(index)Here, “index” is the index of the character we are willing to return. The method returns the Unicode of the character. However, "NaN" is returned if no character is found at the index we added as the parameter. The following is an example: <!DOCTYPE HTML> <html> <body> <script> var myStr = "Chatting!"; var res = myStr.charCodeAt(0); document.write( "Unicode = " + res.toString() ); </script> </body> </html>The output displays the returned Unicode of the 1st character, since we added parameter as 0: Unicode = 67The following is another example wherein we will find out the Unicode for character at index 2: <!DOCTYPE html> <html> <body> <script> var myStr = "HIT Wicket!!"; var res = myStr.charCodeAt(2); document.write( "Unicode = " + res.toString() ); </script> </body> </html>The output displays the returned Unicode of the 3rd character, since we added parameter index as 2: Unicode = 116Let us see a CONDITION in which we are finding the character at a position where there is no character: <!DOCTYPE html> <html> <body> <script> var myStr = "abc"; // 5th character does not EXIST var res = myStr.charCodeAt(5); // NaN is returned document.write( "Unicode = " + res.toString() ); </script> </body> </html>Above, “NaN” is returned since there is no character at position 5th: Unicode = NaN |
|
| 71. |
What is Window alert() in JavaScript |
|
Answer» “True” and “False” are the two values in a Boolean object. Let us now see how to create a Boolean object: var val = NEW Boolean(false);Let us now see an example wherein we will create a Boolean object and return the value. We are using Boolean VALUEOF() method: <!DOCTYPE html> <html> <body> <SCRIPT> var val = new Boolean(true); document.write( "Value = " + val.valueOf() ); </script> </body> </html>The output: Value = trueHere is another example wherein we are returning the string representation of a Boolean value: <!DOCTYPE html> <html> <body> <script> var val = new Boolean(false); document.write( "String = " + val.toString() ); </script> </body> </html>The output: String = false |
|
| 72. |
Why do we use document.write() in JavaScript? |
|
Answer» Unfortunately, Boolean Typed ARRAY do not exist in JavaScript. The following typed arrays exist in JavaScript: Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, etc. Let us see an EXAMPLE of Int8Array typed array. The Int8Array typed array REPRESENTS an array of twos-complement 8-bit signed integers. The following is the syntax: new Int8Array(); new Int8Array(length); new Int8Array(typedArray);The following is an example: <!DOCTYPE html> <html> <body> <SCRIPT> var val = new Int8Array(5); val[3] = 9; // length of array document.write("Array Length = "+val.length); // displaying array elements document.write("<br>Array elements..."); document.write("<br>"+val[0]); document.write("<br>"+val[1]); document.write("<br>"+val[2]); document.write("<br>"+val[3]); </script> </body> </html>The output: Array Length = 5 Array elements... 0 0 0 9 |
|
| 73. |
How to get the length of a string in JavaScript? |
|
Answer» To display an alert box in JavaScript, use the alert() method. The alert box would have an OK button. Here, msg is the text which is to be displayed in the alert box. SHOWN below under alert(): function show() { alert("This is an alert box!"); }The following is an example: <!DOCTYPE html> <html> <BODY> <p>Below button displays an alert...</p> <button onclick="show()">Display</button> <script> function show() { alert("This is an alert box!"); } </script> </body> </html>The output: On clicking the above button, the following alert GENERATES and the message we added as parameter is visible: You MAY be wondering how we can add a multi-line message in an alert box in JavaScript. For that, just use \n as shown below: <!DOCTYPE html> <html> <body> <p>Below button displays an alert with multi-line content...</p> <button onclick="show()">Display</button> <script> function show() { alert("This is first line!\nThis is next line!"); } </script> </body> </html>The output: On clicking the above button, the following alert generates and the multi-line message we added as parameter is visible: |
|
| 74. |
How to create a Number object using JavaScript? |
|
Answer» <P>The document.write() method writes JavaScript code to a document. It also writes HTML EXPRESSIONS. The syntax: document.write(expression1, expression2, expression3, ...)Here, expression1, expression2, expression3 are the expressions to be written to the OUTPUT stream. Let us now see an example to write HTML elements with document.write(): <!DOCTYPE html> <html> <body> <script> document.write("<p>John CENA</p>"); </script> </body> </html>The output: John CenaLet us see another example to write text to stream with document.write(): <!DOCTYPE html> <html> <body> <script> document.open(); document.write("<p>TRAVIS Head</p>"); document.close(); </script> </body> </html>The output: Travis Head |
|
| 75. |
let vs var in JavaScript? |
|
Answer» The length property is used in JAVASCRIPT to get the length of a STRING: The SYNTAX: string.lengthLet’s say the following is our string: VAR myStr = "This is an example!";Now get the length of the string in a new variable: var res = myStr.length;The following is an example that displays the string length: <html> <head> <title>JavaScript String Length</title> </head> <body> <script> var myStr = "This is an example!"; var res = myStr.length; document.write("Length = " + res); </script> </body> </html>The output: Length = 19Let us now see what we will get when we will TRY to find the length of an empty string: <html> <head> <title>JavaScript String Length</title> </head> <body> <script> var myStr = ""; var res = myStr.length; document.write("Length = " + res); </script> </body> </html>The output displays 0 since it is an empty string: Length = 0 |
|
| 76. |
Convert JavaScript array into comma-separated list? |
|
Answer» The Number object is for integers, floating-point numbers, etc. Let us now see how to CREATE a Number object: var VAL = new Number(10);Let us now create an object with floating-point value: var val = new Number(25.90);An example here is to GET the value of the specified Number object. We are creating a Number object: <html> <head> <title>JAVASCRIPT Number Object</title> </head> <BODY> <script> var val = new Number(25.90); document.write("Value = " + val.valueOf()); </script> </body> </html>The output: Value = 25.9Let us now create another Number object and represent it in String: <html> <head> <title>JavaScript Number Object</title> </head> <body> <script> var val = new Number(40); document.write("String: " + val.toString()); </script> </body> </html>The output: String: 40 |
|
| 77. |
How to shuffle an array in JavaScript? |
|
Answer» The var and let are used to declare a variable in JavaScript. The new way to define a variable in JavaScript is using the let statement. The ECMAScript 2015 introduced it. As you know that variables can ALSO be declared with var, but the usage of var are scoped to the function block level. Declare variables that are limited in scope to the block, statement, or expression using the let. Redeclaring a variable inside a block will not redeclare the variable outside the block. Example of let Let us see an example of let. The variable declared in the LOOP does not redeclare the variable outside the loop: <!DOCTYPE html> <html> <body> <h3>JavaScript let</h3> <p id="myid"></p> <script> let i = 2; for (let i = 0; i < 10; i++) { document.write(i); } document.getElementById("myid").innerHTML = i; </script> </body> </html>The output displays the value if i variable as 2: Example of var Let us see the same example and place var in place of let to work with variables: <!DOCTYPE html> <html> <body> <h3>JavaScript var</h3> <p id="myid"></p> <script> var i = 2; for (var i = 0; i < 10; i++) { document.write(i); } document.getElementById("myid").innerHTML = i; </script> </body> </html>The output displays the value of i variable as 10: |
|
| 78. |
Why do we use pageYOffset property in JavaScript? |
|
Answer» JavaScript provides a join() method to join the elements of an array. While joining, you can set the separator as WELL: array.join(separator)Here, separator is the resultant array would be specified by this separator. Comma is the default separator. The return value is the strings as array elements separated by the separator. Let us see an EXAMPLE wherein we have the following array: var products = ["Shoes", "Cap", "TShirt", "Shirt", "Trousers"];The example to convert array into comma-separated list: <!DOCTYPE HTML> <html> <body> <script> var products = ["Shoes", "Cap", "TShirt", "Shirt", "Trousers"]; document.write(products.join()); </script> </body> </html>The following is the OUTPUT: Shoes,Cap,TShirt,Shirt,Trousers |
|
| 79. |
What does “javascript:void(0)” mean? |
|
Answer» Let’s say the following is your array: VAR a = [99, 150, 299, 340, 390, 450, 590, 600];Now, get the length of the array: var len = a.length;Loop until the length of the array is more than 0. Use Math.random() to RANDOMIZE the elements. Decrement the value of len (length) after every iteration for each element: while (len > 0) { index = Math.floor(Math.random() * len); len--; t = a[len]; a[len] = a[index]; a[index] = t; }The following is an example that shuffles an array: <html> <body> <script> function SHOW(a) { var len = a.length; var t, index; while (len > 0) { index = Math.floor(Math.random() * len); len--; t = a[len]; a[len] = a[index]; a[index] = t; } return a; } var a = [99, 150, 299, 340, 390, 450, 590, 600]; document.write("Array = "+a); document.write("<br>SHUFFLING the array = "+show(a)); </script> </body> </html>The output: Array = 99,150,299,340,390,450,590,600 Shuffling the array = 390,340,150,590,99,450,299,600 |
|
| 80. |
Inline functions vs Anonymous functions in JavaScript |
|
Answer» Get the pixels of the CURRENT document SCROLLED to from the upper left corner of the window, vertically using the pageYOffset property. An example displays the same and returns the pixels: <!DOCTYPE html> <html> <head> <style> div { height: 1300px; width: 1300px; } </style> </head> <BODY> <script> function display() { window.scrollBy(200, 200); alert("pageYOffset pixels = " + window.pageYOffset); } </script> <button onclick="display()" style="position:fixed;">Display</button> <br><br><br> <div> </div> </body> </html> |
|
| 81. |
Detect if JavaScript is disabled in a web browser |
|
Answer» The javascript:void(0) evaluates an expression even if its addition to a web page brings unwanted output. The output is displayed below. Nothing happens when the link is CLICKED: |
|
| 82. |
Replace a JavaScript alert pop up with a fancy alert box? |
|
Answer» An inline FUNCTION is assigned to a variable created at runtime. It is assigned to a variable and can be easily reused. Creating a function WITHOUT any name is what we call Anonymous functions. Let us see an example: <!DOCTYPE html> <html> <BODY> <p ID="demo"></p> <script> var res = function (val1, val2, val3) {RETURN val1 * val2 * val3}; document.getElementById("demo").innerHTML = res(5, 10, 15); </script> </body> </html>The output: 750 |
|
| 83. |
Check if a variable exist in JavaScript |
|
Answer» The <noscript> TAG is used in JavaScript to allow adding an alternate message if you disable JavaScript in the web browser. In this way a user can know whether the web browser has JavaScript or not. If it’s not there, then the message added USING the <noscript> is visible. The above code will allow the web browser that doesn't support JavaScript to display the text which we added under <noscript> tag i.e. "Your browser does not support JavaScript!". |
|
| 84. |
Should I always put my JavaScript in the head tag of my HTML file? |
|
Answer» Use CSS and jQuery to replace the DEFAULT JavaScript alert pop up. Let us first see how to create an alert in JavaScript and how the default looks: <!DOCTYPE html> <html> <body> <h1>Alerts in JavaScript</h1> <button onclick="show()">Display</button> <script> function show() { alert("This is an alert box!"); } </script> </body> </html>The output displays a button, which is to be clicked to generate an alert: On clicking the above button, the following alert generates:
Under <style> above, we added the CSS code. The output displays a button which is to be clicked to generate an alert: On clicking the above “Display” button, the following alert is visible which we styled. The background color is not blue. The button color and style is also changed: |
|
| 85. |
How to find whether browser supports JavaScript or not |
|
Answer» The best way to CHECK if a variable exist in JavaScript is to verify it with null. The output: Variable do exist!Above, we worked on the condition that a variable exist if it is not null. Therefore we CHECKED the value if variable a like this: if(a != null) { document.write("Variable do exist!"); } |
|
| 86. |
Why to avoid global variables in JavaScript |
|
Answer» Place the JavaScript anywhere WITHIN your web page, but it is recommended to include it within the <head> or <body> tag. The following are the different ways in which we can include JavaScript code in an HTML In head section If you WANT the SCRIPT to run on some event, then add the JavaScript code in the head section of the HTML file. Let us see an example: <html> <head> <script> <!-- function show() { alert("Demo!") } //--> </script> </head> <body> <input TYPE="button" onclick="show()" value="Click" /> </body> </html>In body section If you want the script to run on page load, then add the JavaScript code in the body section of the HTML file. Let us see an example: <html> <head> </head> <body> <script> <!-- document.write("Demo") //--> </script> <p></p> </body> </html> |
|
| 87. |
How to create object properties in JavaScript? |
|
Answer» To find whether the web browser supports JavaScript or not, you can TEST it on your local system. The above code will allow the web browser that doesn't support JavaScript to display the text which we added under <noscript> tag i.e. "Your browser does not support JavaScript!". |
|
| 88. |
How to enable JavaScript in Windows |
|
Answer» Global variables are WIDELY used and do not create any SECURITY concern. |
|
| 89. |
Anonymous functions vs JavaScript closures |
|
Answer» The object properties are variables used internally in the object's methods. These variables can also be globally visible throughout the page. The properties are the values associated with a JavaScript object. Let US SEE how to create and ACCESS object properties: <!DOCTYPE html> <html> <body> <H2>Department</h2> <p id="myid"></p> <script> var department = { id: 5, name : "Finance", Location : "NORTH" }; document.getElementById("myid").innerHTML = department.id + " is " + department.name + " department's id."; </script> </body> </html>The following is the output: Above we access the object properties as: objectName.propertyAs shown above, we used to access object properties. Here, “Department” is our object whereas “name” is our property: department.name |
|
| 90. |
How does JavaScript .prototype work? |
|
Answer» To enable JavaScript in Windows, you NEED to work on “Internet Options” in Windows. Here are the steps: Go to “START” on Windows, type “Internet Options” and click on it: On CLICKING, the following dialog box would be visible: Go to “Security” tab now and click “Custom Level”. Now you will reach the “Security Settings” dialog box: Now under “Active Scripting”, enable “JavaScript” as shown in the following screenshot:
|
|
| 91. |
Is there any <noscript> element in JavaScript? |
|
Answer» JavaScript Closures A closure is a FUNCTION in JavaScript which have access to the parent scope, even after closing the parent function. Let us see an EXAMPLE: <!DOCTYPE html> <html> <body> <p>Increment by 5</p> <button type="button" onclick="show()">Count!</button> <p ID="myid">0</p> <script> var sum = (function () { var count = 0; return function () {count += 5; return count;} })(); function show(){ document.getElementById("myid").innerHTML = sum(); } </script> </body> </html>The output: After clicking “Count” above, the value increments by 5: In the above example, the following VARIABLE is assigned the return value of a function which is self-invoking: var sum = (function () {The self-invoking function sets the count to zero: var count = 0; return function () {count += 5; return count;}It returns a function expression as you can see above. This makes it a function and can access the count in the parent scope as well. This is what we can call closure in JavaScript. Anonymous functions Creating a function without a name is what we call Anonymous functions. Let us see an example: <!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var res = function (val1, val2, val3) {return val1 * val2 * val3}; document.getElementById("demo").innerHTML = res(5, 10, 15); </script> </body> </html>The output: 750Above, we have function without a name: var res = function (val1, val2, val3) {return val1 * val2 * val3}; |
|
| 92. |
JavaScript Native Objects? |
|
Answer» The JAVASCRIPT engine adds a prototype property to the function when a function is created. This prototype property is an object. The objects inherit the properties and methods from their prototype. Access the function’s prototype property using the following syntax: functionName.prototypeHere’s an EXAMPLE: <!DOCTYPE html> <html> <BODY> <h2>Player</h2> <p ID="DETAILS"></p> <script> function Team(rank, name) { this.rank = rank; this.name = name; } var res = new Team("3", "Jacob"); document.getElementById("details").innerHTML = "The name of the Player is " + res.name; </script> </body> </html>The output: |
|
| 93. |
Why the 'with' keyword is used in JavaScript? |
|
Answer» Yes, <noscript> element do exist in JavaScript. Use this element to set a message for USERS if the web browser they are using do not support JavaScript. This is also useful if the scripts have been disabled in the web browser. The above code will allow the web browser that doesn't support JavaScript to DISPLAY the text which we added under <noscript> tag i.e. "Your browser does not support JavaScript!". |
|
| 94. |
How to create a blink text using JavaScript? |
|
Answer» It is said in JavaScript that almost everything is an object. JavaScript has many NATIVE or built-in objects. Let us see some of them:
Example: Create an object Let us now see how to create an object in JavaScript. To create an object in JavaScript, use “new” as shown below. It is followed by the constructor method Object(): var department = new Object();Let us see an example to create an object using Object() constructor: <html> <head> <title>Objects</title> <script> var department = new Object(); department.name = "FINANCE"; department.id = 005; department.location = "North"; </script> </head> <body> <h2>Department Details</h2> <script> document.write("Department Name = " + department.name + "<br>"); document.write("Department Id = " + department.id + "<br>"); document.write("Department Location = " + department.location); </script> </body> </html>The output: Above, firstly we have created an object: var department = new Object();After that properties are assigned: department.name = "Finance"; department.id = 005; department.location = "North";Example: Create a Boolean Object The Boolean object represents two values, i.e. "true" or "false". Let us now see an example wherein we will create a Boolean object and return the VALUE. We are using Boolean valueOf() method: <!DOCTYPE html> <html> <body> <script> var val = new Boolean(true); document.write( "Value = " + val.valueOf() ); </script> </body> </html>The output: Value = trueHere is another example wherein we are returning the string representation of a Boolean value. We are creating a Boolean object first: <!DOCTYPE html> <html> <body> <script> var val = new Boolean(false); document.write( "String = " + val.toString() ); </script> </body> </html>The output: String = falseExample: Create a Number Object The Number object represents numerical date, i.e. integers or floating-point numbers. Let us now see how to create a Number object: var val = new Number(25);Let us now create an object with floating-point value: var val = new Number(35.90)An example here is to get the value of the specified Number object. We are creating a Number object: <html> <head> <title>JavaScript Number Object</title> </head> <body> <script> var val = new Number(35.70); document.write("Value = " + val.valueOf()); </script> </body> </html>The output: Value = 35.7Let us now create another Number object and represent it in String: <html> <head> <title>JavaScript Number Object</title> </head> <body> <script> var val = new Number(90); document.write("String: " + val.toString()); </script> </body> </html>The output: String: 90 |
|
| 95. |
What is Number.NEGATIVE_INFINITY constant in JavaScript |
|
Answer» To reference an object's properties or methods, use the with keyword. The syntax: with (obj){ properties USED without the object name and dot }The “obj” becomes the default object for the duration of the block that FOLLOWS. Now the object’s properties and methods can be used without even naming the object. The example demonstrates the usage of with keyword: <html> <head> <title>JavaScipt with keyword</title> <script> function stock(count){ with(this){ inventory = count; } } function product(pname, category, id){ this.pname = pname; this.category = category; this.id = id; this.inventory = 0; this.stock = stock; } </script> </head> <body> <script> VAR p = new product("SHIRT", "CLOTHING", 17); p.stock(100); document.write("Product Name : " + p.pname + "<br>"); document.write("Product Category : " + p.category + "<br>"); document.write("Product ID : " + p.id + "<br>"); document.write("Product Inventory : " + p.inventory + "<br>"); </script> </body> </html>The output: Product Name : Shirt Product Category : Clothing Product ID : 17 Product Inventory : 100 |
|
| 96. |
Absolute value of a number in JavaScript? |
|
Answer» To display a blink text, use the blink () method in JavaScript. The string blinks using this method. Note: The blank() method is not part of the standard now and the <blank> element is OBSOLETE. THEREFORE, it may not work on modern web browsers. Let us SEE an example: <html> <BODY> <script> var myStr = "Learn!"; var res = myStr.blink(); document.write(res) </script> </body> </html>The output displays the text and it may or may not blink, SINCE the method is not part of the standard now: Learn! |
|
| 97. |
Role of JSON.stringify() in JavaScript |
|
Answer» The NEGATIVE_INFINITE property is a property of the NUMBER Object in JavaScript, which is negative INFINITY. The following is the syntax: Number.NEGATIVE_INFINITY;The return value is -Infinity. LET us now see an EXAMPLE: <!DOCTYPE html> <html> <body> <script> var val = 5; document.write(val.NEGATIVE_INFINITY); </script> </body> </html>The output: Undefined |
|
| 98. |
Role of “use strict” in JavaScript |
|
Answer» The Math.ABS() method is used in JavaScript to FIND the absolute value of a number. The FOLLOWING is the parameter of abs(val) method:
The method returns:
Let us see an example to get the absolute value of a negative number: var val = -9.50;To get the absolute value: Math.abs(val);The entire example: <!DOCTYPE html> <html> <body> <script> var val = -9.50; document.write("Number: "+val); var res = Math.abs(val); document.write("<br>Absolute Value: "+res); </script> </body> </html>The output returns the negative value: Number: -9.5 Absolute Value: 9.5Let us see another example for “null” as input: <!DOCTYPE html> <html> <body> <script> var val = null; document.write("Number: "+val); var res = Math.abs(val); document.write("<br>Absolute Value: "+res); </script> </body> </html>The output: Number: null Absolute Value: 0Let us see another example to get the absolute value: <!DOCTYPE html> <html> <body> <script> var val = 15+30+55; document.write("Number: "+val); var res = Math.abs(val); document.write("<br>Absolute Value: "+res); </script> </body> </html>The output: Number: 100 Absolute Value: 100 |
|
| 99. |
What are event handlers in JavaScript? |
|
Answer» When data is sent to a web server, it has to be in the form of string. The JSON.stringify() method is USED in JavaScript to convert an object to string. Let’s say we have the following object in JavaScript: VAR ob = { deptname: "Finance", deptid: 2, deptlocation: "East", deptEmployees: 150 };Now use the JSON.stringify() method to convert the above object into string: var res = JSON.stringify(ob);Now, display it with INNERHTML. Let us SEE the example: <!DOCTYPE html> <html> <body> <h2>JSON String</h2> <p id="myid"></p> <script> var ob = { deptname: "Finance", deptid: 2, deptlocation: "East", deptEmployees: 150 }; var res = JSON.stringify(ob); document.getElementById("myid").innerHTML = res; </script> </body> </html>The output generates the string: |
|
| 100. |
Remove whitespace from both sides of a string in JavaScript |
|
Answer» The “USE strict” is a literal expression introduced in ECMAScript version 5. It indicates that the code should be executed in "strict mode", which in turn considered a good practice. The key use of this mode is if you won’t declare a variable and use it, then an error would be visible. Let us see what we discussed using the following example: <script> "use strict"; // a is not defined a = 10; </script>Since, variable “a” is not defined above, the following error would be visible if you will Press F12 for debugging: a is not definedThe following is not allowed in strict mode with “use strict”: Case1: It is not allowed to delete a variable in strict mode "use strict"; // error var a = 10; delete a;Above generates the following error in strict mode, when you will enable debugging with F12 on web browser: Error: DELETION of an UNQUALIFIED identifier in strict modeCase 2: Using Octal numeric LITERALS are not allowed <script> "use strict"; // error var a = 012; </script>Above generates the following error in strict mode, when you will enable debugging with F12 on web browser: Error: Octal literals are not allowed in strict mode |
|