1. Can you use x === "object" to test if x is an object?
In short, yes, but you must take into account the fact that null is considered an object in JavaScript. Even if x is null, 'console.log(typeof x === "object")' will log true instead of false.
To account for this, you must also test whether or not x is null by including the following:
console.log((x !== null) && (typeof x === "object"));
2. What happens when you don't declare a variable in Javascript?
If you don't explicitly declare a variable, you risk creating an implied global variable. This is a problem, as you will be unable to create multiple instances of that object, as each new instance will overwrite the data from the last.
In general, global variables should be used only in very specific situations and are typically not recommended, as they can lead to a lot of odd side effects that may be difficult to track down.
3. How can I prevent others from reading/stealing my scripts or images?
There are no assertive measures which can be taken to foolproof your scripts and images, but preventive measures can be taken like copyrighting your pages, putting watermark on your images and applying non-technological way to protect your images. Scripts are difficult to protect as they can be accessed through many applications and many programs by using the web browsers.
4. Explain the concept of unobtrusive JavaScript?
Unobtrusive JavaScript is basically a JavaScript methodology that seeks to overcome browser inconsistencies by separating page functionality from structure. The basic premise of unobtrusive JavaScript is that page functionality should be maintained even when JavaScript is unavailable on a user's browser.
5. What is the difference between script type and the script language attributes?
► The script type specifies the type of content that is used to show the language used by the browsers like "language=text/javascript". This defines the MIME type that is also known as Multipurpose Internet Mail Extensions (MIME). Text in this defines a plain text format and script defines the language that will be used.
► The script language attribute on the other hand specify a particular version of JavaScript language that is required to run the script and to provide a mechanism to fall back if any browser doesn't support it.
► Script type is used to define the type through which the browser can understand the language and all the compatible browsers can execute the type according to themselves, whereas the script language attribute defines the content and its attributes that are used.
6. What is namespacing in JavaScript and how is it used?
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.
Nan is literally "Not-a-Number". NaN usually results when either the result or one of the values in an operation is non-numeric. Even though NaN is not a number, 'console.log(typeof NaN === "number");' logs true, while NaN compared to anything else (including NaN) logs false. The only real way to test if a value is equal to NaN is with the function 'isNaN()'.
8. What is unescape() function?
► The unescape() function is used to decode the encoded string.
► Syntax : unescape(string1)
► Where string1 is the string to be decoded.
► Example :
<script>
document.write(unescape("Questions%3F%20Get%20from%20us%21"));
</script>
- Output :
Questions? Get from us!
9. How are JavaScript and ECMA Script related?
ECMAScript is nothing but another name for JavaScript. Precisely, ECMAScript is the formal name of JavaScript, when XML elements have to be accessed.
10. Which boolean operators are in JavaScript?
'and' operator: &&
'or' operator: ||
'not' operator: !
11. What is the difference between window.onload and onDocumentReady?
► The difference is that onDocumentReady is called after the DOM is loaded without waiting for all the contents to get loaded. While window.onload() function waits until the contents of page is loaded.
► Suppose there is very large image on a page, at that time onDocumentReady will wait until that image is loaded totally.
► So while using the window.onlaod() function the execution will be slow, but the onDocumentReady will not wait until the image is loaded.
12. What is the method for reading and writing a file in JavaScript?
This can be done by Using JavaScript extensions (runs from JavaScript Editor), example for opening of a file -
fh = fopen(getScriptPath(), 0);
13. Is JavaScript case sensitive?
Yes, absolutely. For example, the function getElementById is not the same as the function getElementbyID. Keeping your capitalization consistent is important.
► The screen object can be used to retrieve the information about the visitor's screen.
► There are following properties of Screen objects :
avalHeight : This property returns the height of the screen excluding the windows taskbar.
availWidth : This property returns the width of the screen excluding the windows taskbar.
colorDepth : This property returns the bit depth of the color palette to display images.
height : This property returns the total height of the screen.
pixelDepth : This property returns the color resolution of the screen in bits per pixel.
width : This property returns the total width of the screen.
15. How can a particular frame be targeted, from a hyperlink, in JavaScript?
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>
16. Why would you include 'use strict' at the beginning of a JavaScript source file?
Using strict mode enforces stricter error handling when running your code. It essentially raises errors that would have otherwise failed silently. Using strict mode can help you avoid simple mistakes like creating accidental globals, undefined values, or duplicate property names. This is typically a good idea when writing JavaScript, as such errors can create a lot of frustrating side effects and be difficult to track down.
17. What is Shift() method in Javascript?
► The shift() method is similar as the pop() method but the difference is that Shift method works at the beginning of the array.
► The shift() method take the first element off of the given array and returns it. The array on which is called is then altered.
► For example :
var myarray = ["apple ", "banana ", "mango "];
console.log(myarray.shift());
console.log(myarray);
► We get the following console output :
apple
["banana ", "mango "];
► When we call shift() on an empty array, it will return an undefined value.
18. What is the function of Deferred scripts?
Deferred scripts are the scripts whose statements run as grouped together statements as a function. Function provides a definition of a block that a script statement consists of to run the statements that are in the <SCRIPT> tags after all the statements loaded in the browser. Functions allow to see the user clearly the visiblity inside the <SCRIPT> tag. In this tag each function starts with function() and function name is written after it including the parentheses. Once a function is loaded it becomes ready to run whenever there is a use of it. It is useful when a function gets used immediately after a page load. The Window object uses an event handler that triggers the response to the user actions and the handler is onLoad.
19. What is the difference between JavaScript and JScript?
Both are almost similar. JavaScript is developed by Netscape and Jscript was developed by Microsoft.
20. What does a timer do and how would you implement one?
Setting timers allows you to execute your code at predefined times or intervals.
This can be achieved through two main methods: setInterval(); and setTimeout();
setInterval() accepts a function and a specified number of milliseconds.
ex) setInterval(function(){alert("Hello, World!"),10000) will alert the "Hello, World!" function every 10 seconds.
setTimeout() also accepts a function, followed by milliseconds. setTimeout() will only execute the function once after the specified amount of time, and will not reoccur in intervals.
21. What is Push() method in JavaScript?
► The push() method is used to append one or more elements to the end of an array.
► For example :
var fruits = [ "apple" ];
fruits.push( "banana" );
fruits.push( "mango", "strawberry" );
console.log(fruits);
► We get the following console output :
["apple ", "banana ", "mango ", "strawberry "]
► Using Push() method we can also append multiple elements by passing multiple arguments.
► The elements will be appended in the order of they are inserted i.e. left to right.
22. What value does prompt() return if the user clicked the Cancel button?
Return value of prompt() function depends on browsers. Most of the browsers return the value as null and some return as empty string (" "). IE is one of the browser which gives the error of empty string when clicked the cancel button by the user, otherwise all the recent browser return the value as null. The code to check this is as follows:
userInput = prompt('Prompt text','Suggested input');
if (userInput) {
// do something with the input
}
23. What are the different types of errors in JavaScript?
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.
24. What is JavaScript, what about history?
JavaScript, some also know it as ECMAScript, is a dynamic programming language used in a web development. It is an integral part of web browsers, and it allows, among other things, better user interaction, browser control, client-server communications (synchronous and asynchronous), alterations of displayed DOM content.
Although it was first introduced under a different name (Mocha), during its initial release it was officially named LiveScript. Developed by Netscape, the first version was available in Navigator 2.0 (September 1995), but it was renamed JavaScript in version 2.0B3.
25. What is escape() function?
► The escape() function is used to encode the string to convert it as portable string so that it can be sent across any network to any computer which supports ASCII characters.
► This function encodes special characters, with the exception of @ * + - / . _
► Syntax :
escape(string1)
Where string1 is the string to be encoded.
► Example :
<script>
document.write(escape("Questions? Get from us!"));
</script>
► Output :
Questions%3F%20Get%20from%20us%21
26. What is difference between undefined variable and undeclared variable?
► The variable which are declared in the program but not assigned any value yet is called undefined variable while the variable which are not declared in the program is called undeclared variable.
► For Example :
undeclared variable:
<script>
var p;
alert(p); // This will give error because p is undeclared variable.
</script>
? undefined variable
<script>
alert(p); //This will give error because p is undefined.
</script>
27. How can I set up my own JavaScript error handler?
To set up your own JavaScript error handler some optional parameters has to be known. These parameters are as follows:
- Textual description of error
- Address (URL) of page on which error occurred
- Number of line in which error occurred
If you want to invoke the default error handler of the browser, then your function should return (false) or vice versa. Example code:
function handlerFunction(description,page,line)
{ // put error-handling operators here
return true;}
window.onerror=handlerFunction;
28. Explain what is pop()method in JavaScript?
The pop() method is similar as the shift() method but the difference is that the Shift method works at the start 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.
Example:
var cloths = ["Shirt", "Pant", "TShirt"];
cloths.pop();
//Now cloth becomes Shirt,Pant
29. What is event bubbling, and why is it beneficial to use?
Event bubbling transfers events contained within the child node to the parent node. It's a beneficial method because of its speediness, as it only requires the code to traverse the DOM tree one time.
30. What would "1"+2+3 and 1+2+"3" evaluate to, respectively?
When the first character is a string, the remaining characters will be converted into a single string, rendering 123.
If the string is at the end, the initial characters will perform normal mathematical functions before converting into a string, resulting in 33.
31. What is the disadvantages using innerHTML in JavaScript?
► If you use innerHTML the content is replaced everytime.
► We cannot use like 'appending to innerHTML'.
► Even if we use += like "innerHTML = innerHTML + 'html'" then also the old content is replaced by html.
► If we use innerHTML then the entire innerHTML content is re-parsed and build into elements. Therefore it's much slower.
► The innerHTML doesn't provide validation and therefore we can potentially insert invalid and broken HTML in the document and break it.
32. What is the difference between Scripting and Programming?
- Scripting is easier to write than programming. As programming requires more hands on to the code and a language specification to write.
- Scripting consists of lots of tools to easily create an object model and run it using any browser, wheras programming doesn't have many tools to create an object model and it is not easy to use browser compatibility.
- Scripts work with more than just objects, each statement of the JavaScript does something means perform some actions, whereas programming becomes different as each and every action takes time to execute.
- Scriptting doesn't require lots of knowledge to be provided with and can be easily learnt, but to learn a programming language it requires lots of knowledge.
33. How can JavaScript codes be hidden from old browsers that don't support JavaScript?
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.
34. How can a page be forced to load another page in JavaScript?
The following code has to be inserted to achieve the desired effect:
XHTML
<script language="JavaScript" type="text/javascript" >
<!-- location.href="http://newhost/newpath/newfile.html"; //--></script>
35. What does the isNaN() function do?
The isNaN() function is used to determine whether a value is not a number, or an illegal number. If the argument is not a number, the isNaN() function will return TRUE.