Interview Questions and Answers Java Script
Q. What’s relationship between JavaScript and ECMA Script?
Ans – ECMA Script is yet another name for JavaScript (other names include Live Script). The current JavaScript that you see supported in browsers is ECMA Script version 3.
Q. What are JavaScript types?
Ans - Number, String, Boolean, Function, Object, Null, Undefined.
Q. How do you convert numbers between different bases in JavaScript?
Ans - 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);
Q. What does isNaN function do?
Ans - Return true if the argument is not a number.
Q. What is negative infinity?
Ans - It’s a number in JavaScript, derived by dividing negative number by zero.
Q. What boolean operators does JavaScript support?
Ans - &&, || and !
Q. What does "1"+2+4 evaluate to?
Ans - Since 1 is a string, everything is a string, so the result is 124.
Q. How about 2+5+"8"?
Ans - Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, it’s concatenation, so 78 is the result.
Q. What about '7' - 4 ?
Ans – This will give 3.
Q. What looping structures are there in JavaScript?
Ans - for, while, do-while loops, but no foreach.
Q. How do you create a new object in JavaScript?
Ans - var obj = new Object(); or var obj = {};
Q. How do you assign object properties?
Ans - obj["age"] = 17 or obj.age = 17.
Q. What’s a way to append a value to an array?
Ans - arr[arr.length] = value;
Q. What is this keyword?
Ans - It refers to the current object.
Q. What is the delete operator in javascript?
Ans - The delete operator is used to delete an object, an object's property or a specified element in an array, returning true if the operation is possible, and false if not. With the defined object 'fruit' below, the following delete operations are possible:
Code:
fruit = new Object;
fruit.name = 'apple';
fruit.color = 'green';
fruit.size = 'large';
delete fruit.size;
with(fruit)
delete color;
delete fruit;
The delete operator can also be used to delete an element of an array. This does not affect the length of the array or any of the other elements but changes the deleted element to undefined.
Code:
fruit = new Array ("apple", "pear", "orange", "cherry", "grape");
delete fruit[2];
Q. What does javascript null mean?
The null value is representing no value or no object.
It implies no object,or null string,no valid boolean value,no number and no array object.
The null value is representing no value or no object.
It implies no object,or null string,no valid boolean value,no number and no array object.
Q.What is the difference between null and undefined in javascript?
Ans - In JavaScript, undefined means a variable has been declared but has not yet been assigned a value, such as:
var TestVar;
alert(TestVar); //shows undefined
alert(typeof TestVar); //shows undefined
Where as null is an assignment value. It can be assigned to a variable as a representation of no value:
var TestVar = null;
alert(TestVar); //shows null
alert(typeof TestVar); //shows object
undefined and null are two distinct things: undefined is a type itself (undefined) while null is an object.
Q. What is triple equility (= = = ) in java script?
Ans - Triple equility means equality checking with out the type conversion, also known as strict equality check.
For strict equality check the objects being compared must have the same type also.
For example:
0 = = false // true
0 = = = false // false, because they are of a different type
1 = = "1" // true, auto type coersion
1 = = = "1" // false, because they are of a different type
Q. How to create arrays in JavaScript?
var scripts = new Array();
scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";
Now our array scrips has 4 elements inside it and we can print or access them by using their index number. Note that index number starts from 0. To get the third element of the array we have to use the index number 2 . Here is the way to get the third element of an array.
document.write(scripts[2]);
We also can create an array like this
var no_array = new Array(21, 22, 23, 24, 25);
Q. How do you target a specific frame from a hyperlink?
Include the name of the frame in the target attribute of the hyperlink. <a href=”mypage.htm” target=”myframe”>>My Page</a>
Include the name of the frame in the target attribute of the hyperlink. <a href=”mypage.htm” target=”myframe”>>My Page</a>
Q. Where are cookies actually stored on the hard disk?
This depends on the user's browser and OS.
In the case of Netscape with Windows OS,all the cookies are stored in a single file called
cookies.txt
c:\Program Files\Netscape\Users\username\cookies.txt
In the case of IE,each cookie is stored in a separate file namely username@website.txt.
c:\Windows\Cookies\username@Website.txt
This depends on the user's browser and OS.
In the case of Netscape with Windows OS,all the cookies are stored in a single file called
cookies.txt
c:\Program Files\Netscape\Users\username\cookies.txt
In the case of IE,each cookie is stored in a separate file namely username@website.txt.
c:\Windows\Cookies\username@Website.txt
Q. How to get the contents of an input box using Javascript?
Use the "value" property.
var myValue = window.document.getElementById("MyTextBox").value;
Use the "value" property.
var myValue = window.document.getElementById("MyTextBox").value;
Q. How to determine the state of a checkbox using Javascript?
var checkedP = window.document.getElementById("myCheckBox").checked;
var checkedP = window.document.getElementById("myCheckBox").checked;
Q. How to set the focus in an element using Javascript?
<script> function setFocus() { if(focusElement != null) { document.forms[0].elements["myelementname"].focus(); } } </script>
<script> function setFocus() { if(focusElement != null) { document.forms[0].elements["myelementname"].focus(); } } </script>
Q. How to access an external javascript file that is stored externally and not embedded?
This can be achieved by using the following tag between head tags or between body tags.
<script language='javascript' src='js/sqltohtml.js'></script>
This can be achieved by using the following tag between head tags or between body tags.
<script language='javascript' src='js/sqltohtml.js'></script>
Q. What is the difference between an alert box and a confirmation box?
An alert box displays only one button which is the OK button whereas the Confirm box displays two buttons namely OK and cancel. So from confirmation box we can get a response from user.
An alert box displays only one button which is the OK button whereas the Confirm box displays two buttons namely OK and cancel. So from confirmation box we can get a response from user.
Q. What is a prompt box?
A prompt box allows the user to enter input by providing a text box.
A prompt box allows the user to enter input by providing a text box.
Q. Can javascript code be broken in different lines?
Breaking is possible within a string statement by using a backslash \ at the end but not within any other javascript statement.
that is ,
document.write("Hello \ world");
is possible but not document.write \
("hello world");
Breaking is possible within a string statement by using a backslash \ at the end but not within any other javascript statement.
that is ,
document.write("Hello \ world");
is possible but not document.write \
("hello world");
Q. What is the difference between SessionState and ViewState?
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.
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.
Q. To put a "close window" link on a page ?
<a href='javascript:window.close()' class='mainnav'> Close </a>
<a href='javascript:window.close()' class='mainnav'> Close </a>
Q. How to comment javascript code?
Use // for line comments and
/*
*/ for block comments
Use // for line comments and
/*
*/ for block comments
Q. Name the numeric constants representing max,min values
Number.MAX_VALUE
Number.MIN_VALUE
Number.MAX_VALUE
Number.MIN_VALUE
Q. To set all checkboxes to true using JavaScript?
//select all input tags
function SelectAll()
//select all input tags
function SelectAll()
{
var checkboxes = document.getElementsByTagName("input");
for(i=0;i<checkboxes.length;i++)
var checkboxes = document.getElementsByTagName("input");
for(i=0;i<checkboxes.length;i++)
{
if(checkboxes.item(i).attributes["type"].value == "checkbox")
if(checkboxes.item(i).attributes["type"].value == "checkbox")
{
checkboxes.item(i).checked = true;
}
}
}
checkboxes.item(i).checked = true;
}
}
}
Q. What is variable typing in javascript?
It is perfectly legal to assign a number to a variable and then assign a string to the same variable as follows
example
i = 10;
i = "string";
This is called variable typing
It is perfectly legal to assign a number to a variable and then assign a string to the same variable as follows
example
i = 10;
i = "string";
This is called variable typing
Q. How to disable an HTML object ?
document.getElementById("myObject").disabled = true;
document.getElementById("myObject").disabled = true;
Q. To write messages to the screen without using "document.write()" ?
Changing the contents of an element is a much better solution. When the method showStatus is invoked it will change the content of the span.
...
function showStatus(message) {
var element = document.getElementById("mystatus");
element.textContent = message; //for Firefox
element.innerHTML = message; //for IE (why can't we all just get along?)
return true;
}
...
<span id="mystatus">Test. </span>
...
Changing the contents of an element is a much better solution. When the method showStatus is invoked it will change the content of the span.
...
function showStatus(message) {
var element = document.getElementById("mystatus");
element.textContent = message; //for Firefox
element.innerHTML = message; //for IE (why can't we all just get along?)
return true;
}
...
<span id="mystatus">Test. </span>
...
Q. How to Add new elements dynamically ?
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>t1</title>
<script type="text/javascript">
function addNode() {
var newP = document.createElement("p");
var textNode = document.createTextNode(" I'm a new text node");
newP.appendChild(textNode);
document.getElementById("firstP").appendChild(newP);
}
</script>
</head>
<body onload="addNode();" style=" background: url('../images/Sand-1280.jpg'); background-color: yellow;">
<p id="firstP">firstP<p>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>t1</title>
<script type="text/javascript">
function addNode() {
var newP = document.createElement("p");
var textNode = document.createTextNode(" I'm a new text node");
newP.appendChild(textNode);
document.getElementById("firstP").appendChild(newP);
}
</script>
</head>
<body onload="addNode();" style=" background: url('../images/Sand-1280.jpg'); background-color: yellow;">
<p id="firstP">firstP<p>
</body>
</html>
Q. How to create a popup warning boxalert('Warning: Please enter an integer between 0 and 100.');
Q. How to create a confirmation box?
confirm("Do you really want to launch the missile?");
confirm("Do you really want to launch the missile?");
Q. How to create an input box?
prompt("What is your temperature?");
prompt("What is your temperature?");
Q. How to make elements invisible ?
Change the "visibility" attribute of the style object associated with your element. Remember that a hidden element still takes up space, use "display" to make the space disappear as well.
if ( x == y) {
myElement.style.visibility = 'visible';
} else {
myElement.style.visibility = 'hidden';
}
Change the "visibility" attribute of the style object associated with your element. Remember that a hidden element still takes up space, use "display" to make the space disappear as well.
if ( x == y) {
myElement.style.visibility = 'visible';
} else {
myElement.style.visibility = 'hidden';
}
Q. How to set the cursor to wait ?
In theory, we should cache the current state of the cursor and then put it back to its original state.
document.body.style.cursor = 'wait';
//do something interesting and time consuming
document.body.style.cursor = 'auto';
In theory, we should cache the current state of the cursor and then put it back to its original state.
document.body.style.cursor = 'wait';
//do something interesting and time consuming
document.body.style.cursor = 'auto';
Q. How to reload the current page ?
window.location.reload(true);
window.location.reload(true);
Q. how to force a page to go to another page using JavaScript ?
<script language="JavaScript" type="text/javascript" ><!-- location.href="http://newhost/newpath/newfile.html"; //--></script>
<script language="JavaScript" type="text/javascript" ><!-- location.href="http://newhost/newpath/newfile.html"; //--></script>
Q. How to convert a string to a number using JavaScript?You can use the parseInt() and parseFloat() methods. Notice that extra letters following a valid number are ignored, which is kinda wierd but convenient at times.
parseInt("100") ==> 100
parseFloat("98.6") ==> 98.6
parseFloat("98.6 is a common temperature.") ==> 98.6
parseInt("aa") ==> Nan //Not a Number
parseInt("aa",16) ==> 170 //you can supply a radix or base
parseInt("100") ==> 100
parseFloat("98.6") ==> 98.6
parseFloat("98.6 is a common temperature.") ==> 98.6
parseInt("aa") ==> Nan //Not a Number
parseInt("aa",16) ==> 170 //you can supply a radix or base
Q. How to convert numbers to strings using JavaScript?
You can prepend the number with an empty string
var mystring = ""+myinteger;
or
var mystring = myinteger.toString();
You can specify a base for the conversion,
var myinteger = 14;
var mystring = myinteger.toString(16);
mystring will be "e".
You can prepend the number with an empty string
var mystring = ""+myinteger;
or
var mystring = myinteger.toString();
You can specify a base for the conversion,
var myinteger = 14;
var mystring = myinteger.toString(16);
mystring will be "e".
Q. What's Math Constants and Functions using JavaScript?
The Math object contains useful constants such as Math.PI, Math.E
Math.abs(value); //absolute value
Math.max(value1, value2); //find the largest
Math.random() //generate a decimal number between 0 and 1
Math.floor(Math.random()*101) //generate a decimal number between 0 and 100
The Math object contains useful constants such as Math.PI, Math.E
Math.abs(value); //absolute value
Math.max(value1, value2); //find the largest
Math.random() //generate a decimal number between 0 and 1
Math.floor(Math.random()*101) //generate a decimal number between 0 and 100
Q. What's the Date object using JavaScript?
Time inside a date object is stored as milliseconds since Jan 1, 1970.
new Date(06,01,02) // produces "Fri Feb 02 1906 00:00:00 GMT-0600 (Central Standard Time)"
new Date(06,01,02).toLocaleString() // produces "Friday, February 02, 1906 00:00:00"
new Date(06,01,02) - new Date(06,01,01) // produces "86400000"
Time inside a date object is stored as milliseconds since Jan 1, 1970.
new Date(06,01,02) // produces "Fri Feb 02 1906 00:00:00 GMT-0600 (Central Standard Time)"
new Date(06,01,02).toLocaleString() // produces "Friday, February 02, 1906 00:00:00"
new Date(06,01,02) - new Date(06,01,01) // produces "86400000"
Q. How to use "join()" to create a string from an array using JavaScript?
"join" concatenates the array elements with a specified seperator between them.
<script type="text/javascript">
var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"];
document.write("days:"+days.join(","));
</script>
This produces
days:Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
"join" concatenates the array elements with a specified seperator between them.
<script type="text/javascript">
var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"];
document.write("days:"+days.join(","));
</script>
This produces
days:Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
Q. eval()?
The eval() method is incredibly powerful allowing you to execute snippets of code during execution.
<script type="text/javascript">
var USA_Texas_Austin = "521,289";
document.write("Population is "+eval("USA_"+"Texas_"+"Austin"));
</script>
This produces
Population is 521,289
The eval() method is incredibly powerful allowing you to execute snippets of code during execution.
<script type="text/javascript">
var USA_Texas_Austin = "521,289";
document.write("Population is "+eval("USA_"+"Texas_"+"Austin"));
</script>
This produces
Population is 521,289
Q. How to create a function using function constructor?
It creates a function called square with argument x and returns x multiplied by itself.
var square = new Function ("x","return x*x");
It creates a function called square with argument x and returns x multiplied by itself.
var square = new Function ("x","return x*x");
Q. unescape(), escape()
These are similar to the decodeURI() and encodeURI(), but escape() is used for only portions of a URI.
<script type="text/javascript">
var myvalue = "Sir Walter Scott";
document.write("Original myvalue: "+myvalue);
document.write("<br />escaped: "+escape(myvalue));
document.write("<br />uri part: \"&author="+escape(myvalue)+"\"");
</script>
If you use escape() for the whole URI... well bad things happen.
<script type="text/javascript">
var uri = "http://www.google.com/search?q=sonofusion Taleyarkhan"
document.write("Original uri: "+uri);
document.write("
escaped: "+escape(uri));
v/script>
These are similar to the decodeURI() and encodeURI(), but escape() is used for only portions of a URI.
<script type="text/javascript">
var myvalue = "Sir Walter Scott";
document.write("Original myvalue: "+myvalue);
document.write("<br />escaped: "+escape(myvalue));
document.write("<br />uri part: \"&author="+escape(myvalue)+"\"");
</script>
If you use escape() for the whole URI... well bad things happen.
<script type="text/javascript">
var uri = "http://www.google.com/search?q=sonofusion Taleyarkhan"
document.write("Original uri: "+uri);
document.write("
escaped: "+escape(uri));
v/script>
Q. decodeURI(), encodeURI() Many characters cannot be sent in a URL, but must be converted to their hex encoding. These functions are used to convert an entire URI (a superset of URL) to and from a format that can be sent via a URI.
<script type="text/javascript">
var uri = "http://www.google.com/search?q=sonofusion Taleyarkhan"
document.write("Original uri: "+uri);
document.write("<br />encoded: "+encodeURI(uri));
</script>
<script type="text/javascript">
var uri = "http://www.google.com/search?q=sonofusion Taleyarkhan"
document.write("Original uri: "+uri);
document.write("<br />encoded: "+encodeURI(uri));
</script>
Are Java and JavaScript the same?
NO!
Java and JavaScript are two completely different languages in both concept and design!
Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in the same category as C and C++.
What are the benifits of Javascript as a Client side script?
•JavaScript can manipulate HTML elements - A JavaScript can read and change the content of an HTML element
•JavaScript can be used to validate data - A JavaScript can be used to validate form input
•JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser
•JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve information on the visitor's computer
The HTML <script> tag is used to insert a JavaScript into an HTML document.
The HTML "id" attribute is used to identify HTML elements.
You can place an unlimited number of scripts in your document, and you can have scripts in both the body and the head section at the same time.
It is a common practice to put all functions in the head section, or at the bottom of the page. This way they are all in one place and do not interfere with page content.
Using an External JavaScript - JavaScript can also be placed in external files.
External JavaScript files often contain code to be used on several different web pages.
External JavaScript files have the file extension .js.
Note: External script cannot contain the <script></script> tags!
To use an external script, point to the .js file in the "src" attribute of the <script> tag:
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" src="myScript.js"></script>
</body>
</html>
JavaScript Statements - A JavaScript statement is a command to a browser. The purpose of the command is to tell the browser what to do.
This JavaScript statement tells the browser to write "Hello Dolly" to an HTML element:
document.getElementById("demo").innerHTML="Hello Dolly";
It is normal to add a semicolon at the end of each executable statement. The semicolon is optional (according to the JavaScript standard), and the browser is supposed to interpret the end of the line as the end of the statement. Because of this you will often see examples without the semicolon at the end.
Note: Using semicolons makes it possible to write multiple statements on one line.
JavaScript Variables - Variables are "containers" for storing information.
Rules for JavaScript variable names:
•Variable names are case sensitive (y and Y are two different variables)
•Variable names must begin with a letter, the $ character, or the underscore character
You declare JavaScript variables with the var keyword:
var carname;
To assign a value to the variable, use the equal (=) sign:
carname="Volvo";
However, you can also assign a value to the variable when you declare it:
var carname="Volvo";
Local JavaScript Variables - A variable declared within a JavaScript function becomes LOCAL and can only be accessed within that function. (the variable has local scope).
Local variables are deleted as soon as the function is completed.
Global JavaScript Variables - Variables declared outside a function, become GLOBAL, and all scripts and functions on the web page can access it.
Global variables are deleted when you close the page.
If you assign values to variables that have not yet been declared, the variables will automatically be declared as global variables.
This statement:
carname="Volvo";
will declare the variable carname as a global variable (if it does not already exist).
Equality Check in JavaScript – We have two operators (= =, = = = ) for equality check.
= = is used only for equality checking of of values for two operands.
Var x = 5
X= =8 will evaluate to false.
X= =5 will evaluate to true
= = = is used for checking the equality of values for both operant as well the type of the operand, so both must be from same type (value and type)
X= = ="5" will evaluate to false, because x is having number where as we are comparing with string.
X= = =5 will evaluate to true
JavaScript If...Else Statements - In JavaScript we have the following conditional statements:
•if statement - use this statement to execute some code only if a specified condition is true
•if...else statement - use this statement to execute some code if the condition is true and another code if the condition is false
•if...else if....else statement - use this statement to select one of many blocks of code to be executed
•switch statement - use this statement to select one of many blocks of code to be executed
if (condition)
{
code to be executed if condition is true
}
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
JavaScript Popup Boxes - JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.
Alert Box - An alert box is often used if you want to make sure information comes through to the user.
When an alert box pops up, the user will have to click "OK" to proceed.
Syntax is :
alert("sometext");
Confirm Box - A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.
Syntax is :
confirm("sometext");
Example
var r=confirm("Press a button");
if (r==true)
{
x="You pressed OK!";
}
else
{
x="You pressed Cancel!";
}
Prompt Box - A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.
Syntax is :
prompt("sometext","defaultvalue");
Example
var name=prompt("Please enter your name","Harry Potter");
if (name!=null && name!="")
{
x="Hello " + name + "! How are you today?";
}
To display line breaks inside a popup box, use a back-slash followed by the character n.
Example
alert("Hello\nHow are you?");
JavaScript Functions - A function is a block of code that executes only when you tell it to execute.
It can be when an event occurs, like when a user clicks a button, or from a call within your script, or from a call within another function.
Functions can be placed both in the <head> and in the <body> section of a document, just make sure that the function exists, when the call is made.
Function with Arguments
function myFunction(var1,var2)
{
some code
}
Functions With a Return Value
function myFunction()
{
var x=5;
return x;
}
The for Loop - The for loop is used when you know in advance how many times the script should run.
Syntax
for (variable=startvalue;variable<endvalue;variable=variable+increment)
{
code to be executed
}
Note: The increment parameter could also be negative, and the < could be any comparing statement.
Example
for (i=0; i<5; i++)
{
x=x + "The number is " + i + "<br />";
}
The while Loop - The while loop loops through a block of code while a specified condition is true.
Syntax
while (variable<endvalue)
{
code to be executed
}Note: The < could be any comparing operator.
Example
while (i<5)
{
x=x + "The number is " + i + "<br />";
i++;
}
The do...while Loop - The do...while loop is a variant of the while loop. This loop will execute the block of code once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
Syntax
do
{
code to be executed
}
while (variable<endvalue);Example
The example below uses a do...while loop. The do...while loop will always be executed at least once, even if the condition is false, because the statements are executed before the condition is tested:
Example
do
{
x=x + "The number is " + i + "<br />";
i++;
}
while (i<5);
The break Statement
The break statement will break the loop and continue executing the code that follows after the loop (if any).
Example
for (i=0;i<10;i++)
{
if (i==3)
{
break;
}
x=x + "The number is " + i + "<br />";
}
The continue Statement
The continue statement will break the current iteration and continue the loop with the next value.
Example
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
}
x=x + "The number is " + i + "<br />";
}
JavaScript For...In Statement - The for...in statement loops through the properties of an object.
Syntax
for (variable in object)
{
code to be executed
}Note: The block of code inside of the for...in loop will be executed once for each property.
Example
Looping through the properties of an object:
Example
var person={fname:"John",lname:"Doe",age:25};
for (x in person)
{
txt=txt + person[x];
}
Events - By using JavaScript, we have the ability to create dynamic web pages. Events are actions that can be detected by JavaScript.
Every element on a web page has certain events which can trigger a JavaScript. For example, we can use the onClick event of a button element to indicate that a function will run when a user clicks on the button. We define the events in the HTML tags.
Examples of events:
•A mouse click
•A web page or an image loading
•Mousing over a hot spot on the web page
•Selecting an input field in an HTML form
•Submitting an HTML form
•A keystroke
Note: Events are normally used in combination with functions, and the function will not be executed before the event occurs!
onLoad and onUnload -The onLoad and onUnload events are triggered when the user enters or leaves the page.
The onLoad event is often used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.
Both the onLoad and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page. For example, you could have a popup asking for the user's name upon his first arrival to your page. The name is then stored in a cookie. Next time the visitor arrives at your page, you could have another popup saying something like: "Welcome John Doe!".
onFocus, onBlur and onChange - The onFocus, onBlur and onChange events are often used in combination with validation of form fields.
Below is an example of how to use the onChange event. The checkEmail() function will be called whenever the user changes the content of the field:
<input type="text" size="30" id="email" onchange="checkEmail()" />
OnSubmit - The onSubmit event is used to validate ALL form fields before submitting it.
Below is an example of how to use the onSubmit event. The checkForm() function will be called when the user clicks the submit button in the form. If the field values are not accepted, the submit should be cancelled. The function checkForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled:
<form method="post" action="xxx.htm" onsubmit="return checkForm()">
OnMouseOver - The onmouseover event can be used to trigger a function when the user mouses over an HTML element:
JavaScript Try...Catch Statement
The try...catch statement allows you to test a block of code for errors. The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs.
Syntax
try
{
//Run some code here
}
catch(err)
{
//Handle errors here
}
function message()
{
try
{
adddlert("Welcome guest!");
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.message + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
}
}
The Throw Statement
The throw statement allows you to create an exception. If you use this statement together with the try...catch statement, you can control program flow and generate accurate error messages.
Syntax
throw exception
The exception can be a string, integer, Boolean or an object.
<script type="text/javascript">
var x=prompt("Enter a number between 5 and 10:","");
try
{
if(x>10)
{
throw "Err1";
}
else if(x<5)
{
throw "Err2";
}
else if(isNaN(x))
{
throw "Err3";
}
}
catch(err)
{
if(err=="Err1")
{
document.write("Error! The value is too high.");
}
if(err=="Err2")
{
document.write("Error! The value is too low.");
}
if(err=="Err3")
{
document.write("Error! The value is not a number.");
}
}
</script>
Insert Special Characters - The backslash (\) is used to insert apostrophes, new lines, quotes, and other special characters into a text string.
var txt="We are the so-called \"Vikings\" from the north.";
Break up a Code Line
You can break up a code line within a text string with a backslash. The example below will be displayed properly:
document.write("Hello \
World!");However, you cannot break up a code line like this:
document.write \
("Hello World!");
Object Based Programming - JavaScript is an Object Based Programming language, and allows you to define your own objects and make your own variable types.
An object has properties and methods.
Properties are the values associated with an object.
In the following example we are using the length property of the String object to return the number of characters in a string:
<script type="text/javascript">
var txt="Hello World!";
document.write(txt.length);
</script>
Methods are the actions that can be performed on objects.
In the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters:
<script type="text/javascript">
var str="Hello world!";
document.write(str.toUpperCase());
</script>
String object - The String object is used to manipulate a stored piece of text.
The following example uses the length property of the String object to find the length of a string:
var txt="Hello world!";
document.write(txt.length);
The following example uses the toUpperCase() method of the String object to convert a string to uppercase letters:
var txt="Hello world!";
document.write(txt.toUpperCase());
var str=document.getElementById("demo").innerHTML;
var n=str.replace("Microsoft","W3Schools");
document.getElementById("demo").innerHTML=n;
function myFunction()
{
var str="Hello world, welcome to the universe.";
var n=str.indexOf("welcome");
document.getElementById("demo").innerHTML=n;
}
Date Object - The Date object is used to work with dates and times.
There are four ways of initiating a date:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Use getFullYear() to get the year, as :
var d = new Date();
alert(d.getFullYear());
getTime() returns the number of milliseconds since 01.01.1970.
var d = new Date();
alert(d.getTime());
use setFullYear() to set a specific date.
var d = new Date();
d.setFullYear(2020,10,3);
This will set the date as :Tue Nov 3 11:31:49 UTC+0530 2020
Compare Two Dates
The Date object is also used to compare two dates.
The following example compares today's date with the 14th January 2100:
var x=new Date();
x.setFullYear(2100,0,14);
var today = new Date();
if (x>today)
{
alert("Today is before 14th January 2100");
}
else
{
alert("Today is after 14th January 2100");
}
Array Object - The Array object is used to store multiple values in a single variable.
An array can be defined in three ways.
1:
var myCars=new Array(); // regular array (add an optional integer
myCars[0]="Saab"; // argument to control array's size)
myCars[1]="Volvo";
myCars[2]="BMW";2:
var myCars=new Array("Saab","Volvo","BMW"); // condensed array3:
var myCars=["Saab","Volvo","BMW"]; // literal arrayNote: If you specify numbers or true/false values inside the array then the variable type will be Number or Boolean, instead of String.
You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0.
document.write(myCars[0]);
Join two or more arrays with CONCAT():
var hege = ["Cecilie", "Lone"];
var stale = ["Emil", "Tobias", "Linus"];
var kai = ["Robin"];
var children = hege.concat(stale,kai);
Remove the last element of an array - pop()
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();
Add new elements to the end of an array - push()
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi")
Reverse the order of the elements in an array - reverse()
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.reverse();
Then the order will be : Mango,Apple,Orange,Banana
Sort an array (alphabetically and ascending) - sort()
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
Sort numbers (numerically and ascending) - sort()
var points = [40,100,1,5,25,10];
points.sort(function(a,b){return a-b});
Sort numbers (numerically and descending) - sort()
var points = [40,100,1,5,25,10];
points.sort(function(a,b){return b-a});
Add an element to position 2 in an array - splice()
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2,0,"Lemon","Kiwi");
Boolean Object - The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false).
The following code creates a Boolean object called myBoolean:
var myBoolean=new Boolean();If the Boolean object has no initial value, or if the passed value is one of the following:
•0
•-0
•null
•""
•false
•undefined
•NaN
the object is set to false. For any other value it is set to true (even with the string "false")!
Math Object - The Math object allows you to perform mathematical tasks.
Syntax for using properties/methods of Math:
var x=Math.PI;
var y=Math.sqrt(16);
Note: Math is not a constructor. All properties and methods of Math can be called by using Math as an object without creating it.
Constants: You may reference these constants from your JavaScript like this:
Math.E
Math.PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E
Mathematical Methods:
Math.round()
random()
max() example Math.max(5,10;
min()
RegExp Object - RegExp, is short for regular expression.
A regular expression is an object that describes a pattern of characters.
Regular expressions are used to perform powerful pattern-matching and "search-and-replace" functions on text.
Syntax
var patt=new RegExp(pattern,modifiers);
or more simply:
var patt=/pattern/modifiers;
•pattern specifies the pattern of an expression
•modifiers specify if a search should be global, case-sensitive, etc.
The i modifier is used to perform case-insensitive matching.
The g modifier is used to perform a global match (find all matches rather than stopping after the first match).
Example 1
Do a case-insensitive search for "w3schools" in a string:
var str = "Visit W3Schools";
var patt1 = /w3schools/i;
document.write(str.match(patt1));
Result will be:
W3Schools
test()
The test() method searches a string for a specified value, and returns true or false, depending on the result.
The following example searches a string for the character "e":
Example
var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));Since there is an "e" in the string, the output of the code above will be:
true
exec()
The exec() method searches a string for a specified value, and returns the text of the found value. If no match is found, it returns null.
The following example searches a string for the character "e":
Example 1
var patt1=new RegExp("e");
document.write(patt1.exec("The best things in life are free"));Since there is an "e" in the string, the output of the code above will be:
e
JavaScript Cookies - A cookie is a variable that is stored on the visitor's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With JavaScript, you can both create and retrieve cookie values.
create a function that stores the name of the visitor in a cookie variable:
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}