Explore topic-wise InterviewSolutions in .

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.

101.

Regular Expression in JavaScript to display non-digit characters from a string

Answer»

Events handlers assist in JavaScript's interaction with HTML. Events can be related to a button being click or a web page loaded. Resizing a WINDOW also comes under event.

The following are the event handlers in JavaScript:

Event Handers
Triggers
onblurWhen the window loses focus
onchangeWhen an element change.
onclickOn a mouse click
ondblclickOn a mouse double-click
ondragWhen an element is dragged
ondragendAt the end of a drag operation
ondragenterWhen an element has been dragged to a VALID drop target
ondragleaveWhen an element is being dragged over a valid drop target
ondragoverAt the start of a drag operation
ondragstartAt the start of a drag operation
ondropDragged element is being dropped
ondurationchangeWhen the length of the media is changed
onerrorWhen an error occur
oninputWhen an element gets user input
oninvalidWhen an element is invalid
onkeydownWhen a key is pressed
onkeypressWhen a key is pressed and released
onkeyupWhen a key is released
onmousedownTriggers when a mouse button is pressed
onmousemoveTriggers when the mouse pointer MOVES
onmouseoutTriggers when the mouse pointer moves out of an element
onmouseoverTriggers when the mouse pointer moves over an element
onmouseupTriggers when a mouse button is released
onmousewheelTriggers when the mouse wheel is being rotated

Let us SEE an example of onclick event in JavaScript wherein the event gets triggered when left button of the mouse is clicked:

<html&GT;    <head>       <script>          <!--             function show() {                alert("This is a message!")             }          //-->       </script>    </head>    <body>       <p>Click the below button:</p>       <form>          <input type="button" onclick="show()" value="Display" />       </form>    </body> </html>

The output: Event gets triggered when you click on the button to generate the following alert: 

Let us see another example wherein we are displaying the current date and time on click of a button:

<!DOCTYPE html> <html> <body> <button onclick="document.getElementById('myid').innerHTML=Date()">Time</button> <h2 id="myid"></h2> </body> </html>

The following output generates on the click of a button that we created in the example above:

102.

Join two or more strings in JavaScript

Answer»

The trim() method is used to remove whitespace from both sides of a string.

Let’s say we have the following string with leading and trailing whitespace:

var myStr = "     Cup of tea!    ";

To remove whitespaces, USE the trim() method: 

myStr.trim( )

The example DEMONSTRATES how to remove whitespaces from both the sides of a string in JavaScript: 

<!DOCTYPE HTML> <html> <body> <script>     var myStr = "     Cup of tea!    ";     document.writeln("String (after REMOVING leading and trailing whitespace): "+myStr.trim()); </script> </body> </html>

The output displays the same string after removing the leading and trailing whitespace:

String (after removing leading and trailing whitespace): Cup of tea!
103.

What is onclick event in JavaScript?

Answer»

Let’s say the following is our string with numbers and special characters: 

var strNum = "DEMO989#@#@"; 

The following RegExp is used to get a non-digits: 

\D/g

Above we have set the g flag to PERFORM global match.

The following is the code:

<HTML>    <head>       <title>Regular Expression in JAVASCRIPT</title>    </head>    <body>       <SCRIPT>         var strNum = "DEMO989#@#@";         var regExp = /\D/g;         document.write("String with numbers and characters = "+strNum)         var res = strNum.match(regExp);         document.write("<br>GETTING Non-Digits = "+res);       </script>    </body> </html>

The output displays non-digits:

String with numbers and characters = DEMO989#@#@ Getting Non-Digits = D,E,M,O,#,@,#,@
104.

What are cookies in JavaScript?

Answer»

To JOIN two or more strings, use the JavaScript concat() method. A new string is returned with the JOINED strings.

The syntax:

string.concat(str1, str2, str3..., strn)

Here, str1, str2, and str3 are the strings you want to join.

Let’s say the following are our two strings to be joined:

var myStr1 = "One"; var myStr2 = "Time!";

Now, use the concat() method to join both the strings:

var res = myStr1.concat(myStr2);

The example DEMONSTRATES how to join two strings:

<!DOCTYPE html> <html> <body> <button ONCLICK="show()">Joined Strings</button> <p id="myid"></p> <script> function show() {a     var myStr1 = "One";     var myStr2 = "Time!";     var res = myStr1.concat(myStr2);     document.getElementById("myid").innerHTML = res; } </script> </body> </html>

The output:

Let us now see another example wherein we will join three strings. Now we have three strings:

var myStr1 = "Only"; var myStr2 = " One"; var myStr3 = " Time!";

Join three strings with the concat() method but with an extra parameter for the 3rd string:

myStr1.concat(myStr2, myStr3);

The example that joins three strings:

<!DOCTYPE html> <html> <body> <button onclick="show()">Joined Strings</button> <p id="myid"></p> <script> function show() {     var myStr1 = "Only";     var myStr2 = " One";     var myStr3 = " Time!";     var res = myStr1.concat(myStr2, myStr3);     document.getElementById("myid").innerHTML = res; } </script> </body> </html>

The output displays the result of three strings in a new string on the click of a button:

105.

Increase the size of the text content in JavaScript

Answer»

The onclick event gets triggered in JavaScript when a user clicks on any of the HTML ELEMENT such as on click of a button.

Let us see an example of onclick event in JavaScript WHEREIN the event gets triggered when left button of the mouse is clicked:

&LT;html>    <head>       <script>          <!--             function SHOW() {                alert("This is a message!")             }          //-->       </script>    </head>    <body>       <p>Click the below button:</p>       <form>          <input type="button" onclick="show()" value="Display" />       </form>    </body> </html>

The output displays a button:

Event gets triggered when you click on the button to generate the following alert: 

Let us see ANOTHER example wherein we are displaying the current date and time on click of a button: 

<!DOCTYPE html> <html> <body> <button onclick="document.getElementById('myid').innerHTML=Date()">Time</button> <h2 id="myid"></h2> </body> </html>

The following output generates on the click of a button that we created in the example above: 

106.

What is the use of JavaScript eval function?

Answer»

Cookies has a plain text record of fields: Expires, Domain, Path, SECURE, etc. They are generally used to track preferences, commissions, etc. It is STORE information on your COMPUTER in the form of plain text. Cookies are saved in name-value pairs. It gets deleted when the web browser is closed.

LET us see how we can create a cookie in JavaScript:

The document.cookie property is used in JavaScript to create cookies. With the same property, you can also read and delete cookies.

