JavaScript
JavaScript
Object 2
1
JavaScript is a client-side as well as server side scripting language that can be inserted into HTML
pages and is understood by web browsers. JavaScript is also an Object Oriented Programming
language
2. Enumerate the differences between Java and JavaScript?
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.
3. What are JavaScript types?
Following are the JavaScript types:
• Number
• String
• Boolean
• Function
• Object
• Null
• Undefined
Javascript
6. What is negative infinity?
Negative Infinity is a number in JavaScript which can be derived by dividing negative number by
zero.
7. Is it possible to break JavaScript Code into several lines?
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:
<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>
<html>
1 <head> <title>t1</title>
2
3 <script type="text/javascript">
4 function addNode() { var newP = document.createElement("p");
5 var textNode = document.createTextNode(" This is a new text node");
6 newP.appendChild(textNode); document.getElementById("firstP").appendChild(newP); }
7
8
</script> </head>
9 <body> <p id="firstP">firstP<p> </body>
</html>
11. What are global variables? How are these variable declared and what are the problems
associated with using them?
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.
12. What is a prompt box?
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.
13. What is ‘this’ keyword in JavaScript?
‘This’ keyword refers to the object from where it was called.
14. Explain the working of timers in JavaScript? Also elucidate the drawbacks of using the
timer, if any?
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, waiting to be executed.
15. Which symbol is used for comments in Javascript?
// for Single line comments and
/* Multi
Line
Comment
*/
16. What is the difference between ViewState and SessionState?
‘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.
17. What is === operator?
=== is called as strict equality operator which returns true when the two operands are having the
same value without any type conversion.
18. Explain how can you submit a form using JavaScript?
To submit a form using JavaScript use document.form[0].submit();
document.form[0].submit();
19. Does JavaScript support automatic type conversion?
Yes JavaScript does support automatic type conversion, it is the common way of type conversion
used by JavaScript developers
20. How can the style/class of an element be changed?
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”;
21. Explain how to read and write a file using JavaScript?
There are two ways to read and write a file using JavaScript
• Using JavaScript extensions
• Using a web page and Active X objects
i = 10; i = "string";
1 i = 10;
2
3 i = "string";
This is called variable typing.
24. How can you convert the string of any base to integer in JavaScript?
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 –
31. What are all the types of Pop up boxes available in JavaScript?
• Alert
• Confirm and
• Prompt
Primitive types are number and Boolean data types. Reference types are more complex types like
strings and dates.
43. How generic objects can be created?
Generic objects can be created as:
Try{ Code } Catch(exp){ Code to throw an exception } Finally{ Code runs either it finishes successfully or after catch }
Try{
1
2 Code
3
4 }
5
6
7 Catch(exp){
8
9 Code to throw an exception
10
11
12
}
13
14 Finally{
15
16
Code runs either it finishes successfully or after catch
17
}
46. Which keyword is used to print the text in the screen?
document.write(“Welcome”) is used to print the text – Welcome in the screen.
47. What is the use of blur function?
Blur function is used to remove the focus from the specified object.
48. What is variable typing?
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 i= 8;
2
3 i=”john”;
49. How to find operating system in the client machine using JavaScript?
The ‘Navigator.appversion’ is used to find the name of the operating system in the client machine.
50. 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.
51. What is the use of Push method in JavaScript?
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
52. What is unshift method in JavaScript?
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.
53. What is the difference between JavaScript and Jscript?
Both are almost similar. JavaScript is developed by Netscape and Jscript was developed by
Microsoft .
obj["class"] = 12;
1 obj["class"] = 12;
or
obj.class = 12;
1 obj.class = 12;
55. What is the ‘Strict’ mode in JavaScript and how can it be enabled?
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()
1
2
3 {
4
5 “use strict";
6
7
8
var v = “This is a strict mode function";
9
}
56. What is the way to get the status of a CheckBox?
The status can be acquired as follows –
alert(document.getElementById(‘checkbox1’).checked);
If the CheckBox will be checked, this alert will return TRUE.
57. How can the OS of the client machine be detected?
The navigator.appVersion string can be used to detect the operating system on the client machine.
58. Explain window.onload and onDocumentReady?
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.
59. How will you explain closures in JavaScript? When are they used?
Closure is a locally declared variable related to a function which stays in memory when the function
has returned.
For example:
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("James", 23); //
Use the closure JamesGreeter();
function greet(message) {
console.log(message);
1
}
2
3
4 function greeter(name, age) {
5
6 return name + " says howdy!! He is " + age + " years old";
7
8
9 }
10
11 // Generate the message
12
13
14 var message = greeter("James", 23);
15
16 // Pass it explicitly to greet
17
18
19 greet(message);
20
21 This function can be better represented by using closures
22
23
24
function greeter(name, age) {
25
26 var message = name + " says howdy!! He is " + age + " years old";
27
28
return function greet() {
29
30
31 console.log(message);
32
33 };
34
35
36 }
37
38 // Generate the closure
39
40
41 var JamesGreeter = greeter("James", 23);
JamesGreeter();
60. How can a value be appended to an array?
A value can be appended to an array in the given manner –
arr[arr.length] = value;
61. Explain the for-in loop?
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 }
var someObject = { myProperty : 'Foo', myMethod : function(prefix, postfix) { alert(prefix + this.myProperty + postfix); } };
someObject.myMethod('<', '>'); // alerts '<Foo>' var someOtherObject = { myProperty : 'Bar' };
someObject.myMethod.call(someOtherObject, '<', '>'); // alerts '<Bar>' someObject.myMethod.apply(someOtherObject, ['<', '>']); //
alerts '<Bar>'
var someObject = {
1 myProperty : 'Foo',
2
3
myMethod : function(prefix, postfix) {
4
5
6 alert(prefix + this.myProperty + postfix);
7
8 }
9
10
11 };
12
13 someObject.myMethod('<', '>'); // alerts '<Foo>'
14
15
16 var someOtherObject = {
17
18 myProperty : 'Bar'
19
20
21 };
22
23 someObject.myMethod.call(someOtherObject, '<', '>'); // alerts '<Bar>'
fh = fopen(getScriptPath(), 0);
1 fh = fopen(getScriptPath(), 0);
72. How are DOM utilized in JavaScript?
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.
73. How are event handlers utilized in JavaScript?
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.
74. Explain the role of deferred scripts in JavaScript?
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.
75. What are the various functional components in JavaScript?
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.
76. Write about the errors shown in JavaScript?
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 example, an infinite loop.
77. What are Screen objects?
Screen objects are used to read the information from the client’s screen. The properties of screen
objects are –
• AvailHeight: 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
[" joseph "," Jane ", " charlie ", " john "]
1 [" joseph "," Jane ", " charlie ", " john "]
79. Define unescape() and escape() functions?
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 <script>
2
3 document.write(escape(“Hello? How are you!”));
4
5
</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:
1 <script>
2
3 document.write(unescape(“Hello%3F%20How%20are%20you%21”));
4
5
</script>
Output: Hello? How are you!
80. What are the decodeURI() and encodeURI()?
EncodeURl() is used to convert URL into their hex coding. And DecodeURI() is used to convert the
encoded URL back to normal.
<script>
1
2
3 var uri="my test.asp?name=ståle&car=saab";
4
5 document.write(encodeURI(uri)+ "<br>");
6
7
8
document.write(decodeURI(uri));
9
</script>
Output –
my%20test.asp?name=st%C3%A5le&car=saab
my test.asp?name=ståle&car=saab
81. Why it is not advised to use innerHTML in JavaScript?
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.
82. What does the following statement declares?