Question 1: What is JavaScript?
Answer: JavaScript is a client-side scripting language that can be inserted into HTML pages and is understood by web browsers.
View detailed answer →Prepare Javascript interview questions for freshers and experienced candidates. This page includes important questions, answer previews, preparation guidance, related interview topics and cached content for faster page loading.
For better preparation, read each question carefully, understand the concept, prepare one real example, and connect your answer with your project or work experience.
Quick list of important Javascript interview questions. Detailed answer previews are available below.
Answer: JavaScript is a client-side scripting language that can be inserted into HTML pages and is understood by web browsers.
View detailed answer →Answer: java is a complete programming language. In contrast, JavaScript is a coded program that can be introduced to HTML pages. These two languages are not at all inter-dependent and are designed for the different intent. Java is an object – oriented programming (OOPS) or structured programming language like C++ or C whereas JavaScript is a client-side scripting language and it is said to be unstructured programming.
View detailed answer →Answer: Following are the JavaScript types: Number String Boolean Function Object Null Undefined
View detailed answer →Answer: isNan function returns true if the argument is not a number otherwise it is false.
View detailed answer →Answer: JavaScript is faster. JavaScript is a client-side language and thus it does not need the assistance of the web server to execute. On the other hand, ASP is a server-side language and hence is always slower than JavaScript.
View detailed answer →Answer: Negative Infinity is a number in JavaScript which can be derived by dividing negative number by zero.
View detailed answer →Answer: Breaking within a string statement can be done by the use of a backslash, ‘’, at the end of the first line Example: document.write("This is a program"); 1 document.write("This is a program"); And if you change to a new line when not within a string statement, then javaScript ignores break in line. Example: var x=1, y=2, z= x+y; 1 2 3 4 5 varx=1,y=2, z= x+y; The above code is perfectly fine, though not advisable as it hampers debugging.
View detailed answer →Answer: Netscape is the software company who developed JavaScript.
View detailed answer →Answer: Undeclared variables are those that do not exist in a program and are not declared. If the program tries to read the value of an undeclared variable, then a runtime error is encountered. Undefined variables are those that are declared in the program but have not been given any value. If the program tries to read the value of an undefined variable, an undefined value is returned.
View detailed answer →Answer: XHTML <html> <head> <title>t1</title> <script type="text/javascript"> function addNode() { var newP = document.createElement("p"); var textNode = document.createTextNode(" This is a new text node"); newP.appendChild(textNode); document.getElementById("firstP").appendChild(newP); } </script> </head> <body> <p id="firstP">firstP<p> </body> </html> 1 2 3 4 5 6 7 8 9 <html> <head><title>t1</title> <script type="text/javascript"> functionaddNode(){varnewP=document.createElement("p"); vartextNode=document.createTextNode(" This is a new text node");...
View detailed answer →Answer: Global variables are those that are available throughout the length of the code, that is, these have no scope. The var keyword is used to declare a local variable or object. If the var keyword is omitted, a global variable is declared. Example: // Declare a global globalVariable = “Test”; The problems that are faced by using global variables are the clash of variable names of local and global scope. Also, it is difficult to debug and test the code that relies on global variables.
View detailed answer →Answer: A prompt box is a box which allows the user to enter input by providing a text box. Label and box will be provided to enter the text or number.
View detailed answer →Answer: ‘This’ keyword is used to point at the current object in the code. For instance: If the code is presently at an object created by the help of the ‘new’ keyword, then ‘this’ keyword will point to the object being created.
View detailed answer →Answer: Timers are used to execute a piece of code at a set time or also to repeat the code in a given interval of time. This is done by using the functions setTimeout, setInterval and clearInterval. The setTimeout(function, delay) function is used to start a timer that calls a particular function after the mentioned delay. The setInterval(function, delay) function is used to repeatedly execute the given function in the mentioned delay and only halts when cancelled. The clearInterval(id) function instructs the timer to stop. Timers are operated within a single thread, and thus events might queue up, waitin...
View detailed answer →Answer: // for Single line comments and /* Multi Line Comment */
View detailed answer →Answer: ‘ViewState’ is specific to a page in a session. ‘SessionState’ is specific to user specific data that can be accessed across all pages in the web application.
View detailed answer →Answer: === is called as strict equality operator which returns true when the two operands are having the same value without any type conversion.
View detailed answer →Answer: To submit a form using JavaScript use document.form[0].submit(); document.form[0].submit();
View detailed answer →Answer: Yes JavaScript does support automatic type conversion, it is the common way of type conversion used by JavaScript developers
View detailed answer →Answer: It can be done in the following way: document.getElementById(“myText”).style.fontSize = “20?; 1 document.getElementById(“myText”).style.fontSize=“20?; or document.getElementById(“myText”).className = “anyclass”; 1 document.getElementById(“myText”).className=“anyclass”;
View detailed answer →Answer: There are two ways to read and write a file using JavaScript Using JavaScript extensions Using a web page and Active X objects
View detailed answer →Answer: Following are looping structures in Javascript: For While do-while loops
View detailed answer →Answer: Variable typing is used to assign a number to a variable and the same variable can be assigned to a string. Example i = 10; i = "string"; 1 2 3 i=10; i="string"; This is called variable typing.
View detailed answer →Answer: The parseInt() function is used to convert numbers between different bases. parseInt() takes the string to be converted as its first parameter, and the second parameter is the base of the given string. In order to convert 4F (of base 16) to integer, the code used will be – parseInt ("4F", 16); 1 parseInt("4F",16);
View detailed answer →Answer: “==” checks only for equality in value whereas “===” is a stricter equality test and returns false if either the value or the type of the two variables are different.
View detailed answer →Answer: Since 3 and 2 are integers, they will be added numerically. And since 7 is a string, its concatenation will be done. So the result would be 57.
View detailed answer →Answer: In order to detect the operating system on the client machine, the navigator.appVersion string (property) should be used.
View detailed answer →Answer: The NULL value is used to represent no value or no object. It implies no object or null string, no valid boolean value, no number and no array object.
View detailed answer →Answer: The functionality of delete operator is used to delete all variables and objects in a program but it cannot delete variables declared with VAR keyword.
View detailed answer →Answer: Undefined value means the Variable used in the code doesn’t exist Variable is not assigned to any value Property doesn’t exist
View detailed answer →Answer: Alert Confirm and Prompt
View detailed answer →Answer: Void(0) is used to prevent the page from refreshing and parameter “zero” is passed while calling. Void(0) is used to call another method without refreshing the page.
View detailed answer →Answer: The following code has to be inserted to achieve the desired effect: <script language="JavaScript" type="text/javascript" > <!-- location.href="http://newhost/newpath/newfile.html"; //--></script> 1 2 3 <script language="JavaScript"type="text/javascript"> <!--location.href="http://newhost/newpath/newfile.html";//--></script>
View detailed answer →Answer: All variables in the JavaScript are object data types.
View detailed answer →Answer: An alert box displays only one button which is the OK button. But a Confirmation box displays two buttons namely OK and cancel.
View detailed answer →Answer: Escape characters (Backslash) is used when working with special characters like single quotes, double quotes, apostrophes and ampersands. Place backslash before the characters to make it display. Example: document.write "I m a "good" boy" document.write "I m a "good" boy" 1 2 3 document.write"I m a "good" boy" document.write"I m a "good" boy"
View detailed answer →Answer: Cookies are the small test files stored in a computer and it gets created when the user visits the websites to store information that they need. Example could be User Name details and shopping cart information from the previous visits.
View detailed answer →Answer: The pop() method is similar as the shift() method but the difference is that the Shift method works at the end of the array. Also the pop() method take the last element off of the given array and returns it. The array on which is called is then altered.
View detailed answer →Answer: No. JavaScript does not have concept level scope. The variable declared inside the function has scope inside the function.
View detailed answer →Answer: If you use innerHTML in JavaScript the disadvantage is Content is replaced everywhere We cannot use like “appending to innerHTML” Even if you use +=like “innerHTML = innerHTML + ‘html’” still the old content is replaced by html The entire innerHTML content is re-parsed and build into elements, therefore its much slower The innerHTML does not provide validation and therefore we can potentially insert valid and broken HTML in the document and break it
View detailed answer →Answer: Break statement exits from the current loop. Continue statement continues with next statement of the loop.
View detailed answer →Answer: They are as – Primitive Reference types.
View detailed answer →Answer: Generic objects can be created as: var I = new object(); 1 varI=newobject();
View detailed answer →Answer: ‘Typeof’ is an operator which is used to return a string description of the type of a variable.
View detailed answer →Answer: Try… Catch—finally is used to handle exceptions in the JavaScript Try{ Code } Catch(exp){ Code to throw an exception } Finally{ Code runs either it finishes successfully or after catch } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 Try{ Code } Catch(exp){ Code tothrowan exception } Finally{ Code runs either it finishes successfully orafter catch }
View detailed answer →Answer: document.write(“Welcome”) is used to print the text – Welcome in the screen.
View detailed answer →Answer: Blur function is used to remove the focus from the specified object.
View detailed answer →Answer: Variable typing is used to assign a number to a variable and then assign string to the same variable. Example is as follows: i= 8; i=”john”; 1 2 3 i=8; i=”john”;
View detailed answer →Answer: The ‘Navigator.appversion’ is used to find the name of the operating system in the client machine.
View detailed answer →Answer: There are three types of errors: Load time errors: Errors which come up when loading a web page like improper syntax errors are known as Load time errors and it generates the errors dynamically. Run time errors: Errors that come due to misuse of the command inside the HTML language. Logical Errors: These are the errors that occur due to the bad logic performed on a function which is having different operation.
View detailed answer →Answer: The push method is used to add or append one or more elements to the end of an Array. Using this method, we can append multiple elements by passing multiple arguments
View detailed answer →Answer: Unshift method is like push method which works at the beginning of the array. This method is used to prepend one or more elements to the beginning of the array.
View detailed answer →Answer: Both are almost similar. JavaScript is developed by Netscape and Jscript was developed by Microsoft .
View detailed answer →Answer: Properties are assigned to objects in the following way – obj["class"] = 12; 1 obj["class"]=12; or obj.class = 12; 1 obj.class=12;
View detailed answer →Answer: Strict Mode adds certain compulsions to JavaScript. Under the strict mode, JavaScript shows errors for a piece of codes, which did not show an error before, but might be problematic and potentially unsafe. Strict mode also solves some mistakes that hamper the JavaScript engines to work efficiently. Strict mode can be enabled by adding the string literal “use strict” above the file. This can be illustrated by the given example: function myfunction() { “use strict"; var v = “This is a strict mode function"; } 1 2 3 4 5 6 7 8 9 functionmyfunction() { “usestrict"; var v = “This is a st...
View detailed answer →Answer: The status can be acquired as follows – alert(document.getElementById(‘checkbox1′).checked); If the CheckBox will be checked, this alert will return TRUE.
View detailed answer →Answer: The navigator.appVersion string can be used to detect the operating system on the client machine.
View detailed answer →Answer: The onload function is not run until all the information on the page is loaded. This leads to a substantial delay before any code is executed. onDocumentReady loads the code just after the DOM is loaded. This allows early manipulation of the code.
View detailed answer →Answer: Closure is a locally declared variable related to a function which stays in memory when the function has returned. For example: JavaScript function greet(message) { console.log(message); } function greeter(name, age) { return name + " says howdy!! He is " + age + " years old"; } // Generate the message var message = greeter("James", 23); // Pass it explicitly to greet greet(message); This function can be better represented by using closures function greeter(name, age) { var message = name + " says howdy!! He is " + age + " years old"; return function greet() { console.log(message); }; } // Generate the closure var JamesGreeter = greeter("Jame...
View detailed answer →Answer: A value can be appended to an array in the given manner – arr[arr.length] = value;
View detailed answer →Answer: The for-in loop is used to loop through the properties of an object. The syntax for the for-in loop is – for (variable name in object){ statement or block to execute } 1 2 3 4 5 for(variable nameinobject){ statement orblock toexecute } In each repetition, one property from the object is associated to the variable name, and the loop is continued till all the properties of the object are depleted.
View detailed answer →Answer: A function that is declared without any named identifier is known as an anonymous function. In general, an anonymous function is inaccessible after its declaration. Anonymous function declaration – var anon = function() { alert('I am anonymous'); }; anon(); 1 2 3 4 5 6 7 varanon=function(){ alert('I am anonymous'); }; anon();
View detailed answer →Answer: The function .call() and .apply() are very similar in their usage except a little difference. .call() is used when the number of the function’s arguments are known to the programmer, as they have to be mentioned as arguments in the call statement. On the other hand, .apply() is used when the number is not known. The function .apply() expects the argument to be an array. The basic difference between .call() and .apply() is in the way arguments are passed to the function. Their usage can be illustrated by the given example. JavaScript var someObject = { myProperty : 'Foo', myMethod : function(prefix, postfix) { alert(prefix + this.myPrope...
View detailed answer →Answer: JavaScript allows DOM elements to be nested inside each other. In such a case, if the handler of the child is clicked, the handler of parent will also work as if it were clicked too.
View detailed answer →Answer: Yes, JavaScript is case sensitive. For example, a function parseInt is not same as the function Parseint.
View detailed answer →Answer: The ‘And’ Operator (&&), ‘Or’ Operator (||) and the ‘Not’ Operator (!) can be used in JavaScript. *Operators are without the parenthesis.
View detailed answer →Answer: This can be done by including the name of the required frame in the hyperlink using the ‘target’ attribute. <a href=”newpage.htm” target=”newframe”>>New Page</a> 1 <a href=”newpage.htm”target=”newframe”>>New Page</a>
View detailed answer →Answer: Break statement is used to come out of the current loop while the continue statement continues the current loop with a new recurrence.
View detailed answer →Answer: Both web-garden and web-farm are web hosting systems. The only difference is that web-garden is a setup that includes many processors in a single server while web-farm is a larger setup that uses more than one server.
View detailed answer →Answer: This can be done by Using JavaScript extensions (runs from JavaScript Editor), example for opening of a file – fh = fopen(getScriptPath(), 0); 1 fh=fopen(getScriptPath(),0);
View detailed answer →Answer: DOM stands for Document Object Model and is responsible for how various objects in a document interact with each other. DOM is required for developing web pages, which includes objects like paragraph, links, etc. These objects can be operated to include actions like add or delete. DOM is also required to add extra capabilities to a web page. On top of that, the use of API gives an advantage over other existing models.
View detailed answer →Answer: Events are the actions that result from activities, such as clicking a link or filling a form, by the user. An event handler is required to manage proper execution of all these events. Event handlers are an extra attribute of the object. This attribute includes event’s name and the action taken if the event takes place.
View detailed answer →Answer: By default, the parsing of the HTML code, during page loading, is paused until the script has not stopped executing. It means, if the server is slow or the script is particularly heavy, then the webpage is displayed with a delay. While using Deferred, scripts delays execution of the script till the time HTML parser is running. This reduces the loading time of web pages and they get displayed faster.
View detailed answer →Answer: The different functional components in JavaScript are- First-class functions: Functions in JavaScript are utilized as first class objects. This usually means that these functions can be passed as arguments to other functions, returned as values from other functions, assigned to variables or can also be stored in data structures. Nested functions: The functions, which are defined inside other functions, are called Nested functions. They are called ‘everytime’ the main function is invoked.
View detailed answer →Answer: JavaScript gives a message if it encounters an error. The recognized errors are – Load-time errors: The errors shown at the time of the page loading are counted under Load-time errors. These errors are encountered by the use of improper syntax, and thus are detected while the page is getting loaded. Run-time errors: This is the error that comes up while the program is running. It is caused by illegal operations, for example, division of a number by zero, or trying to access a non-existent area of the memory. Logic errors: It is caused by the use of syntactically correct code, which does not fulfill the required task. For examp...
View detailed answer →Answer: Screen objects are used to read the information from the client’s screen. The properties of screen objects are – AvalHeight: Gives the height of client’s screen AvailWidth: Gives the width of client’s screen. ColorDepth: Gives the bit depth of images on the client’s screen Height: Gives the total height of the client’s screen, including the taskbar Width: Gives the total width of the client’s screen, including the taskbar
View detailed answer →Answer: This method is functional at the starting of the array, unlike the push(). It adds the desired number of elements to the top of an array. For example – JavaScript var name = [ "john" ]; name.unshift( "charlie" ); name.unshift( "joseph", "Jane" ); console.log(name); 1 2 3 4 5 6 7 varname=["john"]; name.unshift("charlie"); name.unshift("joseph","Jane"); console.log(name); The output is shown below: [" Jane ", " joseph ", " charlie ", " john "] 1 [" Jane "," joseph "," charlie "," john "]
View detailed answer →Answer: The escape () function is responsible for coding a string so as to make the transfer of the information from one computer to the other, across a network. For Example: <script> document.write(escape(“Hello? How are you!”)); </script> 1 2 3 4 5 <script> document.write(escape(“Hello?How are you!”)); </script> Output: Hello%3F%20How%20are%20you%21 The unescape() function is very important as it decodes the coded string. It works in the following way. For example: <script> document.write(unescape(“Hello%3F%20How%20are%20you%21”)); </script> 1 2 3 4 5 <script&g...
View detailed answer →Answer: EncodeURl() is used to convert URL into their hex coding. And DecodeURI() is used to convert the encoded URL back to normal. JavaScript <script> var uri="my test.asp?name=ståle&car=saab"; document.write(encodeURI(uri)+ "<br>"); document.write(decodeURI(uri)); </script> 1 2 3 4 5 6 7 8 9 <script> varuri="my test.asp?name=ståle&car=saab"; document.write(encodeURI(uri)+"<br>"); document.write(decodeURI(uri)); </script>
View detailed answer →Answer: innerHTML content is refreshed every time and thus is slower. There is no scope for validation in innerHTML and, therefore, it is easier to insert rouge code in the document and, thus, make the web page unstable.
View detailed answer →Answer: var myArray = [[[]]]; 1 varmyArray=[[[]]]; It declares a three dimensional array.
View detailed answer →Answer: ECMAScript is nothing but another name for JavaScript. Precisely, ECMAScript is the formal name of JavaScript, when XML elements have to be accessed.
View detailed answer →Answer: Namespacing is used for grouping the desired functions, variables etc. under a unique name. It is a name that has been attached to the desired functions, objects and properties. This improves modularity in the coding and enables code reuse.
View detailed answer →Answer: For hiding JavaScript codes from old browsers: Add “<!–” without the quotes in the code just after the <script> tag. Add “//–>” without the quotes in the code just before the <script> tag. Old browsers will now treat this JavaScript code as a long HTML comment. While, a browser that supports JavaScript, will take the “<!–” and “//–>” as one-line comments.
View detailed answer →Answer: Ans:There are several way for adding JavaScript on a web page, but there are two ways which are commonly used by developers If your script code is very short and only for single page, then following ways are the best: a) You can place <script type="text/javascript"> tag inside the <head> element. Code <head> <title>Page Title</title> <script language="JavaScript" type="text/javascript"> var name = "Vikas Ahlawta" alert(name); </script> </head> b) If your script code is very large, then you can make a JavaScript file and add its path in the following way: Code <head> <title>Page Title...
View detailed answer →Answer: Yes! A function getElementById is not the same as getElementbyID.
View detailed answer →Answer: Ans:String, Number, Boolean, Function, Object, Null, Undefined.
View detailed answer →Answer: Or Operator: || Not Operator: !
View detailed answer →Answer: “==” checks equality only, “===” checks for equality as well as the type.
View detailed answer →Answer: Code <!DOCTYPE html> <html> <body> Full name: <input type="text" id="txtFullName" name="FirstName" value="Vikas Ahlawat"> </body> </html> There are following ways to access the value of the above textbox: var name = document.getElementById('txtFullName').value; alert(name); or: we can use the old way: document.forms[0].mybutton. var name = document.forms[0].FirstName.value; alert(name); Note: This uses the "name" attribute of the element to locate it.
View detailed answer →Answer: // is used for line comments ex:- var x=10; //comment text /* */ is used for block comments ex:- var x= 10; /* this is block comment example.*
View detailed answer →Answer: var status = document.getElementById('checkbox1').checked; alert(status); will return true or false.
View detailed answer →Answer: here are two ways to create array in JavaScript like other languages: a) The first way to create array Declare Array: Code var names = new Array(); Add Elements in Array:- names[0] = "Vikas"; names[1] = "Ashish"; names[2] = "Nikhil"; b) This is the second way: var names = new Array("Vikas", "Ashish", "Nikhil");
View detailed answer →Answer: Ans: Print third array element document.write(names[2]); Note:- Array index starts with 0.
View detailed answer →Answer: Use document.forms[0].submit();
View detailed answer →Answer: It returns true if the argument is not a number. Example: Code document.write(isNaN("Hello")+ "<br>"); document.write(isNaN("2013/06/23")+ "<br>"); document.write(isNaN(123)+ "<br>"); The output will be: true true false
View detailed answer →Answer: The math object provides you properties and methods for mathematical constants and functions. ex:- Code var x = Math.PI; // Returns PI var y = Math.sqrt(16); // Returns the square root of 16 var z = Math.sin(90); Returns the sine of 90
View detailed answer →Answer: In JavaScript the this is a context-pointer and not an object pointer. It gives you the top-most context that is placed on the stack. The following gives two different results (in the browser, where by-default the window object is the 0-level context):
View detailed answer →Answer: Since 1 is a string, everything is a string, so the result is 124.
View detailed answer →Answer: Since 3 and 4 are integers, this is number arithmetic, since 7 is a string, it is concatenation, so 77 is the result.
View detailed answer →Answer: Code document.getElementById(“myText”).style.fontSize = “10"; -or- document.getElementById(“myText”).className = “anyclass”;
View detailed answer →Answer: JavaScript 1.6(ECMAScript 5th Edition) support foreach loop, See example here http://jsfiddle.net/gpDWk/
View detailed answer →Answer: for, while, do-while loops
View detailed answer →Answer: An object is just a container for a collection of named values: // Create the man object Code var man = new Object(); man.name = 'Vikas Ahlawat'; man.living = true; man.age = 27;
View detailed answer →Answer: Code var man = new Object(); man.name = 'Vikas Ahlawat'; man.living = true; man.age = 27; man.getName = function() { return man.name;} console.log(man.getName()); // Logs 'Vikas Ahlawat'.
View detailed answer →Answer: 1st:- var myString = new String('male'); // An object. 2nd:- var myStringLiteral = 'male'; // Primitive string value, not an object. Ans: Both will call String() constructor function You can confirm it by running the following statement: console.log(myString.constructor, myStringLiteral.constructor);
View detailed answer →Answer: var myString = 'Vikas' // Create a primitive string object. var myStringCopy = myString; // Copy its value into a new variable. var myString = null; // Manipulate the value console.log(myString, myStringCopy); Ans: // Logs 'null Vikas'
View detailed answer →Answer: console.log(price1 === price2); // Logs true. console.log(price1 === price3); /* Logs false because price3 contains a complex number object and price 1 is a primitive value. */
View detailed answer →Answer: Logs false, JavaScript does not care that they are identical and of the same object type. When comparing complex objects, they are equal only when they reference the same object (i.e., have the same address). Two variables containing identical objects are not equal to each other since they do not actually point at the same object.
View detailed answer →Answer: Logs true
View detailed answer →Answer: Three dimensional array
View detailed answer →Answer: Number() parseInt() parseFloat() Code var n1 = Number(“Hello world!”); //NaN var n2 = Number(“”); //0 var n3 = Number(“000010”); //10 var n4 = Number(true); //1 var n5 = Number(NaN); //NaN
View detailed answer →Answer: Yes! Javascript support automatic type conversion. You should take advantage of it, It is most common way of type conversion used by Javascript developers. Ex. var s = '5'; var a = s*1; var b = +s; typeof(s); //"string" typeof(a); //"number" typeof(b); //"number"
View detailed answer →Answer: Event bubbling is series of events when : An event is triggered on the inner most element first and then it triggers on the parent elements in nested order. DOM elements could be nested inside each other. The handler of the parent works even if you click on it’s child. Event bubbling can make this happen. Event Capturing is the opposite of bubbling where the event is triggered on the outer most element and then it triggers the inner children in nested order.
View detailed answer →Answer: JavaScript allows you to declare a function within another function, and the local variables still can be accessible even after returning from the function you called. In other words, a closure is the local variables for a function which is kept alive after the function has returned. An example : function goodMorning(name) { var text = ‘Good Morning ‘ + name; // local variable var goodMorningAlert = function() { alert(text); } return sayAlert; } var goodMorningAlert2 = goodMorning(‘Bob’); goodMorningAlert2(); In the example above, when goodMorningAlert2() will...
View detailed answer →Answer: The code above prints 5. The trick of this question is that in the IIFE there are two assignments but the variable a is declared using the keyword var. What this means is that a is a local variable of the function. On the contrary, b is assigned to the global scope. The other trick of this question is that it doesn’t use strict mode ('use strict';) inside the function. If strict mode was enabled, the code would raise the error Uncaught ReferenceError: b is not defined. Remember that strict mode requires you to explicitly reference to the global scope if this was the intended behavior. So, you should write: 1 2 3 4 5 6 (function() { &nbs...
View detailed answer →Answer: A possible implementation is shown below: 1 2 3 4 5 6 7 8 9 String.prototype.repeatify = String.prototype.repeatify || function(times) { var str = ''; for (var i = 0; i < times; i++) { str += this; } return str; }; The question tests the knowledge of the developer about inheritance in JavaScript and the prototype property. It also verifies that the developer is able to extend native data type functionalities (although this should not be done). Another important point here is to demonstrate that you are aware abou...
View detailed answer →Answer: The result of this code is undefined and 2. The reason is that both variables and functions are hoisted (moved at the top of the function) but variables don’t retain any assigned value. So, at the time the variable a is printed, it exists in the function (it’s declared) but it’s still undefined. Stated in other words, the code above is equivalent to the following: 1 2 3 4 5 6 7 8 9 10 11 12 13 function test() { var a; function foo() { return 2; } console.log(a); console.log(foo()); ...
View detailed answer →Answer: The code prints Aurelio De Rosa and John Doe. The reason is that the context of a function, what is referred with the this keyword, in JavaScript depends on how a function is invoked, not how it’s defined. In the first console.log() call, getFullname() is invoked as a function of the obj.prop object. So, the context refers to the latter and the function returns the fullname property of this object. On the contrary, when getFullname() is assigned to the test variable, the context refers to the global object (window). This happens because test is implicitly set as a property of the global object. For this reason, the function returns the ...
View detailed answer →Answer: ECMAScript is yet another name for JavaScript (other names include LiveScript). The current JavaScript that you see supported in browsers is ECMAScript revision 3.
View detailed answer →Answer: Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt ("3F", 16);
View detailed answer →Answer: &&, || and !
View detailed answer →Answer: var obj = new Object(); or var obj = {};
View detailed answer →Answer: obj["age"] = 17 or obj.age = 17.
View detailed answer →Answer: arr[arr.length] = value;
View detailed answer →Answer: It refers to the current object.
View detailed answer →Answer: The onload event does not fire until every last piece of the page is loaded, this includes css and images, which means there’s a huge delay before any code is executed. That isnt what we want. We just want to wait until the DOM is loaded and is able to be manipulated. onDocumentReady allows the programmer to do that.
View detailed answer →Answer: document.getElementById(“myText”).style.fontSize = “20”; -or- document.getElementById(“myText”).className = “anyclass”;
View detailed answer →Answer: Two one sentence summaries: * a closure is the local variables for a function – kept alive after the function has returned, or * a closure is a stack-frame which is not deallocated when the function returns. A closure takes place when a function creates an environment that binds local variables to it in such a way that they are kept alive after the function has returned. A closure is a special kind of object that combines two things: a function, and any local variables that were in-scope at the time that the closure was created. The following code returns a reference to a function: function sayHello2(name) { var text = ‘Hello &lsq...
View detailed answer →Answer: Unobtrusive Javascript refers to the argument that the purpose of markup is to describe a document’s structure, not its programmatic behavior and that combining the two negatively impacts a site’s maintainability. Inline event handlers are harder to use and maintain, when one needs to set several events on a single element or when one is using event delegation. 1 <input type="text" name="date" /> Say an input field with the name “date” had to be validated at runtime: 1 2 3 4 5 6 document.getElementsByName("date")[0]. &...
View detailed answer →Answer: Using global variables in Javascript is evil and a bad practice. That being said, namespacing is used to bundle up all your functionality using a unique name. In JavaScript, a namespace is really just an object that you’ve attached all further methods, properties and objects. It promotes modularity and code reuse in the application.
View detailed answer →Answer: Number, String, Undefined, null, Boolean 10. What is the difference between innerHTML and append() in JavaScript? InnerHTML is not standard, and its a String. The DOM is not, and although innerHTML is faster and less verbose, its better to use the DOM methods like appendChild(), firstChild.nodeValue, etc to alter innerHTML content.
View detailed answer →Answer: The most basic and ancient use of buttons are the "submit" and "clear", which appear slightly beforethe Pleistocene period. Notice when the "GO!" button is pressed it submits itself to itself and appendsthe name in the URL.<form action="" name="buttonsGalore" method="get">Your Name: <input type="text" name="mytext" /><br /><input type="submit" value="GO!" /><input type="reset" value="Clear All" /></form> Another useful approach is to set the "type" to "button" and use the "onclick" event.<script type="text/javascript">function displayHero(button) {alert("Your hero is ""+button.value+"".")...
View detailed answer →Answer: Generation of HTML pages on-the-fly without accessing the Web server. The user can be given controlover the browser like User input validation Simple computations can be performed on the client'smachine The user's browser, OS, screen size, etc. can be detected Date and Time Handling
View detailed answer →Answer: Fragmentation of the installed base of browsers will only get worse. By definition, it can never improveunless absolutely everyone on the planet threw away their old browsers and upgraded to the latest geewhizversions. But even then, there are plenty of discrepancies between the scriptability of the latestNetscape Navigator and Microsoft Internet Explorer.The situation makes scripting a challenge, especially for newcomers who may not be aware of thelimitations of earlier browsers. A lot of effort in my books and ancillary material goes toward helpingscripters know what features work in which browsers and how to either workaround limitations i...
View detailed answer →Answer: Use window.opener to refer to the main window from pop-ups.
View detailed answer →Answer: 1. To remove an item from a list set it to nullmySelectObject.options[3] = null;2. To truncate a list set its length to the maximum size you desiremySelectObject.length = 2;3. To delete all options in a select object set the length to 0.mySelectObject.leng
View detailed answer →Answer: The "Access Denied" error in any browser is due to the following reason.A javascript in one window or frame is tries to access another window or frame whose document'sdomain is different from the document containing the script
View detailed answer →Answer: Yes.Since javascript is a client-side script it does require the web server's help for itscomputation,so it is always faster than any server-side script like ASP,PHP,etc..
View detailed answer →Answer: No.java and javascript are two different languages.Java is a powerful object - oriented programming language like C++,C whereas Javascript is a clientsidescripting language with some limitations.
View detailed answer →Answer: javascript code can be embedded in a web page between <script langugage="javascript"></script> tags
View detailed answer →Answer: The Web has several FAQ areas on JavaScript. The best place to start is something called the meta-FAQ [14-Jan-2001 Editor's Note: I can't point to it anymore, it is broken!], which provides a high-leveloverview of the JavaScript help available on the Net. As for fact-filled FAQs, I recommend onemaintained by Martin Webb and a mini-FAQ that I maintain.For interactive help with specific problems, nothing beats the primary JavaScript Usenet newsgroup,comp.lang.javascript. Depending on my work backlog, I answer questions posted there from time totime. Netscape and Microsoft also have vendor-specific developer discussion groups as well as detailed...
View detailed answer →Answer: Breaking is possible within a string statement by using a backslash at the end but not within any otherjavascript statement.that is ,document.write("Hello world");
View detailed answer →Answer: Setting EnableViewStateMac=true is a security measure that allows ASP.NET to ensure that theviewstate for a page has not been tampered with. If on Postback, the ASP.NET framework detects thatthere has been a change in the value of viewstate that was sent to the browser, it raises an error -Validation of viewstate MAC failed.Use <%@ Page EnableViewStateMac="true"%> to set it to true (the default value, if this attribute isnot specified is also true) in an aspx page.
View detailed answer →Answer: JavaScript was developed by Brendan Eich of Netscape; Java was developed at Sun Microsystems. While the two languages share some common syntax, they were developed independently of each other and for different audiences. Java is a full-fledged programming language tailored for network computing; it includes hundreds of its own objects, including objects for creating user interfaces that appear in Java applets (in Web browsers) or standalone Java applications. In contrast, JavaScript relies on whatever environment it's operating in for the user interface, such as a Web document's form elements. JavaScript was initially called LiveScript at Net...
View detailed answer →Answer: You can use several different methods of placing javascript in you pages. You can directly add a script element inside the body of page. 1. For example, to add the "last updated line" to your pages, In your page text, add the following: <p>blah, blah, blah, blah, blah.</p><script type="text/javascript" ><!-- Hiding from old browsersdocument.write("Last Updated:" + document.lastModified);document.close();// --></script><p>yada, yada, yada.</p>(Note: the first comment, "<--" hides the content of the script from browsers that don't understand javascript. The "// -->" finishes the comment. The "//" ...
View detailed answer →Answer: I/O operations like reading or writing a file is not possible with client-side javascript. However , this can be done by coding a Java applet that reads files for the script.
View detailed answer →Answer: In order to detect the operating system on the client machine, the navigator.appVersion string (property) should be used.
View detailed answer →Answer: JavaScript's greatest potential gift to a Web site is that scripts can make the page more immediately interactive, that is, interactive without having to submit every little thing to the server for a server program to re-render the page and send it back to the client. For example, consider a top-level navigation panel that has, say, six primary image map links into subsections of the Web site. With only a little bit of scripting, each map area can be instructed to pop up a more detailed list of links to the contents within a subsection whenever the user rolls the cursor atop a map area. With the help of that popup list of links, the user with...
View detailed answer →Answer: On their own, Web pages tend to be lifeless and flat unless you add animated images or more bandwidth-intensive content such as Java applets or other content requiring plug-ins to operate (ShockWave and Flash, for example). Embedding JavaScript into an HTML page can bring the page to life in any number of ways. Perhaps the most visible features built into pages recently with the help of JavaScript are the so-called image rollovers: roll the cursor atop a graphic image and its appearance changes to a highlighted version as a feedback mechanism to let you know precisely what you're about to click on. But there are less visible yet more powerful...
View detailed answer →Answer: Include the name of the frame in the target attribute of the hyperlink. <a href=”mypage.htm” target=”myframe”>>My Page</a>
View detailed answer →Answer: Fixed width tables are rendered by the browser based on the widths of the columns in the first row, resulting in a faster display in case of large tables. Use the CSS style table-layout:fixed to specify a fixed width table. If the table is not specified to be of fixed width, the browser has to wait till all data is downloaded and then infer the best width for each of the columns. This process can be very slow for large tables.Example of using Regular Expressions for syntax checking in JavaScript ...var re = new RegExp("^(&[A-Za-z_0-9]{1,}=[A-Za-z_0-9]{1,})*$");var text = myWidget.value;var OK = re.test(text);if( ! OK ) {alert("The extra p...
View detailed answer →Answer: document.bgcolor property can be set to any appropriate color.
View detailed answer →Answer: JavaScript allows a Web page to perform "if-then" kinds of decisions based on browser version, operating system, user input, and, in more recent browsers, details about the screen size in which the browser is running. While a server CGI program can make some of those same kinds of decisions, not everyone has access to or the expertise to create CGI programs. For example, an experienced CGI programmer can examine information about the browser whenever a request for a page is made; thus a server so equipped might serve up one page for Navigator users and a different page for Internet Explorer users. Beyond browser and operating system version, ...
View detailed answer →Answer: GET: Parameters are passed in the querystring. Maximum amount of data that can be sent via the GET method is limited to about 2kb.POST: Parameters are passed in the request body. There is no limit to the amount of data that can be transferred using POST. However, there are limits on the maximum amount of data that can be transferred in one name/value pair.
View detailed answer →Answer: It is true, text you last copied for pasting (copy & paste) can be stolen when you visit web sites using a combination of JavaScript and ASP (or PHP, or CGI) to write your possible sensitive data to a database on another server.
View detailed answer →Answer: Browser version incompatibility is the biggest problem. It requires knowing how each scriptable browser version implements its object model. You see, the incompatibility rarely has to do with the core JavaScript language (although there have been improvements to the language over time); the bulk of incompatibility issues have to do with the object models that each browser version implements. For example, scripters who started out with Navigator 3 implemented the image rollover because it looked cool. But they were dismayed to find out that the image object wasn't scriptable in Internet Explorer 3 or Navigator 2. While there are easy workaroun...
View detailed answer →Answer: Use the "value" property. var myValue = window.document.getElementById("MyTextBox").value;
View detailed answer →Answer: var checkedP = window.document.getElementById("myCheckBox").checked;
View detailed answer →Answer: <script> function setFocus() { if(focusElement != null) { document.forms[0].elements["myelementname"].focus(); } } </script>
View detailed answer →Answer: This can be achieved by using the following tag between head tags or between body tags.<script src="abc.js"></script>How to access an external javascript file that is stored externally and not embedded? where abc.js is the external javscript file to be accessed.
View detailed answer →Answer: One of the reasons JavaScript has the word "script" in it is that as a programming language, the vocabulary of the core language is compact compared to full-fledged programming languages. If you already program in Java or C, you actually have to unlearn some concepts that had been beaten into you. For example, JavaScript is a loosely typed language, which means that a variable doesn't care if it's holding a string, a number, or a reference to an object; the same variable can even change what type of data it holds while a script runs. The other part of JavaScript implementation in browsers that makes it easier to learn is that most of the obje...
View detailed answer →Answer: The best sites are the ones that use JavaScript so transparently, that I'm not aware that there is any scripting on the page. The worst sites are those that try to impress me with how much scripting is on the page.
View detailed answer →Answer: Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, it’s concatenation, so 78 is the result.
View detailed answer →Answer: ViewState is specific to a page in a session. Session state refers to user specific data that can be accessed across all pages in the web application.
View detailed answer →Answer: Use the below specified style of comments <script language=javascript> <!-- javascript code goes here // --> or Use the <NOSCRIPT>some html code </NOSCRIPT> tags and code the display html statements between these and this will appear on the page if the browser does not support javascript
View detailed answer →Answer: Use // for line comments and/**/ for block comments
View detailed answer →Answer: Number.MAX_VALUENumber.MIN_VALUE
View detailed answer →Answer: Each HTML document loaded into a browser window becomes a document object. It provides access to all HTML elements in a page from within the script. The document object is a part of the window object. It can be accessed through window document property.
View detailed answer →Answer: Events allow you to write a javascript code that reacts to certain situations. They are actions detected by javascript. Every element on a web page has certain events that can trigger a javascript code. Events are usually used in a combination with functions. Hence, functions will not be executed until the event occurs. In order to execute functions on the occurrence of certain events, event handlers are provided in javascript They start with the prefix 'On'. Each event handler deals with a certain type of event.
View detailed answer →Answer: Lightweight interpreted open and cross-platform created for the network-centric application
View detailed answer →Answer: We can explain the javascript method and object value with the value is div tag in html. In coding basic level is html. there have various tag.<div *dxTemplate="let cell of 'valueTemplate'"> <div [ngstyle]="{color:(fmtValue(cell.value).startsWith('(')) ? 'green' : 'blue'}"> {{fmtValue(cell.value)}} </div> </div>
View detailed answer →