Create a cookie:

document.cookie = "username=Knowledge Hut";

Add an expiry date to the cookie create above: 

document.cookie = "username= Knowledge Hut; expires=Thu, 12 Dec 2018 12:00:00 UTC";

To read a cookie in JavaScript:

var a = document.cookie;

The above displays the cookies in name-value form i.e.: 

cookie1=value; cookie2=value;

To delete a cookie, you need to just set the cookie to the past date. The date is included using the expires parameter:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

Let us see an example that creates and set a cookie: 

<html>    <head>       <script>          <!--             function displayCookie()             {                if( document.one.dept.value == "" ){                   alert("Enter some value!");                   return;                }                val = escape(document.one.dept.value) + ";";                document.cookie="name=" + val;                document.write ("Setting Cookie <br> " + "name=" + val );             }          //-->       </script>    </head>    <body>       <form name="one" action="">          Enter Department: <input type="text" name="dept"/>          <input type="button" value="Input Cookie" onclick="displayCookie();"/>       </form>    </body> </html>

The output displays an input, wherein we add a value to set as cookie: 

On clicking “Input Cookie” above, you can see that we have set the cookie successfully:

107.

What is Modulus Operator (%) in JavaScript?

Answer»

To INCREASE the size of the text, you need to USE the JavaScript big() method. USING it, you can easily display a string in a font size BIGGER than the normal font.

The following is an example to create a text with big font:

&LT;html>    <head>       <title>JavaScript big()</title>    </head>    <body>       <script>          var myStr = "Demo Text";          document.write("Normal font: "+myStr)          document.write("<br>Bigger font: "+myStr.big());       </script>    </body> </html>

The output displays normal as well as bigger font using the <big> element: 

108.

How to handle exceptions in JavaScript?

Answer»

The eval() function is used in JavaScript to evaluate or execute an argument. The method evaluates the expression, if the argument is an expression, else for arguments as statements, it executes the statements.

The parameter in the eval(string) function is a string, which can be an expression, variable, statement, or sequence of statements:

eval(string)

Note: Do not call eval() method to evaluate an ARITHMETIC expression

Let’s say we have the following two variables:

var val1 = 20; var val2 = 7;

Now, with a new variable we will perform some calculations with the eval() method:

var calc1 = eval("val1 * val2") + "<br>"; var calc2 = eval("99 + val1") + "<br>";

The example demonstrates the role of eval() in JavaScript:

<!DOCTYPE html> <html> <body> <button onclick="SHOW()">Display</button> <p id="myid"></p> <script> function show() {     var val1 = 20;     var val2 = 7;     var calc1 = eval("val1 * val2") + "<br>";     var calc2 = eval("99 + val1") + "<br>";     var RES = calc1 + calc2;     document.getElementById("myid").innerHTML = res; } </script> </body> </html>

The output displays a button, which on pressing GENERATES the following result: 

140 119

Let us see another example: 

<!DOCTYPE html> <html> <body> <button onclick="show()">Display</button> <p id="myid"></p> <script> function show() {     var val1 = 15;     var val2 = 10;     var calc1 = eval("30 * 3") + "<br>";     var calc2 = eval("val1 + val2") + "<br>";     var calc3 = eval("5 * val1") + "<br>";     var calc4 = eval("10 + val2") + "<br>";     var res = calc1 + calc2 + calc3 + calc4;     document.getElementById("myid").innerHTML = res; } </script> </body> </html>

The output displays a button, which on pressing generates the following result:

90 25 75 20
109.

What are the different types of pop-up boxes in JavaScript?

Answer»

To RETURN the division remainder, use the Modulus operator in JavaScript.

Let’s say the following are our two variables for which we want the modulus:

var val1 = 20; var val2 = 8;

Now, let us use the % operator to find the remainder:

var RES = val1 % val2;

The example finds the division remainder using the Modulus operator:

&LT;!DOCTYPE html> <html> <body> <h2>Remainder</h2> <p id="DEMO"></p> <script> var val1 = 20; var val2 = 8; var res = val1 % val2; document.getElementById("demo").innerHTML = res; </script> </body> </html>

The output displays the remainder:

110.

In how many ways a JavaScript code can be included in an HTML file?

Answer»

To handle exceptions in JavaScript, use the try, catch, throw and finally statements.

The try statement DEFINES a block of code to be tested for errors, whereas the catch statement allows defining a block of code to be executed if an error occurs in the try.

The try block MUST be followed by EITHER EXACTLY one catch block or one finally block.

Let us SEE an example of try, catch and finally: 

<html>    <head>       <script>          <!--             function show()             {                var val = 5;                try {                   alert("Value = " + val );                }                catch ( e ) {                   alert("Error = " + e.description );                }                finally {                   alert("Finally block executes!" );                }             }          //-->       </script>    </head>    <body>       <p>Click below:</p>       <form>          <input type="button" value="Display" onclick="show();" />       </form>    </body> </html>

The output on running displays the following button:

On clicking the above button, an alert box is visible: 

No error is there. On clicking “OK”, the “finally” statement executes. The alert box in the “finally” generates the following alert: 

111.

What is type of Operator in JavaScript?

Answer»

The following are the types of pop-up boxes available in JAVASCRIPT:

Alert Box

The alert box is for an alert or message to the user. User needs to click “OK”. The alert() method is used to add a message in the alert:

Let us see an example:

<!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 an alert on the click of a button:

On clicking the above button, the following alert generates: 

Prompt Box

To input a value from the user and display it, use the prompt box. Users need to click “OK” to return the entered input, else click “Cancel” to return null.

Let us see an example:

<!DOCTYPE html> <html> <body> <button onclick="show()">Display</button> <p id="myid"></p> <script> function show() {   var res;   var department = prompt("Enter your Department", "Operations");   if (department == null || department == "") {     res = "Prompt cancelled!";   } else {     res = "Department is " + department;   }   document.getElementById("myid").innerHTML = res; } </script> </body> </html>

The output first displays the button which you need to click: 

On clicking the above button, a prompt box is visible WHEREIN user input is requested: 

On clicking “Ok”, the input is DISPLAYED on the web page: 

Confirm Box

The confirm box is used in JavaScript to take user’s consent or accept something. User need to click “OK” to return true, else click “Cancel” to return false.

Let us see an example:

<!DOCTYPE html> <html> <body> <button onclick="show()">Display</button> <p id="myid"></p> <script> function show() {   var res;   if (confirm("Press a button!")) {     res = "OK is pressed!";   } else {     res = "Cancel is pressed!";   }   document.getElementById("myid").innerHTML = res; } </script> </body> </html>

