Polaris JavaScript Most Frequently Asked Latest Interview Questions Answers
What will the code below output to the console and why?
var arr1 = "john".split('');
var arr2 = arr1.reverse();
var arr3 = "jones".split('');
arr2.push(arr3);
console.log("array 1: length=" + arr1.length + " last=" + arr1.slice(-1));
console.log("array 2: length=" + arr2.length + " last=" + arr2.slice(-1));
The logged output will be:
"array 1: length=5 last=j,o,n,e,s"
"array 2: length=5 last=j,o,n,e,s"
arr1 and arr2 are the same (i.e. ['n','h','o','j', ['j','o','n','e','s'] ]) after the above code is executed for the following reasons:
Calling an array object’s reverse() method doesn’t only return the array in reverse order, it also reverses the order of the array itself (i.e., in this case, arr1).
The reverse() method returns a reference to the array itself (i.e., in this case, arr1). As a result, arr2 is simply a reference to (rather than a copy of) arr1. Therefore, when anything is done to arr2 (i.e., when we invoke arr2.push(arr3);), arr1 will be affected as well since arr1 and arr2 are simply references to the same object.
And a couple of side points here that can sometimes trip someone up in answering this question:
Passing an array to the push() method of another array pushes that entire array as a single element onto the end of the array. As a result, the statement arr2.push(arr3); adds arr3 in its entirety as a single element to the end of arr2 (i.e., it does not concatenate the two arrays, that’s what the concat() method is for).
Like Python, JavaScript honors negative subscripts in calls to array methods like slice() as a way of referencing elements at the end of the array; e.g., a subscript of -1 indicates the last element in the array, and so on.
What will the code below output to the console and why ?
console.log(1 + "2" + "2");
console.log(1 + +"2" + "2");
console.log(1 + -"1" + "2");
console.log(+"1" + "1" + "2");
console.log( "A" - "B" + "2");
console.log( "A" - "B" + 2);
The above code will output the following to the console:
"122"
"32"
"02"
"112"
"NaN2"
NaN
Here’s why…
The fundamental issue here is that JavaScript (ECMAScript) is a loosely typed language and it performs automatic type conversion on values to accommodate the operation being performed. Let’s see how this plays out with each of the above examples.
Example 1: 1 + "2" + "2" Outputs: "122" Explanation: The first operation to be performed in 1 + "2". Since one of the operands ("2") is a string, JavaScript assumes it needs to perform string concatenation and therefore converts the type of 1 to "1", 1 + "2" yields "12". Then, "12" + "2" yields "122".
Example 2: 1 + +"2" + "2" Outputs: "32" Explanation: Based on order of operations, the first operation to be performed is +"2" (the extra + before the first "2" is treated as a unary operator). Thus, JavaScript converts the type of "2" to numeric and then applies the unary + sign to it (i.e., treats it as a positive number). As a result, the next operation is now 1 + 2 which of course yields 3. But then, we have an operation between a number and a string (i.e., 3 and "2"), so once again JavaScript converts the type of the numeric value to a string and performs string concatenation, yielding "32".
Example 3: 1 + -"1" + "2" Outputs: "02" Explanation: The explanation here is identical to the prior example, except the unary operator is - rather than +. So "1" becomes 1, which then becomes -1 when the - is applied, which is then added to 1 yielding 0, which is then converted to a string and concatenated with the final "2" operand, yielding "02".
Example 4: +"1" + "1" + "2" Outputs: "112" Explanation: Although the first "1" operand is typecast to a numeric value based on the unary + operator that precedes it, it is then immediately converted back to a string when it is concatenated with the second "1" operand, which is then concatenated with the final "2" operand, yielding the string "112".
Example 5: "A" - "B" + "2" Outputs: "NaN2" Explanation: Since the - operator can not be applied to strings, and since neither "A" nor "B" can be converted to numeric values, "A" - "B" yields NaN which is then concatenated with the string "2" to yield “NaN2”.
Example 6: "A" - "B" + 2 Outputs: NaN Explanation: As exlained in the previous example, "A" - "B" yields NaN. But any operator applied to NaN with any other numeric operand will still yield NaN.
The following recursive code will cause a stack overflow if the array list is too large. How can you fix this and still retain the recursive pattern?
var list = readHugeList();
var nextListItem = function() {
var item = list.pop();
if (item) {
// process the list item...
nextListItem();
}
};
The potential stack overflow can be avoided by modifying the nextListItem function as follows:
var list = readHugeList();
var nextListItem = function() {
var item = list.pop();
if (item) {
// process the list item...
setTimeout( nextListItem, 0);
}
};
The stack overflow is eliminated because the event loop handles the recursion, not the call stack. When nextListItem runs, if item is not null, the timeout function (nextListItem) is pushed to the event queue and the function exits, thereby leaving the call stack clear. When the event queue runs its timed-out event, the next item is processed and a timer is set to again invoke nextListItem. Accordingly, the method is processed from start to finish without a direct recursive call, so the call stack remains clear, regardless of the number of iterations.
What is Ajax?
Ajax is abbreviated as Asynchronous Javascript and XML. It is new technique used to create better, faster and more interactive web systems or applications. Ajax uses asynchronous data transfer between the Browser and the web server.
This technique is used to make internet faster and user friendly. It is not a programming language.
What are the disadvantages of Ajax?
Following are the disadvantages of Ajax:
AJAX is dependent on Javascript. If there is some Javascript problem with the browser or in the OS, Ajax will not support
Ajax can be problematic in Search engines as it uses Javascript for most of its parts.
Source code written in AJAX is easily human readable. There will be some security issues in Ajax.
Debugging is difficult
Increases size of the requests
Slow and unreliable network connection.
Problem with browser back button when using AJAX enabled pages.
What is the difference between innerHTML and innerText?
innerHTML will process an HTML tag if found in a string, whereas innerText will not. For Example document.querySelector('p').innerHTML='one <br> two' gives the output one and two in two lines as <br> in html is a new line. Whereas document.querySelector('p').innerText='one <br> two' gives the output of the text as it is in one line.
What is the difference between textContent and innerText?
Let us have a paragraph element and a span element in it as a child element.
<p>some text and a <span style="visibility: hidden">span tag hidden <\span>in it</p>
Now, if the following two steps would result in the following-
console.log(document.querySelector('p').textContent); gives some text and a span tag hidden in it.
console.log(document.querySelector('p').innerText); gives some text and a in it.
What is the difference between HTMLCollection and NodeList?
The functions querySelectorAll() returns NodeList in which the forEach can be used directly to traverse the elements. Whereas, the getElementsByClassName() or getElementsByTagName() returns an HTMLCollection, which does not have a forEach by default.
How can an HTMLCollection be traversed?
The HTMLCollection by default does not have forEach, it needs to be converted into an array (eleName = Array.from(eleName)) and then the traversal is possible using forEach.
What is the difference between childNode and children?
A childNode, when used returns a NodeList. Whereas, children, when used; returns an HTMLCollection.
What is the difference between firstChild and firstElementChild?
A firstChild when used returns the first node. It could be an HTML element or even a space, or a new line. Whereas, firstElementChild, when used returns the first HTML element only.
Name the two functions that are used to create an HTML element dynamically.
To generate an html element dynamically, we need to use two functions:
(i) var ele = createElement ('elementName'), which creates an element and
(ii) parentElement.appendChild(ele)
What is the difference between remove() and removeChild()?
The remove() function just removes the element. Whereas, the removeChild() returns the deleted element.
List out the Mouse Events.
There are altogether 9 mouse events. Here is the list:
1. click: A single click
2. dblclick: A double click
3. mousedown: When the mouse button is clicked down.
4. mouseup: When the mouse button is released up.
5. mouseenter: When the mouse cursor enters an external element.
6. mouseleave: When the mouse cursor leaves an external element.
7. mouseover: When the mouse cursor enters an internal and external element.
8. mouseout: When the mouse cursor leaves an internal and external element.
9. mousemove: When the mouse cursor is moved.
What is the use of history object?
By using the history object you can change or switch back to history pages or forward from current page to another page.
What is an Event Bubbling in Javascript?
When an event is fired on an HTML element, the execution starts from that event and goes to its parent element. From there, the execution passes to its parent element and so on till the body element.
What does window.print() do in Javascript?
The print() function from window object prints the current web page when executed.
How can a Javascript code redirect the user to a different page?
The window.location is assigned a value; i.e., a web link. On its execution, the Javascript code can redirect the user to the mentioned web link.
What is update panel?
Update panel is a server control used to update the specified portion of a web page. Script Manager needs to be used whenever update panel is used. Using update panel, user cannot handle outside controls.
Which are the two methods used for cross domain Ajax calls?
There are two methods used to transfer data between the two more more security domains:
CORS – Cross Origin Resource Sharing and it works with the HTTP web browsers
JSONP – JSON with Padding which works with the HTTP GET and on legacy browsers
What are all the technologies used by Ajax?
AJAX uses following technologies:
JavaScript
XMLHttpRequest
Document Object Model (DOM)
Extensible HTML (XHTML)
Cascading Style Sheets (CSS)
What are all the features of Ajax?
Following are the features of Ajax and they are as follows:
Live data binding
Client-side template rendering
Declarative instantiation of client components
Observer pattern on JavaScript objects and arrays
Invoking ADO.NET data services and data contexts
DataView control
What are Ajax applications?
Browser based applications and platform independent applications are used by Ajax.
How many types of triggers are present in update panel?
There are two types of triggers used in update panel:
PostBackTrigger – This works as full postback and it cannot work asynchronously
AsyncPostBackTrigger – Partial post back asynchronously
What are all the controls of Ajax?
Following are the controls of Ajax:
ScriptManager
ScriptManagerProxy
UpdatePanel
UpdateProgress
Timer
What is the name of the DLL that contains Ajax control tool kit?
Ajaxcontroltoolkit.dll is the DLL used for Ajax control tool kit and it can be downloaded from the internet. It can be added in the tool box or copied directly in the bin folder.
What role of #&& in querystring?
# is treated as fragment delimiter to delimit the history state and && precedes is used to check on the information in the query string.
How to control the duration of an Ajax request?
AsyncPostBackTimeout property is used to control the duration of Ajax request. Deafult value of this property is 90 seconds.
Example –
<asp:ScriptManager runat=”server” id=”sample” AsyncPostBackTimeout=”40”/>
1
<asp:ScriptManager runat=”server” id=”sample” AsyncPostBackTimeout=”40”/>
What will the code below output to the console and why?
var arr1 = "john".split('');
var arr2 = arr1.reverse();
var arr3 = "jones".split('');
arr2.push(arr3);
console.log("array 1: length=" + arr1.length + " last=" + arr1.slice(-1));
console.log("array 2: length=" + arr2.length + " last=" + arr2.slice(-1));
The logged output will be:
"array 1: length=5 last=j,o,n,e,s"
"array 2: length=5 last=j,o,n,e,s"
arr1 and arr2 are the same (i.e. ['n','h','o','j', ['j','o','n','e','s'] ]) after the above code is executed for the following reasons:
Calling an array object’s reverse() method doesn’t only return the array in reverse order, it also reverses the order of the array itself (i.e., in this case, arr1).
The reverse() method returns a reference to the array itself (i.e., in this case, arr1). As a result, arr2 is simply a reference to (rather than a copy of) arr1. Therefore, when anything is done to arr2 (i.e., when we invoke arr2.push(arr3);), arr1 will be affected as well since arr1 and arr2 are simply references to the same object.
And a couple of side points here that can sometimes trip someone up in answering this question:
Passing an array to the push() method of another array pushes that entire array as a single element onto the end of the array. As a result, the statement arr2.push(arr3); adds arr3 in its entirety as a single element to the end of arr2 (i.e., it does not concatenate the two arrays, that’s what the concat() method is for).
Like Python, JavaScript honors negative subscripts in calls to array methods like slice() as a way of referencing elements at the end of the array; e.g., a subscript of -1 indicates the last element in the array, and so on.
Polaris JavaScript Most Frequently Asked Latest Interview Questions Answers |
What will the code below output to the console and why ?
console.log(1 + "2" + "2");
console.log(1 + +"2" + "2");
console.log(1 + -"1" + "2");
console.log(+"1" + "1" + "2");
console.log( "A" - "B" + "2");
console.log( "A" - "B" + 2);
The above code will output the following to the console:
"122"
"32"
"02"
"112"
"NaN2"
NaN
Here’s why…
The fundamental issue here is that JavaScript (ECMAScript) is a loosely typed language and it performs automatic type conversion on values to accommodate the operation being performed. Let’s see how this plays out with each of the above examples.
Example 1: 1 + "2" + "2" Outputs: "122" Explanation: The first operation to be performed in 1 + "2". Since one of the operands ("2") is a string, JavaScript assumes it needs to perform string concatenation and therefore converts the type of 1 to "1", 1 + "2" yields "12". Then, "12" + "2" yields "122".
Example 2: 1 + +"2" + "2" Outputs: "32" Explanation: Based on order of operations, the first operation to be performed is +"2" (the extra + before the first "2" is treated as a unary operator). Thus, JavaScript converts the type of "2" to numeric and then applies the unary + sign to it (i.e., treats it as a positive number). As a result, the next operation is now 1 + 2 which of course yields 3. But then, we have an operation between a number and a string (i.e., 3 and "2"), so once again JavaScript converts the type of the numeric value to a string and performs string concatenation, yielding "32".
Example 3: 1 + -"1" + "2" Outputs: "02" Explanation: The explanation here is identical to the prior example, except the unary operator is - rather than +. So "1" becomes 1, which then becomes -1 when the - is applied, which is then added to 1 yielding 0, which is then converted to a string and concatenated with the final "2" operand, yielding "02".
Example 4: +"1" + "1" + "2" Outputs: "112" Explanation: Although the first "1" operand is typecast to a numeric value based on the unary + operator that precedes it, it is then immediately converted back to a string when it is concatenated with the second "1" operand, which is then concatenated with the final "2" operand, yielding the string "112".
Example 5: "A" - "B" + "2" Outputs: "NaN2" Explanation: Since the - operator can not be applied to strings, and since neither "A" nor "B" can be converted to numeric values, "A" - "B" yields NaN which is then concatenated with the string "2" to yield “NaN2”.
Example 6: "A" - "B" + 2 Outputs: NaN Explanation: As exlained in the previous example, "A" - "B" yields NaN. But any operator applied to NaN with any other numeric operand will still yield NaN.
The following recursive code will cause a stack overflow if the array list is too large. How can you fix this and still retain the recursive pattern?
var list = readHugeList();
var nextListItem = function() {
var item = list.pop();
if (item) {
// process the list item...
nextListItem();
}
};
The potential stack overflow can be avoided by modifying the nextListItem function as follows:
var list = readHugeList();
var nextListItem = function() {
var item = list.pop();
if (item) {
// process the list item...
setTimeout( nextListItem, 0);
}
};
The stack overflow is eliminated because the event loop handles the recursion, not the call stack. When nextListItem runs, if item is not null, the timeout function (nextListItem) is pushed to the event queue and the function exits, thereby leaving the call stack clear. When the event queue runs its timed-out event, the next item is processed and a timer is set to again invoke nextListItem. Accordingly, the method is processed from start to finish without a direct recursive call, so the call stack remains clear, regardless of the number of iterations.
What is Ajax?
Ajax is abbreviated as Asynchronous Javascript and XML. It is new technique used to create better, faster and more interactive web systems or applications. Ajax uses asynchronous data transfer between the Browser and the web server.
This technique is used to make internet faster and user friendly. It is not a programming language.
What are the disadvantages of Ajax?
Following are the disadvantages of Ajax:
AJAX is dependent on Javascript. If there is some Javascript problem with the browser or in the OS, Ajax will not support
Ajax can be problematic in Search engines as it uses Javascript for most of its parts.
Source code written in AJAX is easily human readable. There will be some security issues in Ajax.
Debugging is difficult
Increases size of the requests
Slow and unreliable network connection.
Problem with browser back button when using AJAX enabled pages.
What is the difference between innerHTML and innerText?
innerHTML will process an HTML tag if found in a string, whereas innerText will not. For Example document.querySelector('p').innerHTML='one <br> two' gives the output one and two in two lines as <br> in html is a new line. Whereas document.querySelector('p').innerText='one <br> two' gives the output of the text as it is in one line.
What is the difference between textContent and innerText?
Let us have a paragraph element and a span element in it as a child element.
<p>some text and a <span style="visibility: hidden">span tag hidden <\span>in it</p>
Now, if the following two steps would result in the following-
console.log(document.querySelector('p').textContent); gives some text and a span tag hidden in it.
console.log(document.querySelector('p').innerText); gives some text and a in it.
What is the difference between HTMLCollection and NodeList?
The functions querySelectorAll() returns NodeList in which the forEach can be used directly to traverse the elements. Whereas, the getElementsByClassName() or getElementsByTagName() returns an HTMLCollection, which does not have a forEach by default.
How can an HTMLCollection be traversed?
The HTMLCollection by default does not have forEach, it needs to be converted into an array (eleName = Array.from(eleName)) and then the traversal is possible using forEach.
What is the difference between childNode and children?
A childNode, when used returns a NodeList. Whereas, children, when used; returns an HTMLCollection.
What is the difference between firstChild and firstElementChild?
A firstChild when used returns the first node. It could be an HTML element or even a space, or a new line. Whereas, firstElementChild, when used returns the first HTML element only.
Name the two functions that are used to create an HTML element dynamically.
To generate an html element dynamically, we need to use two functions:
(i) var ele = createElement ('elementName'), which creates an element and
(ii) parentElement.appendChild(ele)
What is the difference between remove() and removeChild()?
The remove() function just removes the element. Whereas, the removeChild() returns the deleted element.
List out the Mouse Events.
There are altogether 9 mouse events. Here is the list:
1. click: A single click
2. dblclick: A double click
3. mousedown: When the mouse button is clicked down.
4. mouseup: When the mouse button is released up.
5. mouseenter: When the mouse cursor enters an external element.
6. mouseleave: When the mouse cursor leaves an external element.
7. mouseover: When the mouse cursor enters an internal and external element.
8. mouseout: When the mouse cursor leaves an internal and external element.
9. mousemove: When the mouse cursor is moved.
What is the use of history object?
By using the history object you can change or switch back to history pages or forward from current page to another page.
What is an Event Bubbling in Javascript?
When an event is fired on an HTML element, the execution starts from that event and goes to its parent element. From there, the execution passes to its parent element and so on till the body element.
What does window.print() do in Javascript?
The print() function from window object prints the current web page when executed.
How can a Javascript code redirect the user to a different page?
The window.location is assigned a value; i.e., a web link. On its execution, the Javascript code can redirect the user to the mentioned web link.
What is update panel?
Update panel is a server control used to update the specified portion of a web page. Script Manager needs to be used whenever update panel is used. Using update panel, user cannot handle outside controls.
Which are the two methods used for cross domain Ajax calls?
There are two methods used to transfer data between the two more more security domains:
CORS – Cross Origin Resource Sharing and it works with the HTTP web browsers
JSONP – JSON with Padding which works with the HTTP GET and on legacy browsers
What are all the technologies used by Ajax?
AJAX uses following technologies:
JavaScript
XMLHttpRequest
Document Object Model (DOM)
Extensible HTML (XHTML)
Cascading Style Sheets (CSS)
What are all the features of Ajax?
Following are the features of Ajax and they are as follows:
Live data binding
Client-side template rendering
Declarative instantiation of client components
Observer pattern on JavaScript objects and arrays
Invoking ADO.NET data services and data contexts
DataView control
What are Ajax applications?
Browser based applications and platform independent applications are used by Ajax.
How many types of triggers are present in update panel?
There are two types of triggers used in update panel:
PostBackTrigger – This works as full postback and it cannot work asynchronously
AsyncPostBackTrigger – Partial post back asynchronously
What are all the controls of Ajax?
Following are the controls of Ajax:
ScriptManager
ScriptManagerProxy
UpdatePanel
UpdateProgress
Timer
What is the name of the DLL that contains Ajax control tool kit?
Ajaxcontroltoolkit.dll is the DLL used for Ajax control tool kit and it can be downloaded from the internet. It can be added in the tool box or copied directly in the bin folder.
What role of #&& in querystring?
# is treated as fragment delimiter to delimit the history state and && precedes is used to check on the information in the query string.
How to control the duration of an Ajax request?
AsyncPostBackTimeout property is used to control the duration of Ajax request. Deafult value of this property is 90 seconds.
Example –
<asp:ScriptManager runat=”server” id=”sample” AsyncPostBackTimeout=”40”/>
1
<asp:ScriptManager runat=”server” id=”sample” AsyncPostBackTimeout=”40”/>
Post a Comment