The following is the output. The button is visible. You need to click it: 

On clicking the above button, a confirm box generates that WANTS users’ consent on clicking the button: 

On PRESSING OK, the following is visible: 

112.

How to create a Cookie with JavaScript?

Answer»

The following are the different ways in which we can include JavaScript code in an HTML file. We can add JavaScript in the same file or an external file:

Java Script in the same file

Add the JavaScript code in the same HTML file using any of the following ways:

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>

JavaScript in an external file

Using the <script> TAG you can STORE the JavaScript code in an external .JS extension file. The tag with the “src” attribute allows you to include this js file in your HTML.

If you are using the same JavaScript code in almost every page, then it’s a good practice to create an external JS file and include it in HTML of every page. This enhances the loading time.

Here’s how you can create external JavaScript file with the extension .js. After creating, add it to the HTML file in the <script> tag. The src attribute is used to include the external JavaScript file in your HTML:

<script src="myfile.js" ></script>

Let’s say the following is the content of our external JS file “myfile.js”:

function show () {      alert("Learning is fun!");   }

The following is our HTML file, wherein we will include the external file “myfile.js”:

<html>    <body>        <form>         <input type="button" value="Click" onclick="show()"/>          </form>       <script src="show.js">       </script>    </body> </html>

Press the button “Click”: 

On clicking above, the following alert is visible which we added in the external file by creating a JavaScript function: 

113.

Unsigned Right Shift Operator (&gt;&gt;&gt;) in JavaScript?

Answer»

The typeof operator is a unary operator in JAVASCRIPT. It is used to check the data type of its OPERAND, LIKE a variable is string, numeric, boolean, etc.

Let us see a simple EXAMPLE for number:

<html>    <body>       <script>          var val = 10;          document.write(typeof val);       </script>    </body> </html>

The output displays that it is a number: 

Number

Let us now see ANOTHER example for string:

<html>    <body>       <script>          var val = "Sachin";          document.write(typeof val);       </script>    </body> </html>

The output displays that it is a string:

String

In the same way, we can check the type of a value entered, which is a boolean:

<html>    <body>       <script>          var val = true;          document.write(typeof val);       </script>    </body> </html>

The output display that the value entered is a boolean:

boolean

As we saw some examples above, here is the list of the values returned by the typeof operator:

Type
String Returned
Number type
Returns “number”
String type
Returns “string”
Object type
Returns “object”
Boolean type
Returns “boolean”
Null
Returns “null”
114.

Search for a string in a string with JavaScript

Answer»

Cookies has a plain text RECORD of fields: Expires, Domain, Path, Secure, etc. They are generally used to track preferences, commissions, etc. It stores information on your computer in the form of plain text. Cookies are saved in name-value pairs. It gets deleted when the web browser is closed.

Let us see how we can create a cookie in JavaScript:

The document.cookie property is used in JavaScript to create cookies. With the same property, you can also read and delete cookies.

Create a cookie:

document.cookie = "username=Knowledge Hut";

Add an EXPIRY date to the cookie created above:

document.cookie = "username= Knowledge Hut; expires=Thu, 12 Dec 2018 12:00:00 UTC";

To read a cookie in JavaScript:

var a = document.cookie;

The above displays the cookies in name-value form i.e.:

cookie1=value; cookie2=value;

To delete a cookie, you need to just set the cookie to the past date (expire). The date is included USING the expires parameter:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

Let us see an example that CREATES a cookie:

<html>    <head>       <script>          <!--             function displayCookie()             {                if( document.one.dept.value == "" ){                   alert("Enter some value!");                   return;                }                val = escape(document.one.dept.value) + ";";                document.cookie="name=" + val;                document.write ("Setting Cookie <br> " + "name=" + val );             }          //-->       </script>    </head>    <body>       <form name="one" action="">          Enter Department: <input type="text" name="dept"/>          <input type="button" value="Input Cookie" onclick="displayCookie();"/>       </form>    </body> </html>

The output displays an input box, wherein we add a value to set as cookie:

On clicking “Input Cookie” above, you can see that we have set the cookie successfully:

115.

What is the new way to define a variable in JavaScript?

Answer»

In the unsigned right SHIFT operator (>>>), the bits shifted on the left are always zero.

The zeros get filled in from the left with the operator. It shifts all bits in a 32-bit number to the right.

The following is an example:

&LT;html>    <BODY>       <script>          var val1 = -23;          var val2 = 2;          document.write("val1 >>> val2 = ");          res = (val1 >>> val2);          document.write(res);       </script>    </body> </html>

The OUTPUT:

val1 >>> val2 = 1073741818

Let us see another example wherein we have a positive number. In this CASE the operator works the same as a signed right shift:

<html>    <body>       <script>          var val1 = 7;          var val2 = 2;          document.write("val1 >>> val2 = ");          res = (val1 >>> val2);          document.write(res);       </script>    </body> </html>

The output:

val1 >>> val2 = 1
116.

Regular Expression in JavaScript to display digits from a string with numbers

Answer»

<P>To search for a string in a string, use the search() method. The method searches a string for a specified value. The returned value is the position of the match. However, -1 is returned if the match isn’t found.

LET’s say we have the following string:

var myStr = "Popular Programming LANGUAGES";

We want to search the below string from the above string:

Languages

For that, use the search() method:

var RES = myStr.search("Languages");

Let us see the example wherein the string is successfully searched and the result (position) is displayed on button click:

<!DOCTYPE html> <html> <body> <p>Click the below button...</p> <button onclick="SHOW()">Search</button> <p id="myid"></p> <script> function show() {     var myStr = "Popular Programming Languages"     var res = myStr.search("Languages");     document.getElementById("myid").innerHTML = res; } </script> </body> </html>

The output displays the position:

Let us now see another example, wherein -1 is returned since the string to be found isn’t there: 

<!DOCTYPE html> <html> <body> <p>Click the below button...</p> <button onclick="show()">Search</button> <p id="myid"></p> <script> function show() {     var myStr = "This is an example!"     var res = myStr.search("demo");     document.getElementById("myid").innerHTML = res; } </script> </body> </html>

The output on button click displays -1:

117.

How to compare two dates in JavaScript?

Answer»

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&GT; <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 2 as the variable i value: 

Example of var

Let us see the same example using var this time instead let keyword:

<!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 10 as the value of variable i:

118.

Are there constants in JavaScript?

Answer»

Let’s say the FOLLOWING is our string with numbers:

VAR strNum = "only123!";

To fetch the digits from the above string, the following REGEXP is used:

/\d/G

Above we have set the g flag to perform global match.

The following is the code:

<html&GT;    <head>       <title>Regular Expression in JavaScript</title>    </head>    <body>       <script>         var strNum = "only123!";         var regExp = /\d/g;         document.write("String with numbers: "+strNum)         var res = strNum.match(regExp);         document.write("<br>Getting Digits = "+res);       </script>    </body> </html>

The output:

String with numbers: only123! Getting Digits = 1,2,3
119.

Different ways to create an array in JavaScript?

Answer»

To COMPARE two dates in JavaScript, FIRSTLY add two date objects and SET dates.

Here, our first date is the current date:

To compare two dates in JavaScript, firstly add two date objects and set dates.

Here, our first date is the current date:

var one, two; one = new Date();         two = new Date( "MAR 10, 2017 20:15:10" );

And the second date we have set as past date:

two = new Date( "Mar 10, 2017 20:15:10" );

Now, let us compare the above two dates using the below given code:

<!DOCTYPE html> <html> <body> <script>   var one, two;   one = new Date();   document.write(one);   two = new Date( "Mar 10, 2017 20:15:10" );   document.write("<br>"+two);   if (one > two) {       document.write("<br>First date is the recent date.");   } ELSE {       document.write("<br>Second date is the recent date.");   } </script> </body> </html>
120.

How to validate decimal numbers in JavaScript

Answer»

Yes, constants do exist in JavaScript. The “const” keyword is used to create constant in JavaScript.

The const variables in JavaScript must be assigned a value when they are declared. Once declared, you cannot change and declare the value of constant again.

For example:

const val = 100;

Another example include:

const PI = 3.14159265359;

With const, you can declare local variables with block scope rather than function scope. Let’ say we have a constant variable “a”. After declaring a value LIKE a constant variable, you can’t assign a new value to it.

Here’s an example wherein we are trying to reassign value to a const variable. As expected an error generates:

// declared a constant variable. const val= 150; // Error, SINCE we try to assign a new value to the constant val = 0;

The following also gives an error since we are trying to change the primitive value:

const PI = 3.14159265359; PI = 3.14;

You cannot even reassign a constant array. Let us see an example for this:

<!DOCTYPE HTML> <html> <body> <p id="myid"></p> <script> try {   const department = ["Finance", "HR", "MARKETING", "Operations"];   department = ["Operations", "IT", "Accounting", "Production"]; // error } catch (e) {   document.getElementById("myid").innerHTML = e; } </script> </body> </html>

The output displays an error as shown below since we cannot assign to a constant variable:

TypeError: Assignment to constant variable.
121.

Should I include type=“text/javascript” in my SCRIPT tags

Answer»

Arrays in JavaScript are used to store multiple VALUES in a single variable. Let us see the two ways to create an array in JavaScript:

Using Array Literal

The easiest way to create an array in JavaScript is with array literal. Here, we have a variable and we are setting multiple values to it in an array:

var CARS = ["Saab", "Volvo", "BMW"];

Let us see an EXAMPLE:

<!DOCTYPE html> <html> <body> <p id="myid"></p> <script> var department = ["HR", "FINANCE", "Operations", "Marketing"]; document.getElementById("myid").innerHTML = department; </script> </body> </html>

The output:

HR,Finance,Operations,Marketing

Using keyword new

With JavaScript, you can also create an array using the new operator:

var department = new Array("HR", "Finance", "Operations", "Marketing");

Let us see an example:

<!DOCTYPE html> <html> <body> <p id="myid"></p> <script> var department = new Array("HR", "Finance", "Operations", "Marketing"); document.getElementById("myid").innerHTML = department; </script> </body> </html>

The output:

HR,Finance,Operations,Marketing
122.

When is the comma operator useful in JavaScript?

Answer»

To validate decimal numbers in JavaScript, you can use regular expressions for matching with the match() method:

Let’s SAY we have the following decimal with string representation:

var val = "5.9";

The following regular expression you can use: 

var reg = /^[-+]?[0-9]+\.[0-9]+$/;   var res = val.match( reg );

For validation, we USED the above regular expression and test it using the match() method. It gives us whether the given value is decimal or not:

<html>    <body>       <script>         var val = "5.9";          var reg = /^[-+]?[0-9]+\.[0-9]+$/;            var res = val.match( reg );          if(res)            document.write("Decimal!" );          else            document.write("Not a decimal!" );       </script>    </body> </html>

The output displays ‘decimal’ since the if statement is TRUE:

Decimal!

Let us see another EXAMPLE with a DIFFERENT input i.e. a number:

<html>    <body>       <script>         var val = "7";          var reg = /^[-+]?[0-9]+\.[0-9]+$/;            var res = val.match( reg );          if(res)            document.write("Decimal!" );          else            document.write("Not a decimal!" );       </script>    </body> </html>

The output is ‘not a decimal!’, since the if statement is false:

Not a decimal!

Let us see another example and check for string:

<html>    <body>       <script>         var val = "abc";          var reg = /^[-+]?[0-9]+\.[0-9]+$/;            var res = val.match( reg );          if(res)            document.write("Decimal!" );          else            document.write("Not a decimal!" );       </script>    </body> </html>

The output displays ‘not a decimal!’ since the if statement is false:

Not a decimal!
123.

What does the leading semicolon in JavaScript libraries do?

Answer»

JavaScript used previously had the TYPE ATTRIBUTE USAGE like this:

<html>    <body>       <script language="javascript" type="text/javascript">          <!--             document.write("Demo!")          //-->       </script>    </body> </html>

Above, you can SEE we have SET the script language as “javascript” and the type as “text/javascript”.

The usage of type=”text/javascript” was necessary before the introduction of HTML5. But, when HTML5 came, JavaScript became its default language. Therefore, adding “text/javascript” is optional.

124.

How can I replace newlines with spaces in JavaScript?

Answer»

The comma operator in JavaScript evaluates each of its operands. It returns the value of the LAST operand.

  • Multiple Expressions

With the usage of comma operator, you can easily add multiple expressions. The syntax:

exp1, exp2, exp3, ……exp

Here, exp1, ex,2 exp3 are the expressions.

  • Multiple parameters in for loop

Add multiple parameters in a for loop USING the comma operator:

for (var a = 0, b = 5; a <= 5; a++, b--)
  • Return Statement

Use the comma operator in a return statement. Process before returning using comma:

FUNCTION show() {   var x = 0;   return (x += 1, x); }
  • Declare multiple variables at once

With comma operator, you can declare multiple variables at once. Let’s say you have three variables. To declare and initialize them on NEW lines, you can declare them in a single LINE as shown below:

var a = 5, b = 10, c = 30;
  • Multiple arguments in a function call

You can also use the comma operators to call multiple arguments in a function call. Let’s say you have a function “calculate” and you need to find the multiplication of three numbers. For that, use the comma operators

calculate(33, 47, 79);
125.

How ECMAScript is related to JavaScript?

Answer»

Library in JavaScript has a FUNCTION with a leading semicolon:

;(function ) { }

Let us see the different uses of including a leading semicolon:

  • Concatenate

The purpose to include semicolon is to safely concatenate several JS files into one.

  • Preceding Code

A leading semicolon protects from preceding code, which may have been improperly closed. A semicolon prevents this from occurring. If this is the case, then adding a semicolon will fix it.

  • Appending

The leading semicolon in immediately-invoked function expressions PREVENT errors when appending the file during CONCATENATION. This concat is to a file containing an expression improperly concluded with a semicolon

Let’s see an example. Let’s SAY we are concatenating two files with self-invoking functions:

  • Function ONE
(function(){...ONE...})()
  • Function TWO
(function(){...TWO...})()
  • Now concatenating it will give the following result:
(function(){...ONE...})() (function(){...TWO...})()
  • Function TWO can have a leading semicolon:
!(function(){...TWO...})()
  • Now after concatenation, you can see the semi-colon is VISIBLE:
(function(){...ONE...})();(function(){...TWO...})()

This helps in preventing any kind of errors when appending the file during concatenation.

126.

Remove element from an array in JavaScript

Answer»

Let’s say the following is our VARIABLE declaration of strings:

var val = "e\nx\na\nm\np\nl\ne";

To replace newlines, use the replace() method. The method replaces all occurrences of a CHARACTER in the given string. The replace(char1, char2)  has the following parameters:

  • char1: The character to be replaced
  • char2: The new character to be added in place of char1

Here the g flag on the regular EXPRESSION to perform a global match. The 2nd parameter is a space (“ “), which we want in place of new line (\n):

val = val.replace(/\n/g, " ");

The following is an example that replace newline with spaces:

<!DOCTYPE HTML> <html> <BODY> <script> var val = "e\nx\na\nm\np\nl\ne"; val = val.replace(/\n/g, " "); document.write("After removing new line: "+val); </script> </body> </html>

The output:

After removing new line: e x a m p l e
127.

instanceof operator in JavaScript

Answer»

ECMAScript INTRODUCED to standardize JavaScript. The implementations of ECMAScript include JavaScript, ActionScript, JScript, ETC. ECMAScript is a STANDARD for these. It is a trademark scripting language specification. 

JavaScript is a lightweight and interpreted programming language that introduced in 1995 as LiveScript.  Brendan Eich developed it and the language became an ECMA standard in 1997.

ECMAScript is a standard for JavaScript. The FIRST edition of ECMAScript came in 1997. JavaScript 2.0 conforms to Edition 5 of the ECMAScript standard. The 8th edition of ECMAScript is ECMAScript 2017, introduced in June 2017. The full form of ECMA is European Computer Manufacturers Association

The current VERSION is the 9th edition of ECMAScript, which came in the year 2018. The ECMA-262 Specification defined a standard version of the core JavaScript language.

128.

JavaScript has dynamic types. How?

Answer»

Remove a Single Element

To remove a single element from an array in JavaScript, the splice() method is used. With that you can also replace, and/or add elements in an array.

Let’s say we have the following array:

var myArr = ["Java", "PHP", "HTML", "jQuery", "ECLIPSE", "NetBeans"];

We are USING the splice() method to remove a single element by setting the location from where it start, and the number of elements to be removed. Here, we have set 1, therefore only a single element will get removed:

myArr.splice(3, 1);

The following is an EXAMPLE:

<html>    <head>       <title>JavaScript Splice Method</title>    </head>    <body>       <script>          var myArr = ["Java", "PHP", "HTML", "jQuery", "Eclipse", "NetBeans"];          document.write("<br />Array before removing an element = " + myArr );          rem = myArr.splice(3, 1);          document.write("<br />Removed element = " + rem);          document.write("<br />Array after removing an element = " + myArr );       </script>    </body> </html>

The output: 

Array before removing an element = Java,PHP,HTML,jQuery,Eclipse,NetBeans Removed element = jQuery Array after removing an element = Java,PHP,HTML,Eclipse,NetBeans

Remove more than one element

To remove more than one element and in a range,  use the splice() method.

Let’s say we have the following array:

var myArr = ["Java", "PHP", "HTML", "jQuery", "Eclipse", "NetBeans"];

We are using the splice() method to remove more than one element by setting the location from where it starts, and the number of elements to be removed. Here, we have set 3, therefore three elements will get removed:

We are using the splice() method to remove more than one element by setting the location from where it starts, and the number of elements to be removed. Here, we have set 3, therefore three elements will get removed:

myArr.splice(2, 3);

In the following example, we are deleting 3 elements starting from the 3rd position:

<html>    <head>       <title>JavaScript Splice Method</title>    </head>    <body>       <script>          var myArr = ["Java", "PHP", "HTML", "jQuery", "Eclipse", "NetBeans"];          document.write("<br />Array before removing 3 elements = " + myArr );          // removing multiple elements          rem = myArr.splice(2, 3);          document.write("<br />Array after removing 3 elements = " + myArr );       </script>    </body> </html>

The output displays the array after removing 3 elements:

Array before removing 3 elements = Java,PHP,HTML,jQuery,Eclipse,NetBeans Array after removing 3 elements = Java,PHP,NetBeans
129.

What are events in JavaScript?

Answer»

If you want to check the type of an object at runtime, then use the instanceof operator. The RESULT is a boolean.

Check for Array

Let’s say we are checking if a VARIABLE is an array or not using instanceof operator. The syntax:

variable_name instanceof Array

The following is our example and we are checking whether array exists or not:

 <html>    <body>         <script>         var DEPARTMENT = [ "FINANCE", "Operations", "Marketing", "HR" ];         if (department instanceof Array) {           alert('This is an Array!');         } else {           alert('This is not an array!');         }       </script>    </body> </html>

The output displays that array exists SINCE the if condition is true:

Check for Object using instanceof

To check for an object, use the instanceof operator, the following is the example:

<html>    <body>         <script>         var myObj = {};         if (myObj instanceof Object) {           alert('This is an object!');         } else {           alert('This is not an object!');         }       </script>    </body> </html>

The output displays ‘this is an object!’ in an alert box, since the if condition is true: 

130.

How to work with external JavaScript file?

Answer»

In JavaScript, you can use the same variable to hold different data types. This is why it is called that JavaScript has dynamic types.

It is not required to specify the type of variable in JavaScript. For example, the following is a variable, which is a number:

var val = 10;

Now, the same variable is a String:

var val = “BINGO”;

Now, you can also set it as a Number with decimal:

var val = 3.6;

Let us see them in an example to understand the dynamic types wherein we are showing the same variable can easily hold different types:

<!DOCTYPE html&GT; <html> <BODY> <H2>Dynamic Types</h2> <p id="myid"></p> <script> var a;         // a is UNDEFINED a = "Bingo";   // a is a String a = 10;        // a is a Number a = 3.6;       // a is a Number with Decimal document.getElementById("myid").innerHTML = a; </script> </body> </html>

The output:

In the above example, we have set different types for the same variable “a”:

var a;         // a is undefined a = "Bingo";   // a is a String a = 10;        // a is a Number a = 3.6;       // a is a Number with Decimal
131.

Empty an array in JavaScript

Answer»

Events handle JavaScript's interaction with HTML. Events can be related to a button being click or a web page loaded. Resizing a window also comes under event.

The following are the events. A function in JavaScript gets executed against the event:

Events
Triggers
onblur
When the window loses focus
onchange
When an element change.
onclick
On a mouse click
ondblclick
On a mouse double-click
ondrag
When an element is dragged
ondragen
At the end of a drag operation
ondragenter
When an element has been dragged to a valid drop target
ondragleave
When an element is being dragged over a valid drop target
ondragover
At the START of a drag operation
ondragstart
At the start of a drag operation
ondrop
Dragged element is being dropped
ondurationchange
When the length of the MEDIA is changed
onerror
When an error occurs
oninput
When an element gets user input
oninvalid
When an element is invalid
onkeydown
When a key is PRESSED
onkeypress
When a key is pressed and released
onkeyup
When a key is released
onmousedown
Triggers when a mouse button is pressed
onmousemove
Triggers when the mouse pointer moves
onmouseout
Triggers when the mouse pointer moves out of an element
onmouseover
Triggers when the mouse pointer moves over an element
onmouseup
Triggers when a mouse button is released
onmousewheel
Triggers when the mouse wheel is being rotated

Let us see an example of onclick event in JavaScript wherein the event gets triggered when left button of the mouse is clicked:

<html>    <head>       <script>          <!--             function show() {                alert("This is a message!")             }          //-->       </script>    </head>    <body>       <p>Click the below button:</p>       <form>          <input type="button" onclick="show()" value="Display" />       </form>    </body> </html>

The output:

Event gets triggered when you click on the button “Display” to agenerate the following alert:

Let us see another example wherein we are displaying the current date and TIME on click of a button:

<!DOCTYPE html> <html> <body> <button onclick="document.getElementById('myid').innerHTML=Date()">Time</button> <h2 id="myid"></h2> </body> </html>

The following output generates on the click of a button that we created in the example above:

132.

How to create an object in JavaScript?

Answer»

Using the <scrip>t TAG you can store the JavaScript code in an external .js extension file. The tag with the “src” attribute ALLOWS you to include this js file in your HTML.

If you are using the same JavaScript code in ALMOST every page, then it’s a good PRACTICE to create an external JS file and include it in HTML of every page. This enhances the loading time.

Here’s how you can create external JavaScript file with the extension .js. After creating, add it to the HTML file in the script tag. The ”src” attribute is used to include the external JavaScript file in your HTML:

<script src="myfile.js" ></script>

Let’s say the following is the content of our external JS file “myfile.js”:

function show () {      ALERT("Learning is fun!");   }

The following is our HTML file, wherein we will include the external file “myfile.js”:

<html>    <body>        <form>         <input type="button" value="Click" onclick="show()"/>          </form>       <script src="show.js">       </script>    </body> </html>

On running the above “myfile.js” file, the following is visible. Press the button “Click”:

On clicking above, the following alert is visible which we added in the external file by creating a JavaScript function:

133.

Is JavaScript case-sensitive?

Answer»

The array VARIABLE is to be set empty if you want to empty an array.

Let’s SAY we have the following array:

var myArr = ["shirt", "trousers", "WATCH"];

To empty the above array, just set it to empty:

myArr = [];

Here we converting our array to empty array:

<html>    <head>       <title>Empty Array in JAVASCRIPT</title>       <script>          var myArr = ["shirt", "trousers", "watch"];          document.write("<BR />Array: " + myArr );          // set array to empty          myArr = [];          document.write("<br />New array (Empty now): " + myArr );       </script>    </head>    <body>    </body> </html>

The output:

Array: shirt,trousers,watch New array (Empty now):
134.

Role of === operator in JavaScript

Answer»

LET’s see the following two ways with which you can create an object in JAVASCRIPT:

  • Object creation with constructor METHOD
  • Object creation with Object Literal

Let us understand them one by one:

Object creation with constructor method

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>

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";

Object creation with Object Literal

An object can also be created in JavaScript using object literal as shown below:

var department = {   id: 11,   name : "Finance",   Location     : "North" };

We can write it as:

var department = { id: 11, name : "Finance", Location     : "North"};

Let us see another example:

<!DOCTYPE html> <html> <body> <h2>Department Details</h2> <p id="test"></p> <script> var department = { id: 11, name : "Finance", Location : "North"}; document.getElementById("test").innerHTML = department.name + " Department is in " + department.Location + " location."; </script> </body> </html>

The output: 

135.

What are the limitations of JavaScript?

Answer»

Yes, JavaScript is case-sensitive. Therefore, the following identifiers are DIFFERENT:

Knowledge KNOWLEDGE

The case-sensitivity feature remains the same for variables, function names, and any other identifiers. The consistent capitalization of LETTERS should be considered. For example, “for loop” should be written as “for”, not “FOR” or “For”.

Let us see an example wherein we have three variables with different case. All of these 3 variables are considered different:

<!DOCTYPE html> <html> <body> <h3>Popular Programming Languages</h3> <p id="test"></p> <script>  var language, LANGUAGE, Language;  language = "C#";  LANGUAGE = "Java";  Language = "Python";  document.getElementById("test").innerHTML = LANGUAGE; </script> </body> </html>

The OUTPUT:

136.

Java vs JavaScript

Answer»

The === is a comparison operator in JavaScript. It checks for the value as well type.

Same value and type

Let US SEE an EXAMPLE wherein we have assigned a numeric value to variable “val1” and checked it with a numeric value for EQUALITY (type and value):

<!DOCTYPE html> <html> <body> <h2>JavaScript === operator</h2> <p id="test"></p> <script> var val1 = 20; document.getElementById("test").innerHTML = (val1 === 20); </script> </body> </html>

The output displays that the variable has the same value and type. Therefore, TRUE is returned as output:

Same Value and Different Type

Let us see an example wherein we have assigned a numeric value to variable “val2” and checked it with a value of another type for equality (type and value):

<!DOCTYPE html> <html> <body> <h2>JavaScript === operator</h2> <p id="test"></p> <script> var val2 = 5; document.getElementById("test").innerHTML = (val2 === "5"); </script> </body> </html>

The output displays that the variable has same value but different type. Therefore, false is returned as output:

137.

Need of JavaScript

Answer»

JavaScript is a lightweight and interpreted scripted/ programming language introduced in by Brendan Eic. It has a lot of advantages like validation, animation, interactions, ETC. However, like any other programming language, it has some limitations too like you cannot WRITE files on server, browser compatibility issues, etc.

Let us see the limitations of JavaScript one by one:

Writing files on server

JavaScript cannot DIRECTLY write files on server. However, they can do this USING server-side script.

Disable JavaScript

Due to security reasons, every web browser provides an option to disable JavaScript.

The screenshot displays how to ENABLE or disable JavaScript:

  • Networking

It cannot be used for Networking applications.

  • Browser Compatibility

Applications may behave differently in different web browsers. To support all modern browsers, you need to write cross browser codes.

  • Security

Since the code executes on client’s computer, the chances are high for vulnerability and can be exploited for malicious purposes

  • Databases

JavaScript cannot access databases. You need AJAX and a server-side script for this.

Note: New developments in JavaScript introduced accessing client-side databases.

138.

What are Prototypes and how do we use them in JavaScript?

Answer»
  • JavaScript

JavaScript is a LIGHTWEIGHT and interpreted PROGRAMMING language that introduced in 1995 as LiveScript.  Brendan Eich developed it and the language became an ECMA standard in 1997.

  • Java

Java is a programming language developed by James Gosling. It is a language used in my desktop application, web applications, games, etc. Java is a platform INDEPENDENT object-oriented language.

The FOLLOWING is the DIFFERENCE between Java and JavaScript:

Basis
JavaJavaScript
DefinitionJava is a programming language developed by James Gosling. It is a language used in my desktop application, web applications, games, etc. Java is a platform independent object-oriented language.
JavaScript is a lightweight and interpreted programming language that introduced in 1995 as LiveScript.  Brendan Eich developed it and the language became an ECMA standard in 1997.
OOPJava is an OOP programming language
JavaScript is an OOP scripting language.
Running on BrowserJava creates applications that run in a virtual machine or browser
JavaScript code is run on a browser only.
Compiled vs. InterpretedJava Program is compiled.
JavaScript scripts are Interpreted.
Type CheckingJava has static type checking. The type of a variable is checked at compile-time.
JavaScript has dynamic typing. The type safety is verified at runtime.
Type of VariableThe type of variable should be specified.
It is not required to specify the type of variable.
139.

How to make variables private in Constructor functions?

Answer»

JavaScript is a lightweight and interpreted programming language that introduced in 1995 as LiveScript.  Brendan Eich developed it and the language BECAME an ECMA standard in 1997.

Let us now see why JavaScript is needed:

  • Less load on Server

You can VALIDATE input before sending it to the server. This leads to faster loading on the server.

  • Easier Implementation

Executing JavaScript code is not a tedious task. Add your code in an HTML document. When user requests this HTML page with JavaScript in it, the script is sent to the web browser.

  • Loading

JavaScript can load CONTENT into the document whenever you need it. And while doing that, you don’t need to reload the complete page.

  • Animate

Use JavaScript to show and hide information on click. Move DOM elements around the page based on some PATTERN using JavaScript.

  • Text-Animation

With JavaScript, you can also animate text.

  • Game Development

You can develop games as well if you have advanced knowledge of JavaScript and its practical implementation.

  • Validation

JavaScript validates form data on the client's computer. And this task is accomplished before sending the data to the server.

140.

What are constructor functions in JavaScript?

Answer»

In JavaScript everything is an Object. So whenever we create an FUNCTION, there is a one object which is created for that function. But actually there is another object which is created which is known as the Prototype object.
Now to access the Prototype object we have a reference on the function object also known as prototype. Notice the small “p”.

When we create an instance of the function with the NEW keyword interesting THINGS happens. It create something known as __proto__. This is created by the JavaScript engine for every function call using the new keyword.

Now, let’s LOOK how to create an function using prototype and the benefit of it. The below code have two function haveFun and drinkBreak. The function haveFun is an normal function inside the Constructor function. The function drinkBreak is created outside and added to the Prototype Object using it’s reference prototype.

Both the function seems to be doing the same thing, then what’s the benefit.
The benefit of declaring function using prototype is that it’s created once in the Prototype object. So, now whenever we create a new instance of the Constructor function the function is not created again. As in the below screenshot, you can see that emp1 and emp2 both have name and haveFun. But the drinkBreak is inside the __proto__, which is a reference to Prototype object.

141.

How do we handle errors in async-await function?

Answer»

Let US first consider the below code for NORMAL Constructor function. Here we can directly access the variable “name” by person.name.
 Now, this might be not desirable at many places and in Traditional languages like C++ and JAVA, this is  solved by the having “private” variables in class and then having “Getters” and “SETTERS” to access them. 

Now, we implement the same in JavaScript using Closures. We have two closure functions setName and getName which are BASICALLY “setters” and “getters”. Now, the variable _name is private and cannot be accessed outside the function by person._name and we can access it only by person.getName() 

142.

Explain Promise.all with async-await?

Answer»

Constructor functions are the equivalent of classes of traditional programming languages like C++ and Java. Sometimes people will refer to them as reference types, classes, data types, or simply constructors.  

If you aren’t familiar with classes, they are a construct that allows you to specify some properties and behaviours (functions), and multiple objects can be created with those properties and behaviours.  

A common analogy you’ll often hear is, a class is an architecture’s map and an object is a house created using it. Multiple houses can be created from a single map, as multiple objects can be created from a class.

Let’s start with creating a simple function using object to create employee objects.

 Now consider the line var newObj = {} and return newObj. They will be same in every function which we create. So, JavaScript GIVES us a special type of function known as Constructor function to create them.

We will refactor the above to USE Constructor function. LOOK at the below code.

We are adding the keyword NEW to create the object. It basically takes care of the creation and returning of the newObj. But gives this a new name this.
Note, that we don’t need to put those two line in our code and automatically put by JavaScript engine.

We can also add methods to a Constructor function and then it can be CALLED with any object created with new keyword.

143.

Explain async await in JavaScript?

Answer»

 In Promises we handle any error or REJECT in the .catch block. LET’s look at the below example, where we are sending reject() from cleanroom(). So, now the error will be CAUGHT by the .catch block and then we are displaying the same in console log.

 

Now, when we refactor the above code using async-await, we don’t have any .catch block. So, we take help from the good old try…catch block AVAILABLE in JAVASCRIPT

144.

Explain classes in ES6?

Answer»

The Promise.all  method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects.

Let’s refactor the ASYNC await code from PREVIOUS question to use Promise.all. NOTICE, that we are also using array destructuring at line 6, to RECEIVE all the values returned by the promise.

 We should use Promise.all in only cases like above, where the result of ONE Promise is not dependent on other promise.

145.

Explain Destructuring in ES6?

Answer»

ASYNC await help in ALLOWING us to WRITE completely synchronous-looking code while performing asynchronous tasks behind the scenes.

Async await are basically promises under the hood. But they have made the code for promises very easier to implement. If promises had simplified the code for callbacks, then async await have simplified the code for promises.

Let’s first check a nested promise example. Here we have three functions which return promises- cleanRoom, removeGarbage and winPizza. Now, when the cleanRoom function is run and resolve is returned from the promise, then the immediate .then block will be run . In the .then we are returning the next removeGarbage and in its .then we are returning the winPizza. We are passing the message from one function to other, so it will be appended.

We will refactored the code with async await. Here, INSTEAD of three functions we have one function cleaningTheRoom, which have a keyword “async” infront of it. It means that the function will have await statement(s). In the “await” we can have the value returned by a Promise stored in a variable. This type of code is much more CLEANER then promise.

146.

What are spread operators and rest parameters?

Answer»

ES6 introduced the keyword class in JavaScript. But class in JavaScript is still different than those USED in Object ORIENTED Programming LANGUAGES like C++ and Java. The ES6 classes are nothing but synthetic sugar for constructor function and internally behaves exactly the same.

Consider the below example of Constructor function. Here we have a constructor function named “Mammal”. It have two properties of legs and name. It ALSO have a function called walk(), which uses the legs and name property. We are creating an INSTANCE called person, which then is calling the walk function.

 The same can be written with ES6 classes with constructor, but it is exactly the same.

147.

What are default parameters in ES6?

Answer»

 Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct VARIABLES. You can also HANDLE nested structure by using nested destructuring syntax.

Object Destructuring
Consider the old way to assign variable to Object properties WITHOUT destructuring.

Now we will refactor the above using “Object Destructuring”. Basically, you use an object literal on the left-hand-side of an assignment expression for object destructuring.

Nested Object Destructuring
If there is nested object as in below case, we can destructure it by adding it’s value to ANOTHER object syntax 

Array Destructuring
Let’s FIRST see how to do it without destructuring. Here we use the index to assign the variables.

 Array destructuring is similar to object destructuring, but here instead of keys you assign any variable.

Skipping Items
It is possible to skip items in array destructuring by omitting items with comma(,).

148.

What are template Strings in ES6?

Answer»

Spread operators(…) were introduced in JAVASCRIPT in ES6 version. Just like plus(+) and MINUS(-) are operators, spread(…) is also an OPERATOR in JavaScript. Basically Spread operator spreads on demand. 

When you pass arguments to a function using Spread operators they are called Rest parameters.

Consider the below example for arrFunc. We can pass any number of arguments to a function and use the …arr to get it. Now inside the function the arr gets converted into and array. This functionality is quite similar to arguments object.

Now see the restFunc, here we are using rest parameter to get the remaining of the arguments. We can get argument a, b, c and then the rest is converted into array. 

The Spread operator can be use separately from function parameter and have some very useful use in array manipulation. They can now also be used with Objects.

Consider that we want to copy an array to other array. Now as you can see in the problem that when we assign variable y to x, we are referencing it and any changes to y will reflect in x. 

In the FIRST solution, we use the new JavaScript method Object.assign() to copy all contents of “a” to an empty array and then assigning it to “b”.

But the better and simple solution is with Spread operator where we spread the array “c”, and take its content in an array.

Another use it that if we pass an array to build in functions, which expects normal arguments. Consider the below examples. 

We can also use Spread operator in Objects. So, by it we can do both clone and merge as SHOWN in below example. Notice, that in mergedObj foo is “baz” as Object cannot have duplicate keys.

149.

Explain Higher Order Function in JavaScript?

Answer»

Default parameters are the parameters, which are used if we don’t pass the value to that argument in a function while CALLING it.

Earlier to ES6, it was a BIT difficult to handle a situation like this. In the below example if user didn’t SUPPLIED a value to argument , we check inside the function “add” if “a” has a value or assign 0 to it. Same is done for “b”. 

So, now we can handle all THREE situation successfully like when we pass no arguments, or pass only value of ‘a’ or pass only value of ‘b’.

The same can be done in ES6 by changing the parameter to contain the default value. Re-writing the above with ES6 default parameters.

150.

Explain recursion in JavaScript?

Answer»

Template STRINGS are also KNOWN as Template Literals. They are the new WAY to write Strings in JavaScript and been introduced in ES6. We can now write Stings using back-ticks(``), which have a special way to interpolate variables.

They are very useful in Expression interpolation and Multi-LINE strings. Although they don’t add any new feature to JavaScript, but they are a better visual way to write strings.

Expression interpolation
The old JavaScript way is quite CUMBERSOME and we have to use many + operators to concatenate Strings, whereas with back-ticks we interpolate variable name using ${}.

Multi-line strings
The old way to have multiline strings is to have a newline(\n) inserted after where we want the next line.
Template strings provides a new way. You just go to the next line and the text will be displayed in next line.