SlideShare a Scribd company logo
Introduction
JavaScript is a object-based scripting language and it is light weighted. It is first implemented by
Netscape (with help from Sun Microsystems). JavaScript was created by Brendan Eich at
Netscape in 1995 for the purpose of allowing code in web-pages (performing logical operation on
client side).
It is not compiled but translated. JavaScript Translator is responsible to translate the JavaScript
code which is embedded in browser.
Netscape first introduced a JavaScript interpreter in Navigator 2. The interpreter was an extra
software component in the browser that was capable of interpreting JavaSript source code inside
an HTML document. This means that web page developer no need other software other than a text
editor of develop any web page.
Why we Use JavaScript?
Using HTML we can only design a web page but you can not run any logic on web browser like
addition of two numbers, check any condition, looping statements (for, while), decision making
statement (if-else) at client side. All these are not possible using HTML So for perform all these
task at client side you need to use JavaScript.
Where it is used?
It is used to create interactive websites. It is mainly used for:
 Client-side validation
 Dynamic drop-down menus
 Displaying data and time
 Build small but complete client side programs .
 Displaying popup windows and dialog boxes (like alert dialog box, confirm dialog box
and prompt dialog box)
 Displaying clocks etc.
History
JavaScript is a object-based scripting language and it is light weighted. It is first implemented
by Netscape (with help from Sun Microsystems). JavaScript was created by Brendan Eich at
Netscape in 1995 for the purpose of allowing code in web-pages (performing logical operation on
client side).
Using HTML we can only design a web page but you can not run any logic on web browser like
addition of two numbers, check any condition, looping statements(for, while), decision making
statement(if-else) etc. All these are not possible using HTML so for perform all these task we use
JavaScript.
Using HTML we can only design a web page if we want to run any programs like c programming
we use JavaScript. Suppose we want to printsum oftwo number then we use JavaScript for coding.
Features of JavaScript
JavaScript is a client side technology, it is mainly used for gives client side validation, but it have
lot of features which are given below;
 JavaScript is a object-based scripting language.
 Giving the user more control over the browser.
 It Handling dates and time.
 It Detecting the user's browser and OS,
 It is light weighted.
 JavaScript is a scripting language and it is not java.
 JavaScript is interpreter based scripting language.
 JavaScript is case sensitive.
 JavaScript is object based language as it provides predefined objects.
 Every statement in javascript must be terminated with semicolon (;).
 Most of the javascript control statements syntax is same as syntax of control
statements in C language.
 An important part of JavaScript is the ability to create new functions within scripts.
Declare a function in JavaScript using function keyword.
Uses of JavaScript
There are too many web applications running on the web that are using JavaScript technology like
gmail, facebook,twitter, google map, youtube etc.
Uses of JavaScript
 Client-side validation
 Dynamic drop-down menus
 Displaying data and time
 Validate user input in an HTML form before sending the data to a server.
 Build forms that respond to user input without accessing a server.
 Change the appearance of HTML documents and dynamically write HTML into
separate Windows.
 Open and close new windows or frames.
 Manipulate HTML "layers" including hiding, moving, and allowing the user to drag
them around a browser window.
 Build small but complete client side programs .
 Displaying popup windows and dialog boxes (like alert dialog box, confirm dialog box
and prompt dialog box)
 Displaying clocks etc.
Comment
Comment is nothing but it is a statement which is not display on browser window. it is useful to
understand the which code is written for what purpose.
Comments are useful in every programming language to deliver message. It is used to add
information about the code, warnings or suggestions so that the end user or other developer can
easily interpret the code.
Types of JavaScript Comments
There are two types of comments are in JavaScript
 Single-line Comment
 Multi-line Comment
Single-line Comment
It is represented by double forward slashes (//). It can be used before any statement.
Example
<script>
// It is single line comment
document.write("Hello Javascript");
</script>
Result
Hello Javascript
Multi-line Comment
It can be used to add single as well as multi line comments.
It is represented by forward slash (/) with asterisk (*) then asterisk with forward slash.
Example
<script>
/* It is multi line comment.
It will not be displayed */
document.write("Javascript multiline comment");
</script>
JavaScript First Program
Javascript simple example to verify age of any person, if age is greater than 18 show message
adult otherwise show under 18
JavaScript Example to verify age
Example
<html>
<head>
<script>
function verify(){
var no;
no=Number(document.getElementById("age").value);
if(no<18)
{
alert("Under 18");
}
else
{
alert("You are Adult");
}
}
</script>
</head>
<body>
Enter your age:<input id="age"><br />
<button onclick="verify()">Click me</button>
</body>
</html>
Result
Enter your age:
Click me
Way of Using JavaScript
There are three places to put the JavaScript code.
 Between the <body> </body> tag of html (Inline JavaScript)
 Between the <head> </head> tag of html (Internal JavaScript)
 In .js file (External JavaScript)
Inline JavaScript
When java script was written within the html element using attributes related to events of the
element then it is called as inline java script.
Example of Inline JavaScript
Example
<html>
<form>
<input type="button" value="Click" onclick="alert('Button Clicked')"/>
</form>
</html>
Result
Internal JavaScript
When java script was written within the section using element then it is called as internaljava script.
Example of Internal JavaScript
Example
<html>
<head>
<script>
function msg()
{
alert("Welcome in JavaScript");
}
</script>
</head>
<form>
<input type="button" value="Click" onclick="msg()"/>
</form>
</html>
Result
External JavaScript
Writing java script in a separate file with extension .js is called as external java script. For adding
the reference of an external java script file to your html page, use tag with src attribute as follows
Example
<script type="text/javascript" src="filename.js"/>
Create a file with name functions.js and write the following java script functions in it.
message.js
Example
function msg()
{
alert("Hello Javatpoint");
}
Create a html page and use the file functions.js as follows
index.html
Example
<html>
<head>
<script type="text/javascript" src="message.js"></script>
</head>
<body>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
Result
Variable Declaration
Java script did not provide any data types for declaring variables and a variable in java script can
store any type of value. Hence java script is loosely typed language. We can use a variable directly
without declaring it.
Only var keyword are use before variable name to declare any variable.
Syntax
var x;
Rules to declaring a variable
 Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
 After first letter we can use digits (0 to 9), for example value1.
 Javascript variables are case sensitive, for example x and X are different variables.
Variable declaration
Example
var x = 10; // Valid
var _value="porter"; // Valid
var 123=20; // Invalid
var #a=220; // Invalid
var *b=220; // Invalid
Example of Variable declaration in JavaScript
Example
<script>
var a=10;
var b=20;
var c=a+b;
document.write(c);
</script>
Output
30
Types of Variable in JavaScript
 Local Variable
 Global Variable
Local Variable
A variable which is declared inside block or function is called local variable. It is accessible within
the function or block only. For example:
Example
<script>
function abc()
{
var x=10; //local variable
}
</script>
or
Example
<script>
If(10<13)
{
var y=20;//javascript local variable
}
</script>
Global Variable
A global variable is accessible from any function. A variable i.e. declared outside the function or
declared with window object is known as global variable. For example:
Syntax
<script>
var value=10;//global variable
function a()
{
alert(value);
}
function b()
{
alert(value);
}
</script>
Declaring global variable through window object
The best way to declare global variable in javascript is through the window object. For example:
Syntax
window.value=20;
Now it can be declared inside any function and can be accessed from any function. For example:
Example
function m()
{
window.value=200; //declaring global variable by window object
}
function n()
{
alert(window.value); //accessing global variable from other function
}
Example of JavaScript
Here i will show you how to write you first javascript code, you only need to write your javascript
code inside <script> ..... </script> tag using any editor like notepad or edit plus. Save below code
with .html or .htm extension. No need to compile your javascript code just open your code in any
web browser.
Find sum of two number using JavaScript
Example
<!doctype html>
<html>
<head>
<script>
function add(){
var a,b,c;
a=Number(document.getElementById("first").value);
b=Number(document.getElementById("second").value);
c= a + b;
document.getElementById("answer").value= c;
}
</script>
</head>
<body>
<input id="first">
<input id="second">
<button onclick="add()">Add</button>
<input id="answer">
</body>
</html>
Result
Enter First Number:
Enter Second Number:
Add
Code Explanation
 no=Number(document.getElementById("first").value);
This code is used for receive first input value form input field which have id first.
 no=Number(document.getElementById("second").value);
This code is used for receive first input value form input field which have id second.
 document.getElementById("answer").value= fact;
This code is used for receive calculated value of factorial and display in input field
which have id answer
 <button onclick="add()">Add</button>
This code is used for call add function when button clicked.
Find Factorial of number in JavaScript
Using javascript you can find factorial of any number, here same logic are applied like c language
you only need to write your javascript code inside <script> ..... </script> tag using any editor like
notepad or edit plus. Save below code with .html or .htm extension. No need to compile your
javascript code just open your code in any web browser.
Find factorial of number using JavaScript
Example Factorial of any number
<!doctype html>
<html>
<head>
<script>
function show(){
var i, no, fact;
fact=1;
no=Number(document.getElementById("num").value);
for(i=1; i<=no; i++)
{
fact= fact*i;
}
document.getElementById("answer").value= fact;
}
</script>
</head>
<body>
Enter Num: <input id="num">
<button onclick="show()">Factorial</button>
<input id="answer">
</body>
</html>
Result
Enter Num: Factorial
Code Explanation
 no=Number(document.getElementById("num").value);
This code is used for receive input value form input field which have id num.
 document.getElementById("answer").value= fact;
This code is used for receive calculated value of factorial and display in input field
which have id answer
 <button onclick="show()">Factorial</button>
This code is used for call show function when button clicked.
If else Statement
The if statement is used in JavaScript to execute the code if condition is true or false. There are
three forms of if statement.
 If Statement
 If else statement
 if else if statement
JavaScript If statement
if is most basic statement of Decision making statement. It tells to program to execute a certain
part of code only if particular condition or test is true.
Syntax
Syntax
if(expression)
{
//set of statements
}
Example
<script>
var a=10;
if(a>5)
{
document.write("value of a is greater than 5");
}
</script>
JavaScript if-else statement
In general it can be used to execute one block of statement among two blocks.
Syntax
if(expression)
{
//set of statements
}
else
{
//set of statements
}
Example of if..else statement
<script>
var a=40;
if(a%2==0)
{
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
Result
a is even number
JavaScript If...else if statement
It evaluates the content only if expression is true from several expressions.
Syntax
if(expression1)
{
//content to be evaluated if expression1 is true
}
else if(expression2)
{
//content to be evaluated if expression2 is true
}
else
{
//content to be evaluated if no expression is true
}
Example of if..else if statement
<script>
var a=40;
if(a==20)
{
document.write("a is equal to 20");
}
else if(a==5)
{
document.write("a is equal to 5");
}
else if(a==30)
{
document.write("a is equal to 30");
}
else
{
document.write("a is not equal to 20, 5 or 30");
}
</script>
Looping Statement in
Set of instructions given to the compiler to execute set of statements until condition becomes false
is called loops. The basic purpose of loop is code repetition.
The way of the repetition will be forms a circle that's why repetition statements are called loops.
Some loops are available In JavaScript which are given below.
 while loop
 for loop
 do-while
while loop
When we are working with while loop always pre-checking process will be occurred. Pre-checking
process means before evolution of statement block condition part will be executed. While loop will
be repeats in clock wise direction.
Syntax
while (condition)
{
code block to be executed
}
Example of while loop
<script>
var i=10;
while (i<=13)
{
document.write(i + "<br/>");
i++;
}
</script>
Result
10
11
12
13
do-while loop
In implementation when we need to repeat the statement block at least 1 then go for do-while. In
do-while loop post checking of the statement block condition part will be executed.
syntax
do
{
code to be executed
increment/decrement
}
while (condition);
Example of do-while loop
Example
<script>
var i=11;
do{
document.write(i + "<br/>");
i++;
}while (i<=15);
</script>
Result
11
12
13
14
15
for Loop
For loop is a simplest loop first we initialized the value then check condition and then increment
and decrements occurred.
Steps of for loop
Syntax
for (initialization; condition; increment/decrement)
{
code block to be executed
}
Example of for loop
Example
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
Switch Statement
The switch statement is used in JavaScript to execute one code from multiple expressions.
Example
switch(expression)
{
case value1:
statement;
break;
case value2:
statement;
break;
......
default:
statement;
}
Note: default code to be executed if above values are not matched
Note: in switch statement all the cases will be evaluated if we do not use break statement.
Example of switch statement in javascript.
Example
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>
Result
Output: B Grade
Example of switch case in javascript
Example
<html>
<head>
<script>
function myFunction()
{
var day;
day=Number(document.getElementById("first").value);
switch (day)
{
case 1:
day = "Sunday";
break;
case 2:
day = "Monday";
break;
case 3:
day = "Tuesday";
break;
case 4:
day = "Wednesday";
break;
case 5:
day = "Thursday";
break;
case 6:
day = "Friday";
break;
case 7:
day = "Saturday";
break;
default:
day="Enter valid number"
}
document.getElementById("demo").innerHTML =day;
}
</script>
</head>
<body>
<p>Enter any number (1 to 7):</p>
<input id="first">
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>
Result
Enter any number (1 to 7):
Try it
Function
An important part of JavaScript is the ability to create new functions within <script> and </script>
tag. Declare a function in JavaScript using function keyword. The keyword function precedes the
name of the function.
Syntax
function functionName(parameter or not)
{
.........
.........
}
Example of JavaScript using Function
Example
<html>
<head>
<script>
function getname()
{
name=prompt("Enter Your Name");
alert("Welcome Mr/Mrs " + name);
}
</script>
</head>
<form>
<input type="button" value="Click" onclick="getname()"/>
</form>
</html>
Example
Array in JavaScript
Array are used to represents the group of elements into a single unit or consecutive memory
location. Each and every element what we are entering into the array is going to be stored in the
array with the unique index starting from zero. Through the indexes we can store the data or
elements into the array or we can get the elements from the array.
To declare an array in javascript we need new keyword. To create an array you use new Array(n)
where n was the number of slots in the array or new Array() omitting the size of an array.
Note: Whenever we create any array in javaScript without specifying the size then it well create
array object with the zero size.
Syntax
myarray = new array(5);
Example of array in JavaScript
Example
<html>
<head>
<script type="text/javascript">
function arrayex()
{
myarray = new Array(5)
myarray[0] = 10
myarray[1] = 20
myarray[2] = 30
myarray[3] = 40
myarray[4] = 50
sum = 0;
for (i=0; i<myarray.length; i++)
{
sum = sum + myarray[i];
}
alert(sum)
}
</script>
</head>
<body>
<input type="button" onclick="arrayex()" value="click here">
</body>
</html>
Result
Function used in Array
Here we will discussabout some functionswhich are frequentlyused in arrayconceptin JavaScript.
Function Discription
concat()
To concats the elements of one array at the end of another array and returns an
array.
sort() To sort all elements of an array.
reverse() To reverse elements of an array.
slice()
To extract specified number of elements starting from specified index without
deleting them from array.
splice()
It will extract specified number of elements starting from specified index and deletes
them from array.
push() To push all elements in array at top.
pop() To pop the top elements from array.
JavaScript Dialog box
All JavaScript dialog box is a predefined function which is used for to perform different-different
task. Some function are given below;
function Discription
alert() To give alert message to user.
prompt() To input value from used.
confirm() To get confirmation from user before executing some task.
Alert()
Alert function of java script is used to give an alert message to the user.
Alert function example
Example
<!doctype html>
<html>
<head>
<script>
function alertmsg()
{
alert("Alert function call");
}
</script>
</head>
<form>
<input type="button" value="Click Me" onclick="alertmsg()"/>
</form>
</html>
Result
prompt()
Prompt function of java script is used to get input from the user.
prompt() function example
Example
<!doctype html>
<html>
<head>
<script>
function alertmsg()
{
a=prompt("Enter your name:");
alert(a);
}
</script>
</head>
<form>
<input type="button" value="Click Me" onclick="alertmsg()"/>
</form>
</html>
Result
confirm()
confirm function of java script is used to get confirmation from user before executing some task.
confirm() function example
Example
<!doctype html>
<html>
<head>
<script>
function alertmsg()
{
a=prompt("Enter your name:");
confirm(a);
}
</script>
</head>
<form>
<input type="button" value="Click Me" onclick="alertmsg()"/>
</form>
</html>
Result
Window Object
The window object represents a windowin browser. An object of window is created automatically
by the browser.
Window is the object of browser, it is not the object of javascript. The javascript objects are string,
array, date etc. It is used to display the popup dialog box such as alert dialog box, confirm dialog
box, input dialog box etc.
The window methods are mainly for opening and closing new windows. The following are the main
window methods. They are:
Methods of window object
Method Description
alert() displays the alert box containing message with ok button.
confirm() Displays the confirm dialog box containing message with ok and cancel button.
prompt() Displays a dialog box to get input from the user.
open() Opens the new window.
close() Closes the current window.
setTimeout()
Performs action after specified time like calling function, evaluating expressions
etc.
Document Object
The document object represents the whole html document. When html document is loaded in the
browser, it becomes a document object. It is the root element that represents the html document.
Methods of document object
Method Description
write("string") writes the given string on the document.
writeln("string")
Same as write(), but adds a newline character after each
statement.
getElementById() returns the element having the given id value.
getElementsByName() returns all the elements having the given name value.
getElementsByTagName() returns all the elements having the given tag name.
getElementsByClassName() returns all the elements having the given class name.
Event in JavaScript
All objects have properties and methods. In addition, some objects also have "events". Events are
things that happen, usually user actions, that are associated with an object. The "event handler" is
a command that is used to specify actions in response to an event. Below are some of the most
common events:
Event Discription
onLoad Occurs when a page loads in a browser
onUnload occurs just before the user exits a page
onMouseOver occurs when you point to an object
onMouseOut occurs when you point away from an object
onSubmit occurs when you submit a form
onClick occurs when an object is clicked
Events and Objects
Events are things that happen, actions, that are associated with an object. Below are some
common events and the object they are associaated with:
Event Object
onLoad Body
onUnload Body
onMouseOver Link, Button
onMouseOut Link, Button
onSubmit Form
onClick Button, Checkbox, Submit, Reset, Link
getElementById
The document.getElementById() method returns the element of specified id. In below example
we receive input from input field by using document.getElementById() method, here
document.getElementById() receive input value on the basis on input field id. In below example
"number" is the id of input field.
Example
<html>
<body>
<head>
<script type="text/javascript">
function squre()
{
var num=document.getElementById("number").value;
alert(num*num);
}
</script>
</head>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="squre" onclick="squre()"/>
</form>
</body>
</html>
Result
Enter No:
Code Explanation
var num=document.getElementById("number").value; In this code getElementById received
value from input field which have id number.
Square of any number in javascript
Example
<html>
<body>
<head>
<script type="text/javascript">
function squre()
{
var num=document.getElementById("number").value;
var result=num*num;
document.getElementById("answer").value=result;
}
</script>
</head>
<form>
Enter No:<input type="text" id="number" name="number"/>
<input type="button" value="squre" onclick="squre()"/>
<input id="answer"/>
</form>
</body>
</html>
Result
Enter No:
JavaScript Forms Validation
Forms validation is important things other wise user input wrong data, so we need to validate given
data by user before submit it on server.
The JavaScript provides the facility to validate the form on the client side so processing will be fast
than server-side validation. So, most of the web developers prefer client side form validation using
JavaScript.
Here i will show you how to validate any input field like user name can not be blank. In below
example input are can not be blank.
Example
<html>
<head>
<script>
function form_validation(){
var name=document.myform.name.value;
//var x = document.forms["myform"]["name"].value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}
}
</script>
</head>
<body>
<form name="myform" method="post" action="register.php" onsubmit="return form_validation()"
>
Name: <input type="text" name="name">
<input type="submit" value="submit">
</form>
</body>
</html>
Result
Name:
submit
Email validation
We can validate the email with the help of JavaScript. Here we check the condition related to any
email id, like email if must have "@" and "." sign and also email id must be at least 10 character.
There are many criteria that need to be follow to validate the email id such as:
 email id must contain the @ and . character
 There must be at least one character before and after the @.
 There must be at least two characters after . (dot).
Example
<html>
<head>
<script>
function email_validation()
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-mail address n atpostion:"+atposition+"n
dotposition:"+dotposition);
return false;
}
}
</script>
</script>
</head>
<body>
<form name="myform" method="post" action="#" onsubmit="return email_validation();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form></body>
</html>
Result
Email:
register
JavaScript Password Validation
Here i will show you how to validate any password field like password field can not be blank and
length of password is minimum 8 character.
Example
<html>
<head>
<script>
function pass_validation()
{
var password=document.myform.password.value;
if (password==null || password=="")
{
alert("password can't be blank");
return false;
}
else if(password.length<8)
{
alert("Password must be at least 8 characters long.");
return false;
}
}
</script>
</head>
<body>
<form name="myform" method="post" action="register.php" onsubmit="return pass_validation()"
>
Password: <input type="password" name="password">
<input type="submit" value="submit">
</form>
</body>
</html>
Result
Password:
submit
Re-type Password Validation
Example
<html>
<head>
<script>
function pass_validation()
{
var firstpassword=document.f1.password1.value;
var secondpassword=document.f1.password2.value;
if(firstpassword==secondpassword){
return true;
}
else{
alert("password one and two must be same!");
return false;
}
}
</script>
</head>
<body>
<form name="f1" action="/JavaScript/Index" onsubmit="return pass_validation()">
Password:<input type="password" name="password1" /><br/>
Re-enter Password:<input type="password" name="password2"/><br/>
<input type="submit">
</form>
</body>
</html>
Result
Password:
Re-enter Password:
Submit
JavaScript Interview Questions
What is JavaScript ?
JavaScript is a scripting language. It is object-based scripting language. It is light weighted. It is
different from Java language. It is widely used for client side validation.
JavaScript is which type of Language ?
JavaScript is a object-based scripting language. It is light weighted.
Why we use JavaScript ?
Using Html we can only design a web page. Using Html we can not run any logic on web browser
like addition of two numbers, check any condition, looping statements(for, while), decision making
statement(if-else) etc at client side. All these are not possible using Html so for perform all these
task at client side we use JavaScript.
Where JavaScript is used ?
It is used to create interactive websites. It is mainly used for:
 Client-side validation
 Dynamic drop-down menus
 Displaying data and time
 Build small but complete client side programs .
 Displaying popup windows and dialog boxes (like alert dialog box, confirm dialog box
and prompt dialog box)
 Displaying clocks etc.
What is the difference between == and ===
The 3 equal signs (===) mean "equality without type coercion". Using the triple equals, the values
must be equal in type as well. It checks for equality as well as the type.
== means simple equal to, it compare two values only. It checks equality only,
Example
== is equal to
=== is exactly equal to (value and type)
0==false // true
0===false // false, because they are of a different type
1=="1" // true, auto type coercion
1==="1" // false, because they are of a different type
How to declare variable in JavaScript ?
Java script did not provide any data types for declaring variables and a variable in java script can
store any type of value. We can use a variable directly without declaring it. Only var keyword are
use before variable name to declare any variable.
Syntax
var x;
Difference between Window object and document object
Document object Window object
The document object represents the whole html
document. When html document is loaded in the
browser, it becomes a document object.
The window object represents a window in
browser. An object of window is created
automatically by the browser.
What would be the difference if we declare two variables inside a JavaScript, one with
'var' keyword and another without 'var' keyword ?
The variable with var keyword inside a function is treated as Local variable,and the variable without
var keyword inside a function is treated a global variable.
What is a closure in JavaScript ?
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.
What is uses of Window Object ?
The window object represents a window in browser. An object of window is created automatically
by the browser. It is used to display the popup dialog box such as alert dialog box, confirm dialog
box, input dialog box etc.
What is Document Object
The document object represents the whole html document. When html document is loaded in the
browser, it becomes a document object. It is the root element that represents the html document.
Is JavaScript case sensitive ?
Yes!
A function getElementById is not the same as getElementbyID
What does "1"+2+3 evaluate to ?
After a string all the + will be treated as string concatenation operator (not binary +), so the result
is 123.
What does 1+2+"5" evaluate to ?
If there is numeric value before and after +, it is treated is binary + (arithmetic operator), so the
result is 35.
Difference between get and post method.
Http protocol mostly use either get() or post() methods to transfer the request.
Get method Post method
1
Request sends the request parameter as query
string appended at the end of the request.
Post request send the request parameters
as part of the http request body.
2
Get method is visible to every one (It will be
displayed in the address bar of browser ).
Post method variables are not displayed in
the URL.
3
Restriction on form data, only ASCII characters
allowed.
No Restriction on form data, Binary data is
also allowed.
4
Get methods have maximum size is 2000
character.
Post methods have maximum size is 8
mb.
5
Restriction on form length, So URL length is
restricted
No restriction on form data.
6 Remain in browser history. Never remain the browser history.
How to create function in JavaScript ?
Declare a function in JavaScript using function keyword. The keyword function precedes the name
of the function.
Syntax
function function_name()
{
//function body
}
Read more.......
How to write comment in JavaScript ?
There are two types of comment are available in JavaScript.
 Single Line Comment: It is represented by // (double forward slash)
 Multi Line Comment: It is represented by slash with asterisk symbol as /* write
comment here */
How do we add JavaScript onto a web page?
There are several way for adding javascript on a web page but there are two way with is commonly
used by developers
 Between the <body> </body> tag of html (Inline JavaScript)
 Between the <head> </head> tag of html (Internal JavaScript)
 In .js file (External JavaScript)
Read more .......
How to access the value of a textbox using JavaScript ?
Example
<!DOCTYPE html>
<html>
<body>
Name: <input type="text" id="txtname" name="FirstName" value="Porter">
</body>
</html>
There are following way to access the value of the above textbox
Example
var name = document.getElementById('txtname').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.
How you will get the CheckBox status whether it is checked or not ?
Example
var status = document.getElementById('checkbox1').checked;
alert(status);
//it will return true or false
How to create arrays in JavaScript ?
Example
var names = new Array();
// Add Elements in Array
names[0] = "Hina";
names[1] = "Niki";
names[2] = "Ram";
// This is second way
var names = new Array("Hina", "Niki", "Ram");
If an array with name as "marks" contain three elements then how you will print the
third element of this array?
Example
Print third array element document.write(marks[2]);
Note: Array index start with 0
What does the isNaN() function ?
The isNan() function returns true if the variable value is not a number.
Example
document.write(isNaN("Hello")+ "<br>");
document.write(isNaN("2015/04/29")+ "<br>");
document.write(isNaN(1234)+ "<br>");
Output
true
true
false
What is the use of Math Object in Javascript?
The math object provides you properties and methods for mathematical constants and functions.
Example
var x = Math.PI; // Returns PI
var y = Math.sqrt(25); // Returns the square root of 25
var z = Math.sin(60); Returns the sine of 60
How can you submit a form using JavaScript?
To submit a form using JavaScript use document.form[0].submit();
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.
How can the style/class of an element be changed?
It can be done in the following way:
Example
document.getElementById("myText").style.fontSize = "20
or
document.getElementById("myText").className = "anyclass";
What are all the looping structures in JavaScript?
 For
 While
 do-while loops
What is called Variable typing in Javascript?
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";
What is the function of delete operator?
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.
What are all the types of Pop up boxes available in JavaScript?
 Alert
 Confirm and
 Prompt
What is the use of Void(0)?
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.
How can a page be forced to load another page in JavaScript?
The following code has to be inserted to achieve the desired effect:
Example
<script language="JavaScript" type="text/javascript" >
<location.href="http://newhost/newpath/newfile.html";
</script>
What is the difference between an alert box and a confirmation box?
An alert box displays only one button which is the OK button.
But a Confirmation box displays two buttons namely OK and cancel.
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.
Which keyword is used to print the text in the screen?
document.write("Welcome") is used to print the text - Welcome in the screen.
What is the use of blur function?
Blur function is used to remove the focus from the specified object.
What is the use of typeof operator?
'Typeof' is an operator which is used to return a string description of the type of a variable.
How to handle exceptions in JavaScript?
By using Try...Catch--finally keyword handle exceptions in the JavaScript
Example
try
{
code
}
catch(exp)
{
code to throw an exception
}
finally
{
code runs either it finishes successfully or after catch
What is AngularJS ?
AngularJS is a javascript framework used for creating single web page applications.
What are the key features of Angularjs ?
 Scope
 Controller
 Model
 View
 Services
 Data Binding
 Directives
 Filters
 Testable
What is scope in Angularjs ?
scope is an object that refers to the application model. It is an execution context for expressions.
Scopes are arranged in hierarchical structure which mimic the DOM structure of the application.
Scopes can watch expressions and propagate events.
What is controller in Angularjs ?
In Angular, a Controller is a JavaScript constructor function that is used to augment the Angular
Scope. When a Controller is attached to the DOM via the ng-controller directive, Angular will
instantiate a new Controller object, using the specified Controller's constructor function.
What is data binding in Angularjs ?
Data-binding in Angular apps is the automatic synchronization of data between the model and view
components.
What are the Advantages of using Angularjs
 Two way data-binding
 MVC pattern
 Provides Static template and angular template
 Can add custom directive
 Provides REST full services
 Provides form validations
 Provides both client and server communication
 Provides dependency injection
 Applying Animations
 Event Handlers
Read more......
Why called AngularJS ?
Because HTML has Angular brackets and "ng" sounds like "Angular".
AngularJS a library, framework, plugin or a browser extension?
AngularJS is the framework of JavaScript. AngularJS is 100% JavaScript, 100% client-side and
compatible with both desktop and mobile browsers. So it's definitely not a plugin or some other
native browser extension.
What are Directives?
At a high level, directives are markers on a DOM element (such as an attribute, element name,
comment or CSS class) that tell AngularJS's HTML compiler ($compile) to attach a specified
behavior to that DOM element or even transform the DOM element and its children.
Angular use the jQuery library?
Yes, Angular can use jQuery if it's present in your app when the application is being bootstrapped.
If jQueryis not present in your script path,Angular falls backto its own implementation of the subset
of jQuery that we call jQLite.
Why is this project called "AngularJS" ?
Because HTML has Angular brackets and "ng" sounds like "Angular".
Which browsers support Angular ?
AngularJS mostly support all new web browser, following browsers supported by angularJS: Safari,
Chrome, Firefox, Opera, IE8, IE9 and mobile browsers (Android, Chrome Mobile, iOS Safari).
What are limitations of Angularjs ?
 Not Secure: It is a framework of JavaScript not a server side programming. Only
server side programs provides security, server side authentication and authorization
provides security for application.
 Depends on User: If any user disable JavaScript in their own browser then nothing
will be apply on your application related to JavaScript and AngularJS, Only basic
Html page will display.
What is ng-init directive ?
The ng-init directive initialize application data same like variable initialization in C language, In c
language you initialize int a=10;.
What is ng-model directive ?
The ng-model directive binds the value of HTML controls (input, select, textarea) to application
data. The ng-model directive defines the variable to be used in AngularJS Application.
What is ng-repeat directive ?
The ng-repeat directive repeats an Html element. ng-repeat directive repeats a specific
element. Read more......
What is expression in Ajgularjs ?
AngularJS Expressions used to binds application data to HTML. AngularJS expressions are written
inside double curly braces such as : {{ expression }}.
What is filter in Angularjs ?
Filter are mainly used for modify the data. Filters can be added to expressions and directives using
a pipe (|) character. For example uppercase filter are used for converting lower case text to upper
case text. Read more......
What is Angularjs Include ?
Using AngularJS, we can include or embed Html pages within an Html page using ng-include
directive. Read more......
How to define controller in angularjs ?
For define controller in AngularJS application we need ng-controller directive names. Read
more......
How to handel event in Angularjs ?
AngularJS have its own event directive to handle DOM events like mouse clicks, moves, keyboard
presses, change events etc. Read more......
MVC Architecture
What is MVC Architecture ?
MVC stand for Model View Controller. Model View Controller is a software design pattern for
developing web application. It given software application into three interconnected parts, model,
view and controller.
What is view in MVC ?
It is responsible for displaying output data to the user.
What is model in MVC ?
Model is responsible for maintaining data. Model retrieve data form database and also store data
in database.
What is Contoller in MVC ?
Controller It is responsible for controls the interactions between the Model and View. Controllers
can read data from a view, control user input, and send input data to the model.
What is a class loader ?
Part of JVM which is used to load classes and interfaces.
What are the different class loaders used by JVM ?
Bootstrap , Extension and System are the class loaders used by JVM.
Different types of memory used by JVM ?
Class , Heap , Stack , Register , Native Method Stack.
What is the purpose of the System class ?
System class provide access to system resources.
Variable of the boolean type is automatically initialized as ?
The default value of the boolean type is false.
Difference between static vs. dynamic class loading ?
static loading: Classes are statically loaded with Java new operator.
dynamic class loading: Dynamic loading is a technique for programmatically invoking the
functions of a class loader at run time.
Difference between composition and inheritance in Java ?
Composition Inheritance
has-a relationship between classes. is-a relationship between classes.
Used in Dependency Injection Used in Runtime Polymorphism
Single class objects can be composed within multiple
classes.
Single class can only inherit 1
Class.
Its the relationship between objects.
Its the relationship between
classes.
What do you mean by "Java is a statically typed language" ?
It means that the type of variables are checked at compile time in Java.The main advantage here
is that all kinds of checking can be done by the compiler and hence will reduce bugs.
What are different ways of object creation in Java ?
.
 Using new operator - new xyzClass()
 Using factory methods - xyzFactory.getInstance( )
 Using newInstance( ) method
 By cloning an already available object - (xyzClass)obj1.clone( )
Explain Autoboxing ?
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types
and their corresponding object wrapper classes.
What is an Enum type ?
An enum type is a special data type that enables for a variable to be a set of predefined constants.
What are Wrapper Classes ?
A wrapper class is any class which "wraps" or "encapsulates" the functionality of another class or
component.
What are Primitive Wrapper Classes ?
A Wrapper Class that wraps or encapsulates the primitive data type is called Primitive Wrapper
Class..
Why use Scanner class ?
For reading Data Stream from the input device.
Difference between loadClass and Class.forName ?
loadClass only loads the class but doesn't initialize the object whereas Class.forName initialize the
object after loading it.
Should we override finalize method ?
Finalize is used by Java for Garbage collection. It should not be done as we should leave the
Garbage Collection to Java itself.
Why Java don't use pointers ?
Pointers are vulnerable and slight carelessness in their use may result in memory problems and
hence Java intrinsically manage their use.
Do we need to import java.lang.package ?
No, It is loaded by default by the JVM.
What is the difference between System.out ,System.err and System.in ?
System.out and System.err both represent the monitor by default and hence can be used to send
data or results to the monitor. But System.out is used to display normal messages and results
whereas System.err is used to display error messages and System.in represents InputStream
object, which by default represents standard input device, i.e., keyboard.
Is it possible to compile and run a Java program without writing main( ) method ?
Yes, it is possible by using a static block in the Java program.
Can we call the garbage collector explicitly ?
We can call garbage collector of JVM to delete any unused variables and unreferenced objects
from memory using gc( ) method. This gc( ) method appears in both Runtime and System classes
of java.lang package.
What are different oops concept in java ?
OOPs stands for Object Oriented Programming. The oops concepts are similar in any other
programming languages. Because it is not programming concept. All oops concept in java are;
 Class
 Object
 Polymorphism
 Inheritance
 Abstraction
 Encapsulation
 Aggreagation
 Composition
 Association
What is class ?
A class is a specification or blue print or template of an object.
What is object ?
Object is instance of class. It is dynamic memory allocation of class.
What are the Characteristics of Object ?
Characteristics of Object are;State Behavior and Identity.
Can a class extend more than one class in Java ?
No, a class can only extend another class because Java doesn't support multiple inheritances but
yes, it can implement multiple interfaces.
What is the difference between abstraction and polymorphism in Java ?
Abstraction generalizes the concept and Polymorphism allow you to use different implementation
without changing your code.
What is an Abstraction ?
Abstraction is a process to show only usful data and remaining hide from user.
Real Life Example of Abstraction ?
When you log into your email, compose and send a mail. Again there is a whole lot of background
processing involved, verifying the recipient, sending request to the email server, sending your
email. Here you are only interested in composing and clicking on the send button. What really
happens when you click on the send button, is hidden from you.
Real life example of abstraction ?
Real life example of abstraction is ATM machine; here only show balance in your account but not
display ATM pin code.
What is Encapsulation ?
The process of binding data and methods into a single unit is known as Encapsulation. In other
word The process of binding the data with related methods known as encapsulation.
Real Life Example of Encapsulation ?
Encapsulation is like enclosing in a capsule.
Encapsulation is like your bag in which you can keep your pen, book etc.
What is inheritance ?
It is used in java for achieve concept of re-usability. As the name suggests , inheritance means to
take something that already made.
What is polymorphism ?
It is process to represent any things in multiple forms.
Real life example of Polymorphism ?
A Person who knows more than two languages he can speak in a language which he knows. Here
person is Object and speak is polymorphisam.
What is method overloading in Java ?
When same method is available in any class with same name and different signature is called
method overloading.
What is method overriding in Java ?
When same method available in base class and drive class with same name and same signature
it is called method overriding.
What is Aggregation ?
If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A
relationship..
What is Composition ?
Composition is the design technique to implement has-a relationship in classes. Composition in
java is achieved by using instance variables that refers to other objects.
Can we declare abstract method as final ?
No. its not possible to declare abstract method with final keyword. Because abstract methods
should be override by its sub classes.
Is it possible to declare abstract method as private ?
No. its not possible to declare abstract method with private. Because abstract methods should be
override by its sub classes.
Differences between method Overloading and method Overriding ?
Overloaded Method Overridden Method
Arguments Must be Change Must not be change
Return
Type
Can change
Can't change except for covariant
returns
Exceptions Can Change
Can reduce or eliminate. Must not
throw new or broader checked
exceptions
Access Can change
Must not make more restrictive (can
be less restrictive)
Invocation
Reference type determines which
overloaded version is selected. Happens at
compile time.
Object type determines which
method is selected. Happens at
runtime.
Why use constructor ?
The main purpose of create a constructor is, for placing user defined values in place of default
values.
Why constructor not return any value ?
Constructor will never return any value even void, because the basic aim constructor is to place
value in the object
Why constructor definition should not be static ?
Constructor definition should not be static because constructor will be called each and every time
when object is created. If you made constructor is static then the constructor before object creation
same like main method.
Why constructor is not inherited ?
Constructor will not be inherited from one class to another class because every class constructor
is created for initialize its own data members.
What is purpose of default constructor ?
The purpose of default constructor is to create multiple object with respectto same class for placing
same value.
What is purpose of parameterized constructor ?
The purpose of parametrized constructor is to create multiple object with respect to same class for
placing different value of same type or different type or both.
Is constructor inherited?
No, constructor is not inherited.
Can you make a constructor final?
No, constructor can't be final.
What is the purpose of default constructor?
The default constructor provides the default values to the objects. The java compiler creates a
default constructor only if there is no constructor in the class.
Can we use both "this" and "super" in a constructor ?
No, because both this and super should be the first statement.
Does constructor return any value?
yes, that is current instance (You cannot use return type yet it returns a value).
What is flow of constructor in Java ?
Constructor are calling from bottom to top and executing from top to bottom.
Why overriding is not possible at constructor level. ?
The scope of constructor is within the class so that it is not possible to achieved overriding at
constructor level.
Difference between Method and Constructor
Method Constructor
1 Method can be any user defined name Constructor must be class name
2 Method should have return type It should not have any return type (even void)
3
Method should be called explicitly either with
object reference or class reference
It will be called automatically whenever object is
created
1
Method is not provided by compiler in any
case.
The java compiler provides a default
constructor if we do not have any constructor.
What is Abstraction ?
Abstraction is a process of hiding the implementation details and showing only functionality to the
user.
How achieve Abstraction in Java ?
There are two ways to achieve abstraction in java
 Abstract class (0 to 100%)
 Interface (100%)
Real life example of Abstraction ?
Mobile phone is one of example of abstraction. We only know about how to call and use mobile but
we can't know about internal functionally of mobile phone.
Real life example of Abstraction and Encapsulation ?
Outer Look of a Television, like it has a display screen and channel buttons to change channel it
explains Abstraction but Inner Implementation detail of a Television how CRT and Display Screen
are connect with each other using different circuits , it explains Encapsulation.
Which of the following Java feature show only important information ?
 Inheritance
 Encapsulation
 Abstraction
 Composition
Ans: Abstraction
What is Polymorphism ?
The ability to define a function in multiple forms is called Polymorphism.
What is Overloading ?
Whenever several methods have same names with;
 Different method signature and different number or type of parameters.
 Same method signature but different number of parameters.
 Same method signature and same number of parameters but of different type
It is determined at the compile time.
What is method overriding ?
If subclass(child class) hasthe same method as declared in the parentclass, it is known as method
overriding in java. It is determined at the run time.
Difference between method overloading and mehtod Overloading ?
Method overloading is determined at the compile time and method overriding is determined at the
run time
How to achieve polymorphism in Java ?
How to achieve polymorphism in Java ?
In Java, static polymorphism is achieved through method overloading and method overriding.
Types of polymorphism in Java ?
In Java, there are two types of polymorphism.
 Compile time polymorphism (static binding or method overloading)
 Runtime polymorphism (dynamic binding or method overriding)
How to achieve static polymorphism in Java ?
In Java, static polymorphism is achieved through method overloading.
How to achieve dynamic polymorphism in Java ?
In Java, dynamic polymorphism is achieved through method overriding.
What is Compile time polymorphism ?
As the meaning is implicit, this is used to write the program in such a way, that flow of control is
decided in compile time itself. It is achieved using method overloading.
Example
public static int add(int a, int b)
{
......
......
}
public static double add(double a, double b)
{
......
......
}
public static float add(float a, float b)
{
......
......
}
What is Runtime polymorphism ?
Run time Polymorphism also known as method overriding and it is achieve at runtime.
Example
class Vehicle
{
public void move()
{
System.out.println("Vehicles can move !!!!");
}
}
class MotorBike extends Vehicle
{
public void move()
{
System.out.println("MotorBike can move and accelerate too!!!");
}
}
class Demo {
public static void main(String[] args)
{
Vehicle obj=new MotorBike();
obj.move(); // prints message MotorBike can move and accelerate too!!!
obj=new Vehicle();
obj.move(); // prints message Vehicles can move!!
}
}
What is Interface ?
An interface is a collection of abstract methods. A class implements an interface, thereby inheriting
the abstract methods of the interface..
Main features of Interface ?
 Interface cannot be instantiated
 An interface does not contain any constructors
 All of the methods in an interface are abstract
Can an Interface be final ?
No, because its implementation is provided by another class.
What is marker interface ?
An interface that have no data member and method is known as a marker interface.For example
Serializable, Cloneable etc.
What is difference between abstract class and interface ?
An abstract class can have method body (non-abstract methods) but Interface have only abstract
methods.
How to implement Interface in Java ?
Syntax
interface A
{
....
....
}
interface B
{
....
....
}
class C implements A,B
{
....
....
}
In Java Programming Inheritance is used for reuse features of one class into another class, Using
this concept enhance (improve or increase) performance of application.
What is Inheritance ?
Inheritance is one of the main features of any object oriented programming. Using inheritance
concept, a class (Sub Class) can inherit properties of another class (Super Class). So it is used for
reuse features.
Main advantage of using Inheritance ?
Using this feature you can reuse features,less memory wastage, less time required to develop and
application and improve performance of application.
Types of Inheritance supported by Java ?
Java support only four types of inheritance in java.
 Single Inheritance
 Multi level Inheritance
 Hybrid Inheritance
 Hierarchical Inheritance
Why use Inheritance ?
 For Code Re usability.
 For Method Overriding.
What is multilevel inheritance ?
Getting the properties from one class object to another class object level wise with different
priorities.
Which of these keyword must be used to inherit a class ?
 a) super
 b) this
 c) extent
 d) extends
d. extends
What is Multiple Inheritance ?
The concept of Getting the properties from multiple class objects to sub class object with same
priorities is known as multiple inheritance.
How Inheritance can be implemented in java ?
Inheritance can be implemented in Java using two keywords, they are;
 extends
 Implements
Which of these keywords is used to refer to member of base class from a sub class ?
 a) upper
 b) super
 c) this
 d) None of these
Answer: b
extends is used for developing inheritance between two classes and two interfaces.
Implements keyword is used to developed inheritance between interface and class.
What is syntax of inheritance ?
Syntax
public class subclass extends superclass
{
//all methods and variables declare here
}
Which inheritance are not supported bb Java ?
Multi Inheritance is not supported by java.
How Inheritance can be implemented in java ?
Inheritance can be implemented in JAVA using these two keywords; extends and implements
How do you implement multiple inheritance in java ?
Using interfaces java can support multiple inheritance concept in java.
Syntax
interface A
{
....
....
}
interface B
{
....
....
}
class C implements A,B
{
....
....
}
How do you implement multiple inheritance in java ?
Using interfaces java can support multiple inheritance concept in java. in java can not extend more
than one classes, but a class can implement more than one interfaces.
Why we need to use Inheritance ?
It is used for code re-usability and for Method Overriding.
Can a class extend itself ?
No, A class can't extend itself.
What is syntax of Inheritance ?
Syntax
public class subclass extends superclass
{
//all methods and variables declare here
}
Example of Single Inheritance in Java
Example
class Faculty
{
float salary=30000;
}
class Science extends Faculty
{
float bonous=2000;
public static void main(String args[])
{
Science obj=new Science();
System.out.println("Salary is:"+obj.salary);
System.out.println("Bonous is:"+obj.bonous);
}
}
why Java Doesn't Support multiple Inheritance ?
Due to ambiguity problem.
What happens if super class and sub class having same field name ?
Super class field will be hidden in the sub class. You can access hidden super class field in sub
class using super keyword.
How do you implement multiple inheritance in Java ?
Example
interface A
{
.....
.....
}
interface B
{
.....
.....
}
class C implements A,B
{
}
Can we reduce the visibility of the inherited or overridden method ?
Ans. No.
Which of the following is tightly bound ? Inheritance or Composition ?
Ans. Inheritance.
Does a class inherit the constructor of its super class ?
Ans. No

More Related Content

Basic Java script handouts for students

  • 1. Introduction JavaScript is a object-based scripting language and it is light weighted. It is first implemented by Netscape (with help from Sun Microsystems). JavaScript was created by Brendan Eich at Netscape in 1995 for the purpose of allowing code in web-pages (performing logical operation on client side). It is not compiled but translated. JavaScript Translator is responsible to translate the JavaScript code which is embedded in browser. Netscape first introduced a JavaScript interpreter in Navigator 2. The interpreter was an extra software component in the browser that was capable of interpreting JavaSript source code inside an HTML document. This means that web page developer no need other software other than a text editor of develop any web page. Why we Use JavaScript? Using HTML we can only design a web page but you can not run any logic on web browser like addition of two numbers, check any condition, looping statements (for, while), decision making statement (if-else) at client side. All these are not possible using HTML So for perform all these task at client side you need to use JavaScript.
  • 2. Where it is used? It is used to create interactive websites. It is mainly used for:  Client-side validation  Dynamic drop-down menus  Displaying data and time  Build small but complete client side programs .  Displaying popup windows and dialog boxes (like alert dialog box, confirm dialog box and prompt dialog box)  Displaying clocks etc. History JavaScript is a object-based scripting language and it is light weighted. It is first implemented by Netscape (with help from Sun Microsystems). JavaScript was created by Brendan Eich at
  • 3. Netscape in 1995 for the purpose of allowing code in web-pages (performing logical operation on client side). Using HTML we can only design a web page but you can not run any logic on web browser like addition of two numbers, check any condition, looping statements(for, while), decision making statement(if-else) etc. All these are not possible using HTML so for perform all these task we use JavaScript. Using HTML we can only design a web page if we want to run any programs like c programming we use JavaScript. Suppose we want to printsum oftwo number then we use JavaScript for coding. Features of JavaScript JavaScript is a client side technology, it is mainly used for gives client side validation, but it have lot of features which are given below;
  • 4.  JavaScript is a object-based scripting language.  Giving the user more control over the browser.  It Handling dates and time.  It Detecting the user's browser and OS,  It is light weighted.  JavaScript is a scripting language and it is not java.  JavaScript is interpreter based scripting language.  JavaScript is case sensitive.  JavaScript is object based language as it provides predefined objects.  Every statement in javascript must be terminated with semicolon (;).  Most of the javascript control statements syntax is same as syntax of control statements in C language.  An important part of JavaScript is the ability to create new functions within scripts. Declare a function in JavaScript using function keyword. Uses of JavaScript There are too many web applications running on the web that are using JavaScript technology like gmail, facebook,twitter, google map, youtube etc. Uses of JavaScript  Client-side validation  Dynamic drop-down menus  Displaying data and time  Validate user input in an HTML form before sending the data to a server.  Build forms that respond to user input without accessing a server.
  • 5.  Change the appearance of HTML documents and dynamically write HTML into separate Windows.  Open and close new windows or frames.  Manipulate HTML "layers" including hiding, moving, and allowing the user to drag them around a browser window.  Build small but complete client side programs .  Displaying popup windows and dialog boxes (like alert dialog box, confirm dialog box and prompt dialog box)  Displaying clocks etc. Comment Comment is nothing but it is a statement which is not display on browser window. it is useful to understand the which code is written for what purpose. Comments are useful in every programming language to deliver message. It is used to add information about the code, warnings or suggestions so that the end user or other developer can easily interpret the code. Types of JavaScript Comments There are two types of comments are in JavaScript  Single-line Comment  Multi-line Comment Single-line Comment It is represented by double forward slashes (//). It can be used before any statement. Example <script>
  • 6. // It is single line comment document.write("Hello Javascript"); </script> Result Hello Javascript Multi-line Comment It can be used to add single as well as multi line comments. It is represented by forward slash (/) with asterisk (*) then asterisk with forward slash. Example <script> /* It is multi line comment. It will not be displayed */ document.write("Javascript multiline comment"); </script> JavaScript First Program Javascript simple example to verify age of any person, if age is greater than 18 show message adult otherwise show under 18 JavaScript Example to verify age Example <html> <head> <script> function verify(){ var no; no=Number(document.getElementById("age").value);
  • 7. if(no<18) { alert("Under 18"); } else { alert("You are Adult"); } } </script> </head> <body> Enter your age:<input id="age"><br /> <button onclick="verify()">Click me</button> </body> </html> Result Enter your age: Click me Way of Using JavaScript There are three places to put the JavaScript code.  Between the <body> </body> tag of html (Inline JavaScript)  Between the <head> </head> tag of html (Internal JavaScript)  In .js file (External JavaScript) Inline JavaScript When java script was written within the html element using attributes related to events of the element then it is called as inline java script.
  • 8. Example of Inline JavaScript Example <html> <form> <input type="button" value="Click" onclick="alert('Button Clicked')"/> </form> </html> Result Internal JavaScript When java script was written within the section using element then it is called as internaljava script. Example of Internal JavaScript Example <html> <head> <script> function msg() { alert("Welcome in JavaScript"); } </script> </head> <form> <input type="button" value="Click" onclick="msg()"/> </form> </html> Result External JavaScript Writing java script in a separate file with extension .js is called as external java script. For adding the reference of an external java script file to your html page, use tag with src attribute as follows
  • 9. Example <script type="text/javascript" src="filename.js"/> Create a file with name functions.js and write the following java script functions in it. message.js Example function msg() { alert("Hello Javatpoint"); } Create a html page and use the file functions.js as follows index.html Example <html> <head> <script type="text/javascript" src="message.js"></script> </head> <body> <form> <input type="button" value="click" onclick="msg()"/> </form> </body> </html> Result Variable Declaration
  • 10. Java script did not provide any data types for declaring variables and a variable in java script can store any type of value. Hence java script is loosely typed language. We can use a variable directly without declaring it. Only var keyword are use before variable name to declare any variable. Syntax var x; Rules to declaring a variable  Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.  After first letter we can use digits (0 to 9), for example value1.  Javascript variables are case sensitive, for example x and X are different variables. Variable declaration Example var x = 10; // Valid var _value="porter"; // Valid var 123=20; // Invalid var #a=220; // Invalid var *b=220; // Invalid Example of Variable declaration in JavaScript Example <script> var a=10; var b=20; var c=a+b; document.write(c); </script>
  • 11. Output 30 Types of Variable in JavaScript  Local Variable  Global Variable Local Variable A variable which is declared inside block or function is called local variable. It is accessible within the function or block only. For example: Example <script> function abc() { var x=10; //local variable } </script> or Example <script> If(10<13) { var y=20;//javascript local variable } </script> Global Variable
  • 12. A global variable is accessible from any function. A variable i.e. declared outside the function or declared with window object is known as global variable. For example: Syntax <script> var value=10;//global variable function a() { alert(value); } function b() { alert(value); } </script> Declaring global variable through window object The best way to declare global variable in javascript is through the window object. For example: Syntax window.value=20; Now it can be declared inside any function and can be accessed from any function. For example: Example function m() { window.value=200; //declaring global variable by window object } function n() { alert(window.value); //accessing global variable from other function
  • 13. } Example of JavaScript Here i will show you how to write you first javascript code, you only need to write your javascript code inside <script> ..... </script> tag using any editor like notepad or edit plus. Save below code with .html or .htm extension. No need to compile your javascript code just open your code in any web browser. Find sum of two number using JavaScript Example <!doctype html> <html> <head> <script> function add(){ var a,b,c; a=Number(document.getElementById("first").value); b=Number(document.getElementById("second").value); c= a + b; document.getElementById("answer").value= c; } </script> </head> <body> <input id="first"> <input id="second"> <button onclick="add()">Add</button> <input id="answer"> </body> </html> Result
  • 14. Enter First Number: Enter Second Number: Add Code Explanation  no=Number(document.getElementById("first").value); This code is used for receive first input value form input field which have id first.  no=Number(document.getElementById("second").value); This code is used for receive first input value form input field which have id second.  document.getElementById("answer").value= fact; This code is used for receive calculated value of factorial and display in input field which have id answer  <button onclick="add()">Add</button> This code is used for call add function when button clicked. Find Factorial of number in JavaScript Using javascript you can find factorial of any number, here same logic are applied like c language you only need to write your javascript code inside <script> ..... </script> tag using any editor like notepad or edit plus. Save below code with .html or .htm extension. No need to compile your javascript code just open your code in any web browser. Find factorial of number using JavaScript Example Factorial of any number <!doctype html> <html> <head> <script> function show(){ var i, no, fact;
  • 15. fact=1; no=Number(document.getElementById("num").value); for(i=1; i<=no; i++) { fact= fact*i; } document.getElementById("answer").value= fact; } </script> </head> <body> Enter Num: <input id="num"> <button onclick="show()">Factorial</button> <input id="answer"> </body> </html> Result Enter Num: Factorial Code Explanation  no=Number(document.getElementById("num").value); This code is used for receive input value form input field which have id num.  document.getElementById("answer").value= fact; This code is used for receive calculated value of factorial and display in input field which have id answer  <button onclick="show()">Factorial</button> This code is used for call show function when button clicked. If else Statement The if statement is used in JavaScript to execute the code if condition is true or false. There are three forms of if statement.
  • 16.  If Statement  If else statement  if else if statement JavaScript If statement if is most basic statement of Decision making statement. It tells to program to execute a certain part of code only if particular condition or test is true. Syntax Syntax if(expression) { //set of statements } Example
  • 17. <script> var a=10; if(a>5) { document.write("value of a is greater than 5"); } </script> JavaScript if-else statement In general it can be used to execute one block of statement among two blocks. Syntax if(expression) { //set of statements } else {
  • 18. //set of statements } Example of if..else statement <script> var a=40; if(a%2==0) { document.write("a is even number"); } else{ document.write("a is odd number"); } </script> Result a is even number JavaScript If...else if statement It evaluates the content only if expression is true from several expressions. Syntax if(expression1) { //content to be evaluated if expression1 is true } else if(expression2) { //content to be evaluated if expression2 is true } else { //content to be evaluated if no expression is true }
  • 19. Example of if..else if statement <script> var a=40; if(a==20) { document.write("a is equal to 20"); } else if(a==5) { document.write("a is equal to 5"); } else if(a==30) { document.write("a is equal to 30"); } else { document.write("a is not equal to 20, 5 or 30"); } </script> Looping Statement in Set of instructions given to the compiler to execute set of statements until condition becomes false is called loops. The basic purpose of loop is code repetition. The way of the repetition will be forms a circle that's why repetition statements are called loops. Some loops are available In JavaScript which are given below.  while loop  for loop  do-while while loop
  • 20. When we are working with while loop always pre-checking process will be occurred. Pre-checking process means before evolution of statement block condition part will be executed. While loop will be repeats in clock wise direction. Syntax while (condition) { code block to be executed } Example of while loop <script> var i=10; while (i<=13) { document.write(i + "<br/>");
  • 21. i++; } </script> Result 10 11 12 13 do-while loop In implementation when we need to repeat the statement block at least 1 then go for do-while. In do-while loop post checking of the statement block condition part will be executed.
  • 22. syntax do { code to be executed increment/decrement } while (condition); Example of do-while loop Example <script> var i=11; do{ document.write(i + "<br/>");
  • 23. i++; }while (i<=15); </script> Result 11 12 13 14 15 for Loop For loop is a simplest loop first we initialized the value then check condition and then increment and decrements occurred.
  • 24. Steps of for loop Syntax
  • 25. for (initialization; condition; increment/decrement) { code block to be executed } Example of for loop Example <script> for (i=1; i<=5; i++) { document.write(i + "<br/>") } </script> Switch Statement The switch statement is used in JavaScript to execute one code from multiple expressions.
  • 27. } Note: default code to be executed if above values are not matched Note: in switch statement all the cases will be evaluated if we do not use break statement. Example of switch statement in javascript. Example <script> var grade='B'; var result; switch(grade){ case 'A': result="A Grade"; break; case 'B': result="B Grade"; break; case 'C': result="C Grade"; break; default: result="No Grade"; } document.write(result); </script> Result Output: B Grade Example of switch case in javascript Example <html> <head> <script>
  • 28. function myFunction() { var day; day=Number(document.getElementById("first").value); switch (day) { case 1: day = "Sunday"; break; case 2: day = "Monday"; break; case 3: day = "Tuesday"; break; case 4: day = "Wednesday"; break; case 5: day = "Thursday"; break; case 6: day = "Friday"; break; case 7: day = "Saturday"; break; default: day="Enter valid number" } document.getElementById("demo").innerHTML =day; } </script> </head> <body> <p>Enter any number (1 to 7):</p> <input id="first">
  • 29. <button onclick="myFunction()">Try it</button> <p id="demo"></p> </body> </html> Result Enter any number (1 to 7): Try it Function An important part of JavaScript is the ability to create new functions within <script> and </script> tag. Declare a function in JavaScript using function keyword. The keyword function precedes the name of the function. Syntax function functionName(parameter or not) { ......... ......... } Example of JavaScript using Function Example <html> <head> <script> function getname() { name=prompt("Enter Your Name"); alert("Welcome Mr/Mrs " + name); }
  • 30. </script> </head> <form> <input type="button" value="Click" onclick="getname()"/> </form> </html> Example Array in JavaScript Array are used to represents the group of elements into a single unit or consecutive memory location. Each and every element what we are entering into the array is going to be stored in the array with the unique index starting from zero. Through the indexes we can store the data or elements into the array or we can get the elements from the array. To declare an array in javascript we need new keyword. To create an array you use new Array(n) where n was the number of slots in the array or new Array() omitting the size of an array. Note: Whenever we create any array in javaScript without specifying the size then it well create array object with the zero size. Syntax myarray = new array(5); Example of array in JavaScript Example <html> <head> <script type="text/javascript"> function arrayex() { myarray = new Array(5) myarray[0] = 10
  • 31. myarray[1] = 20 myarray[2] = 30 myarray[3] = 40 myarray[4] = 50 sum = 0; for (i=0; i<myarray.length; i++) { sum = sum + myarray[i]; } alert(sum) } </script> </head> <body> <input type="button" onclick="arrayex()" value="click here"> </body> </html> Result Function used in Array Here we will discussabout some functionswhich are frequentlyused in arrayconceptin JavaScript. Function Discription concat() To concats the elements of one array at the end of another array and returns an array. sort() To sort all elements of an array. reverse() To reverse elements of an array. slice() To extract specified number of elements starting from specified index without deleting them from array. splice() It will extract specified number of elements starting from specified index and deletes them from array.
  • 32. push() To push all elements in array at top. pop() To pop the top elements from array. JavaScript Dialog box All JavaScript dialog box is a predefined function which is used for to perform different-different task. Some function are given below; function Discription alert() To give alert message to user. prompt() To input value from used. confirm() To get confirmation from user before executing some task. Alert() Alert function of java script is used to give an alert message to the user. Alert function example Example <!doctype html> <html> <head> <script> function alertmsg() { alert("Alert function call"); } </script> </head> <form> <input type="button" value="Click Me" onclick="alertmsg()"/> </form>
  • 33. </html> Result prompt() Prompt function of java script is used to get input from the user. prompt() function example Example <!doctype html> <html> <head> <script> function alertmsg() { a=prompt("Enter your name:"); alert(a); } </script> </head> <form> <input type="button" value="Click Me" onclick="alertmsg()"/> </form> </html> Result confirm() confirm function of java script is used to get confirmation from user before executing some task. confirm() function example Example <!doctype html>
  • 34. <html> <head> <script> function alertmsg() { a=prompt("Enter your name:"); confirm(a); } </script> </head> <form> <input type="button" value="Click Me" onclick="alertmsg()"/> </form> </html> Result Window Object The window object represents a windowin browser. An object of window is created automatically by the browser. Window is the object of browser, it is not the object of javascript. The javascript objects are string, array, date etc. It is used to display the popup dialog box such as alert dialog box, confirm dialog box, input dialog box etc.
  • 35. The window methods are mainly for opening and closing new windows. The following are the main window methods. They are: Methods of window object Method Description alert() displays the alert box containing message with ok button. confirm() Displays the confirm dialog box containing message with ok and cancel button. prompt() Displays a dialog box to get input from the user. open() Opens the new window. close() Closes the current window.
  • 36. setTimeout() Performs action after specified time like calling function, evaluating expressions etc. Document Object The document object represents the whole html document. When html document is loaded in the browser, it becomes a document object. It is the root element that represents the html document. Methods of document object Method Description write("string") writes the given string on the document. writeln("string") Same as write(), but adds a newline character after each statement.
  • 37. getElementById() returns the element having the given id value. getElementsByName() returns all the elements having the given name value. getElementsByTagName() returns all the elements having the given tag name. getElementsByClassName() returns all the elements having the given class name. Event in JavaScript All objects have properties and methods. In addition, some objects also have "events". Events are things that happen, usually user actions, that are associated with an object. The "event handler" is a command that is used to specify actions in response to an event. Below are some of the most common events: Event Discription onLoad Occurs when a page loads in a browser onUnload occurs just before the user exits a page onMouseOver occurs when you point to an object onMouseOut occurs when you point away from an object onSubmit occurs when you submit a form onClick occurs when an object is clicked Events and Objects Events are things that happen, actions, that are associated with an object. Below are some common events and the object they are associaated with: Event Object onLoad Body
  • 38. onUnload Body onMouseOver Link, Button onMouseOut Link, Button onSubmit Form onClick Button, Checkbox, Submit, Reset, Link getElementById The document.getElementById() method returns the element of specified id. In below example we receive input from input field by using document.getElementById() method, here document.getElementById() receive input value on the basis on input field id. In below example "number" is the id of input field. Example <html> <body> <head> <script type="text/javascript"> function squre() { var num=document.getElementById("number").value; alert(num*num); } </script> </head> <form> Enter No:<input type="text" id="number" name="number"/><br/> <input type="button" value="squre" onclick="squre()"/> </form> </body> </html> Result
  • 39. Enter No: Code Explanation var num=document.getElementById("number").value; In this code getElementById received value from input field which have id number. Square of any number in javascript Example <html> <body> <head> <script type="text/javascript"> function squre() { var num=document.getElementById("number").value; var result=num*num; document.getElementById("answer").value=result; } </script> </head> <form> Enter No:<input type="text" id="number" name="number"/> <input type="button" value="squre" onclick="squre()"/> <input id="answer"/> </form> </body> </html> Result Enter No: JavaScript Forms Validation
  • 40. Forms validation is important things other wise user input wrong data, so we need to validate given data by user before submit it on server. The JavaScript provides the facility to validate the form on the client side so processing will be fast than server-side validation. So, most of the web developers prefer client side form validation using JavaScript. Here i will show you how to validate any input field like user name can not be blank. In below example input are can not be blank. Example <html> <head> <script> function form_validation(){ var name=document.myform.name.value; //var x = document.forms["myform"]["name"].value; if (name==null || name==""){ alert("Name can't be blank"); return false; } } </script> </head> <body> <form name="myform" method="post" action="register.php" onsubmit="return form_validation()" > Name: <input type="text" name="name"> <input type="submit" value="submit"> </form> </body> </html>
  • 41. Result Name: submit Email validation We can validate the email with the help of JavaScript. Here we check the condition related to any email id, like email if must have "@" and "." sign and also email id must be at least 10 character. There are many criteria that need to be follow to validate the email id such as:  email id must contain the @ and . character  There must be at least one character before and after the @.  There must be at least two characters after . (dot). Example <html> <head> <script> function email_validation() { var x=document.myform.email.value; var atposition=x.indexOf("@"); var dotposition=x.lastIndexOf("."); if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){ alert("Please enter a valid e-mail address n atpostion:"+atposition+"n dotposition:"+dotposition); return false; } } </script> </script> </head> <body> <form name="myform" method="post" action="#" onsubmit="return email_validation();"> Email: <input type="text" name="email"><br/> <input type="submit" value="register">
  • 42. </form></body> </html> Result Email: register JavaScript Password Validation Here i will show you how to validate any password field like password field can not be blank and length of password is minimum 8 character. Example <html> <head> <script> function pass_validation() { var password=document.myform.password.value; if (password==null || password=="") { alert("password can't be blank"); return false; } else if(password.length<8) { alert("Password must be at least 8 characters long."); return false; } } </script> </head> <body>
  • 43. <form name="myform" method="post" action="register.php" onsubmit="return pass_validation()" > Password: <input type="password" name="password"> <input type="submit" value="submit"> </form> </body> </html> Result Password: submit Re-type Password Validation Example <html> <head> <script> function pass_validation() { var firstpassword=document.f1.password1.value; var secondpassword=document.f1.password2.value; if(firstpassword==secondpassword){ return true; } else{ alert("password one and two must be same!"); return false; } } </script> </head> <body> <form name="f1" action="/JavaScript/Index" onsubmit="return pass_validation()">
  • 44. Password:<input type="password" name="password1" /><br/> Re-enter Password:<input type="password" name="password2"/><br/> <input type="submit"> </form> </body> </html> Result Password: Re-enter Password: Submit JavaScript Interview Questions What is JavaScript ? JavaScript is a scripting language. It is object-based scripting language. It is light weighted. It is different from Java language. It is widely used for client side validation. JavaScript is which type of Language ? JavaScript is a object-based scripting language. It is light weighted. Why we use JavaScript ? Using Html we can only design a web page. Using Html we can not run any logic on web browser like addition of two numbers, check any condition, looping statements(for, while), decision making statement(if-else) etc at client side. All these are not possible using Html so for perform all these task at client side we use JavaScript. Where JavaScript is used ? It is used to create interactive websites. It is mainly used for:
  • 45.  Client-side validation  Dynamic drop-down menus  Displaying data and time  Build small but complete client side programs .  Displaying popup windows and dialog boxes (like alert dialog box, confirm dialog box and prompt dialog box)  Displaying clocks etc. What is the difference between == and === The 3 equal signs (===) mean "equality without type coercion". Using the triple equals, the values must be equal in type as well. It checks for equality as well as the type. == means simple equal to, it compare two values only. It checks equality only, Example == is equal to === is exactly equal to (value and type) 0==false // true 0===false // false, because they are of a different type 1=="1" // true, auto type coercion 1==="1" // false, because they are of a different type How to declare variable in JavaScript ? Java script did not provide any data types for declaring variables and a variable in java script can store any type of value. We can use a variable directly without declaring it. Only var keyword are use before variable name to declare any variable. Syntax var x;
  • 46. Difference between Window object and document object Document object Window object The document object represents the whole html document. When html document is loaded in the browser, it becomes a document object. The window object represents a window in browser. An object of window is created automatically by the browser. What would be the difference if we declare two variables inside a JavaScript, one with 'var' keyword and another without 'var' keyword ? The variable with var keyword inside a function is treated as Local variable,and the variable without var keyword inside a function is treated a global variable. What is a closure in JavaScript ? 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. What is uses of Window Object ? The window object represents a window in browser. An object of window is created automatically by the browser. It is used to display the popup dialog box such as alert dialog box, confirm dialog box, input dialog box etc. What is Document Object The document object represents the whole html document. When html document is loaded in the browser, it becomes a document object. It is the root element that represents the html document. Is JavaScript case sensitive ? Yes! A function getElementById is not the same as getElementbyID
  • 47. What does "1"+2+3 evaluate to ? After a string all the + will be treated as string concatenation operator (not binary +), so the result is 123. What does 1+2+"5" evaluate to ? If there is numeric value before and after +, it is treated is binary + (arithmetic operator), so the result is 35. Difference between get and post method. Http protocol mostly use either get() or post() methods to transfer the request. Get method Post method 1 Request sends the request parameter as query string appended at the end of the request. Post request send the request parameters as part of the http request body. 2 Get method is visible to every one (It will be displayed in the address bar of browser ). Post method variables are not displayed in the URL. 3 Restriction on form data, only ASCII characters allowed. No Restriction on form data, Binary data is also allowed. 4 Get methods have maximum size is 2000 character. Post methods have maximum size is 8 mb. 5 Restriction on form length, So URL length is restricted No restriction on form data. 6 Remain in browser history. Never remain the browser history. How to create function in JavaScript ? Declare a function in JavaScript using function keyword. The keyword function precedes the name of the function. Syntax function function_name()
  • 48. { //function body } Read more....... How to write comment in JavaScript ? There are two types of comment are available in JavaScript.  Single Line Comment: It is represented by // (double forward slash)  Multi Line Comment: It is represented by slash with asterisk symbol as /* write comment here */ How do we add JavaScript onto a web page? There are several way for adding javascript on a web page but there are two way with is commonly used by developers  Between the <body> </body> tag of html (Inline JavaScript)  Between the <head> </head> tag of html (Internal JavaScript)  In .js file (External JavaScript) Read more ....... How to access the value of a textbox using JavaScript ? Example <!DOCTYPE html> <html> <body> Name: <input type="text" id="txtname" name="FirstName" value="Porter"> </body> </html>
  • 49. There are following way to access the value of the above textbox Example var name = document.getElementById('txtname').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. How you will get the CheckBox status whether it is checked or not ? Example var status = document.getElementById('checkbox1').checked; alert(status); //it will return true or false How to create arrays in JavaScript ? Example var names = new Array(); // Add Elements in Array names[0] = "Hina"; names[1] = "Niki"; names[2] = "Ram"; // This is second way var names = new Array("Hina", "Niki", "Ram"); If an array with name as "marks" contain three elements then how you will print the third element of this array? Example
  • 50. Print third array element document.write(marks[2]); Note: Array index start with 0 What does the isNaN() function ? The isNan() function returns true if the variable value is not a number. Example document.write(isNaN("Hello")+ "<br>"); document.write(isNaN("2015/04/29")+ "<br>"); document.write(isNaN(1234)+ "<br>"); Output true true false What is the use of Math Object in Javascript? The math object provides you properties and methods for mathematical constants and functions. Example var x = Math.PI; // Returns PI var y = Math.sqrt(25); // Returns the square root of 25 var z = Math.sin(60); Returns the sine of 60 How can you submit a form using JavaScript? To submit a form using JavaScript use document.form[0].submit();
  • 51. 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. How can the style/class of an element be changed? It can be done in the following way: Example document.getElementById("myText").style.fontSize = "20 or document.getElementById("myText").className = "anyclass"; What are all the looping structures in JavaScript?  For  While  do-while loops What is called Variable typing in Javascript? 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";
  • 52. What is the function of delete operator? 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. What are all the types of Pop up boxes available in JavaScript?  Alert  Confirm and  Prompt What is the use of Void(0)? 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. How can a page be forced to load another page in JavaScript? The following code has to be inserted to achieve the desired effect: Example <script language="JavaScript" type="text/javascript" > <location.href="http://newhost/newpath/newfile.html"; </script> What is the difference between an alert box and a confirmation box? An alert box displays only one button which is the OK button. But a Confirmation box displays two buttons namely OK and cancel. What are the different types of errors in JavaScript? There are three types of errors:
  • 53.  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. Which keyword is used to print the text in the screen? document.write("Welcome") is used to print the text - Welcome in the screen. What is the use of blur function? Blur function is used to remove the focus from the specified object. What is the use of typeof operator? 'Typeof' is an operator which is used to return a string description of the type of a variable. How to handle exceptions in JavaScript? By using Try...Catch--finally keyword handle exceptions in the JavaScript Example try { code } catch(exp) { code to throw an exception } finally { code runs either it finishes successfully or after catch
  • 54. What is AngularJS ? AngularJS is a javascript framework used for creating single web page applications. What are the key features of Angularjs ?  Scope  Controller  Model  View  Services  Data Binding  Directives  Filters  Testable What is scope in Angularjs ? scope is an object that refers to the application model. It is an execution context for expressions. Scopes are arranged in hierarchical structure which mimic the DOM structure of the application. Scopes can watch expressions and propagate events. What is controller in Angularjs ? In Angular, a Controller is a JavaScript constructor function that is used to augment the Angular Scope. When a Controller is attached to the DOM via the ng-controller directive, Angular will instantiate a new Controller object, using the specified Controller's constructor function. What is data binding in Angularjs ? Data-binding in Angular apps is the automatic synchronization of data between the model and view components.
  • 55. What are the Advantages of using Angularjs  Two way data-binding  MVC pattern  Provides Static template and angular template  Can add custom directive  Provides REST full services  Provides form validations  Provides both client and server communication  Provides dependency injection  Applying Animations  Event Handlers Read more...... Why called AngularJS ? Because HTML has Angular brackets and "ng" sounds like "Angular". AngularJS a library, framework, plugin or a browser extension? AngularJS is the framework of JavaScript. AngularJS is 100% JavaScript, 100% client-side and compatible with both desktop and mobile browsers. So it's definitely not a plugin or some other native browser extension. What are Directives? At a high level, directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS's HTML compiler ($compile) to attach a specified behavior to that DOM element or even transform the DOM element and its children.
  • 56. Angular use the jQuery library? Yes, Angular can use jQuery if it's present in your app when the application is being bootstrapped. If jQueryis not present in your script path,Angular falls backto its own implementation of the subset of jQuery that we call jQLite. Why is this project called "AngularJS" ? Because HTML has Angular brackets and "ng" sounds like "Angular". Which browsers support Angular ? AngularJS mostly support all new web browser, following browsers supported by angularJS: Safari, Chrome, Firefox, Opera, IE8, IE9 and mobile browsers (Android, Chrome Mobile, iOS Safari). What are limitations of Angularjs ?  Not Secure: It is a framework of JavaScript not a server side programming. Only server side programs provides security, server side authentication and authorization provides security for application.  Depends on User: If any user disable JavaScript in their own browser then nothing will be apply on your application related to JavaScript and AngularJS, Only basic Html page will display. What is ng-init directive ? The ng-init directive initialize application data same like variable initialization in C language, In c language you initialize int a=10;. What is ng-model directive ? The ng-model directive binds the value of HTML controls (input, select, textarea) to application data. The ng-model directive defines the variable to be used in AngularJS Application.
  • 57. What is ng-repeat directive ? The ng-repeat directive repeats an Html element. ng-repeat directive repeats a specific element. Read more...... What is expression in Ajgularjs ? AngularJS Expressions used to binds application data to HTML. AngularJS expressions are written inside double curly braces such as : {{ expression }}. What is filter in Angularjs ? Filter are mainly used for modify the data. Filters can be added to expressions and directives using a pipe (|) character. For example uppercase filter are used for converting lower case text to upper case text. Read more...... What is Angularjs Include ? Using AngularJS, we can include or embed Html pages within an Html page using ng-include directive. Read more...... How to define controller in angularjs ? For define controller in AngularJS application we need ng-controller directive names. Read more...... How to handel event in Angularjs ? AngularJS have its own event directive to handle DOM events like mouse clicks, moves, keyboard presses, change events etc. Read more...... MVC Architecture What is MVC Architecture ? MVC stand for Model View Controller. Model View Controller is a software design pattern for developing web application. It given software application into three interconnected parts, model, view and controller.
  • 58. What is view in MVC ? It is responsible for displaying output data to the user. What is model in MVC ? Model is responsible for maintaining data. Model retrieve data form database and also store data in database. What is Contoller in MVC ? Controller It is responsible for controls the interactions between the Model and View. Controllers can read data from a view, control user input, and send input data to the model. What is a class loader ? Part of JVM which is used to load classes and interfaces. What are the different class loaders used by JVM ? Bootstrap , Extension and System are the class loaders used by JVM. Different types of memory used by JVM ? Class , Heap , Stack , Register , Native Method Stack. What is the purpose of the System class ? System class provide access to system resources. Variable of the boolean type is automatically initialized as ? The default value of the boolean type is false.
  • 59. Difference between static vs. dynamic class loading ? static loading: Classes are statically loaded with Java new operator. dynamic class loading: Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time. Difference between composition and inheritance in Java ? Composition Inheritance has-a relationship between classes. is-a relationship between classes. Used in Dependency Injection Used in Runtime Polymorphism Single class objects can be composed within multiple classes. Single class can only inherit 1 Class. Its the relationship between objects. Its the relationship between classes. What do you mean by "Java is a statically typed language" ? It means that the type of variables are checked at compile time in Java.The main advantage here is that all kinds of checking can be done by the compiler and hence will reduce bugs. What are different ways of object creation in Java ? .  Using new operator - new xyzClass()  Using factory methods - xyzFactory.getInstance( )  Using newInstance( ) method  By cloning an already available object - (xyzClass)obj1.clone( )
  • 60. Explain Autoboxing ? Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. What is an Enum type ? An enum type is a special data type that enables for a variable to be a set of predefined constants. What are Wrapper Classes ? A wrapper class is any class which "wraps" or "encapsulates" the functionality of another class or component. What are Primitive Wrapper Classes ? A Wrapper Class that wraps or encapsulates the primitive data type is called Primitive Wrapper Class.. Why use Scanner class ? For reading Data Stream from the input device. Difference between loadClass and Class.forName ? loadClass only loads the class but doesn't initialize the object whereas Class.forName initialize the object after loading it. Should we override finalize method ? Finalize is used by Java for Garbage collection. It should not be done as we should leave the Garbage Collection to Java itself. Why Java don't use pointers ? Pointers are vulnerable and slight carelessness in their use may result in memory problems and hence Java intrinsically manage their use.
  • 61. Do we need to import java.lang.package ? No, It is loaded by default by the JVM. What is the difference between System.out ,System.err and System.in ? System.out and System.err both represent the monitor by default and hence can be used to send data or results to the monitor. But System.out is used to display normal messages and results whereas System.err is used to display error messages and System.in represents InputStream object, which by default represents standard input device, i.e., keyboard. Is it possible to compile and run a Java program without writing main( ) method ? Yes, it is possible by using a static block in the Java program. Can we call the garbage collector explicitly ? We can call garbage collector of JVM to delete any unused variables and unreferenced objects from memory using gc( ) method. This gc( ) method appears in both Runtime and System classes of java.lang package. What are different oops concept in java ? OOPs stands for Object Oriented Programming. The oops concepts are similar in any other programming languages. Because it is not programming concept. All oops concept in java are;  Class  Object  Polymorphism  Inheritance  Abstraction  Encapsulation  Aggreagation
  • 62.  Composition  Association What is class ? A class is a specification or blue print or template of an object. What is object ? Object is instance of class. It is dynamic memory allocation of class. What are the Characteristics of Object ? Characteristics of Object are;State Behavior and Identity. Can a class extend more than one class in Java ? No, a class can only extend another class because Java doesn't support multiple inheritances but yes, it can implement multiple interfaces. What is the difference between abstraction and polymorphism in Java ? Abstraction generalizes the concept and Polymorphism allow you to use different implementation without changing your code. What is an Abstraction ? Abstraction is a process to show only usful data and remaining hide from user. Real Life Example of Abstraction ? When you log into your email, compose and send a mail. Again there is a whole lot of background processing involved, verifying the recipient, sending request to the email server, sending your email. Here you are only interested in composing and clicking on the send button. What really happens when you click on the send button, is hidden from you.
  • 63. Real life example of abstraction ? Real life example of abstraction is ATM machine; here only show balance in your account but not display ATM pin code. What is Encapsulation ? The process of binding data and methods into a single unit is known as Encapsulation. In other word The process of binding the data with related methods known as encapsulation. Real Life Example of Encapsulation ? Encapsulation is like enclosing in a capsule. Encapsulation is like your bag in which you can keep your pen, book etc. What is inheritance ? It is used in java for achieve concept of re-usability. As the name suggests , inheritance means to take something that already made. What is polymorphism ? It is process to represent any things in multiple forms. Real life example of Polymorphism ? A Person who knows more than two languages he can speak in a language which he knows. Here person is Object and speak is polymorphisam. What is method overloading in Java ? When same method is available in any class with same name and different signature is called method overloading.
  • 64. What is method overriding in Java ? When same method available in base class and drive class with same name and same signature it is called method overriding. What is Aggregation ? If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship.. What is Composition ? Composition is the design technique to implement has-a relationship in classes. Composition in java is achieved by using instance variables that refers to other objects. Can we declare abstract method as final ? No. its not possible to declare abstract method with final keyword. Because abstract methods should be override by its sub classes. Is it possible to declare abstract method as private ? No. its not possible to declare abstract method with private. Because abstract methods should be override by its sub classes. Differences between method Overloading and method Overriding ? Overloaded Method Overridden Method Arguments Must be Change Must not be change Return Type Can change Can't change except for covariant returns Exceptions Can Change Can reduce or eliminate. Must not throw new or broader checked exceptions
  • 65. Access Can change Must not make more restrictive (can be less restrictive) Invocation Reference type determines which overloaded version is selected. Happens at compile time. Object type determines which method is selected. Happens at runtime. Why use constructor ? The main purpose of create a constructor is, for placing user defined values in place of default values. Why constructor not return any value ? Constructor will never return any value even void, because the basic aim constructor is to place value in the object Why constructor definition should not be static ? Constructor definition should not be static because constructor will be called each and every time when object is created. If you made constructor is static then the constructor before object creation same like main method. Why constructor is not inherited ? Constructor will not be inherited from one class to another class because every class constructor is created for initialize its own data members. What is purpose of default constructor ? The purpose of default constructor is to create multiple object with respectto same class for placing same value. What is purpose of parameterized constructor ? The purpose of parametrized constructor is to create multiple object with respect to same class for placing different value of same type or different type or both.
  • 66. Is constructor inherited? No, constructor is not inherited. Can you make a constructor final? No, constructor can't be final. What is the purpose of default constructor? The default constructor provides the default values to the objects. The java compiler creates a default constructor only if there is no constructor in the class. Can we use both "this" and "super" in a constructor ? No, because both this and super should be the first statement. Does constructor return any value? yes, that is current instance (You cannot use return type yet it returns a value). What is flow of constructor in Java ? Constructor are calling from bottom to top and executing from top to bottom. Why overriding is not possible at constructor level. ? The scope of constructor is within the class so that it is not possible to achieved overriding at constructor level. Difference between Method and Constructor Method Constructor 1 Method can be any user defined name Constructor must be class name 2 Method should have return type It should not have any return type (even void)
  • 67. 3 Method should be called explicitly either with object reference or class reference It will be called automatically whenever object is created 1 Method is not provided by compiler in any case. The java compiler provides a default constructor if we do not have any constructor. What is Abstraction ? Abstraction is a process of hiding the implementation details and showing only functionality to the user. How achieve Abstraction in Java ? There are two ways to achieve abstraction in java  Abstract class (0 to 100%)  Interface (100%) Real life example of Abstraction ? Mobile phone is one of example of abstraction. We only know about how to call and use mobile but we can't know about internal functionally of mobile phone. Real life example of Abstraction and Encapsulation ? Outer Look of a Television, like it has a display screen and channel buttons to change channel it explains Abstraction but Inner Implementation detail of a Television how CRT and Display Screen are connect with each other using different circuits , it explains Encapsulation. Which of the following Java feature show only important information ?  Inheritance  Encapsulation  Abstraction  Composition
  • 68. Ans: Abstraction What is Polymorphism ? The ability to define a function in multiple forms is called Polymorphism. What is Overloading ? Whenever several methods have same names with;  Different method signature and different number or type of parameters.  Same method signature but different number of parameters.  Same method signature and same number of parameters but of different type It is determined at the compile time. What is method overriding ? If subclass(child class) hasthe same method as declared in the parentclass, it is known as method overriding in java. It is determined at the run time. Difference between method overloading and mehtod Overloading ? Method overloading is determined at the compile time and method overriding is determined at the run time How to achieve polymorphism in Java ? How to achieve polymorphism in Java ? In Java, static polymorphism is achieved through method overloading and method overriding. Types of polymorphism in Java ? In Java, there are two types of polymorphism.  Compile time polymorphism (static binding or method overloading)
  • 69.  Runtime polymorphism (dynamic binding or method overriding) How to achieve static polymorphism in Java ? In Java, static polymorphism is achieved through method overloading. How to achieve dynamic polymorphism in Java ? In Java, dynamic polymorphism is achieved through method overriding. What is Compile time polymorphism ? As the meaning is implicit, this is used to write the program in such a way, that flow of control is decided in compile time itself. It is achieved using method overloading. Example public static int add(int a, int b) { ...... ...... } public static double add(double a, double b) { ...... ...... } public static float add(float a, float b) { ...... ...... }
  • 70. What is Runtime polymorphism ? Run time Polymorphism also known as method overriding and it is achieve at runtime. Example class Vehicle { public void move() { System.out.println("Vehicles can move !!!!"); } } class MotorBike extends Vehicle { public void move() { System.out.println("MotorBike can move and accelerate too!!!"); } } class Demo { public static void main(String[] args) { Vehicle obj=new MotorBike(); obj.move(); // prints message MotorBike can move and accelerate too!!! obj=new Vehicle(); obj.move(); // prints message Vehicles can move!! } } What is Interface ? An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface..
  • 71. Main features of Interface ?  Interface cannot be instantiated  An interface does not contain any constructors  All of the methods in an interface are abstract Can an Interface be final ? No, because its implementation is provided by another class. What is marker interface ? An interface that have no data member and method is known as a marker interface.For example Serializable, Cloneable etc. What is difference between abstract class and interface ? An abstract class can have method body (non-abstract methods) but Interface have only abstract methods. How to implement Interface in Java ? Syntax interface A { .... .... } interface B { .... .... } class C implements A,B { .... ....
  • 72. } In Java Programming Inheritance is used for reuse features of one class into another class, Using this concept enhance (improve or increase) performance of application. What is Inheritance ? Inheritance is one of the main features of any object oriented programming. Using inheritance concept, a class (Sub Class) can inherit properties of another class (Super Class). So it is used for reuse features. Main advantage of using Inheritance ? Using this feature you can reuse features,less memory wastage, less time required to develop and application and improve performance of application. Types of Inheritance supported by Java ? Java support only four types of inheritance in java.  Single Inheritance  Multi level Inheritance  Hybrid Inheritance  Hierarchical Inheritance Why use Inheritance ?  For Code Re usability.  For Method Overriding.
  • 73. What is multilevel inheritance ? Getting the properties from one class object to another class object level wise with different priorities. Which of these keyword must be used to inherit a class ?  a) super  b) this  c) extent  d) extends d. extends What is Multiple Inheritance ? The concept of Getting the properties from multiple class objects to sub class object with same priorities is known as multiple inheritance. How Inheritance can be implemented in java ? Inheritance can be implemented in Java using two keywords, they are;  extends  Implements Which of these keywords is used to refer to member of base class from a sub class ?  a) upper  b) super  c) this  d) None of these Answer: b
  • 74. extends is used for developing inheritance between two classes and two interfaces. Implements keyword is used to developed inheritance between interface and class. What is syntax of inheritance ? Syntax public class subclass extends superclass { //all methods and variables declare here } Which inheritance are not supported bb Java ? Multi Inheritance is not supported by java. How Inheritance can be implemented in java ? Inheritance can be implemented in JAVA using these two keywords; extends and implements How do you implement multiple inheritance in java ? Using interfaces java can support multiple inheritance concept in java. Syntax interface A { .... .... } interface B { .... .... } class C implements A,B {
  • 75. .... .... } How do you implement multiple inheritance in java ? Using interfaces java can support multiple inheritance concept in java. in java can not extend more than one classes, but a class can implement more than one interfaces. Why we need to use Inheritance ? It is used for code re-usability and for Method Overriding. Can a class extend itself ? No, A class can't extend itself. What is syntax of Inheritance ? Syntax public class subclass extends superclass { //all methods and variables declare here } Example of Single Inheritance in Java Example class Faculty { float salary=30000; } class Science extends Faculty {
  • 76. float bonous=2000; public static void main(String args[]) { Science obj=new Science(); System.out.println("Salary is:"+obj.salary); System.out.println("Bonous is:"+obj.bonous); } } why Java Doesn't Support multiple Inheritance ? Due to ambiguity problem. What happens if super class and sub class having same field name ? Super class field will be hidden in the sub class. You can access hidden super class field in sub class using super keyword. How do you implement multiple inheritance in Java ? Example interface A { ..... ..... } interface B { ..... ..... } class C implements A,B { }
  • 77. Can we reduce the visibility of the inherited or overridden method ? Ans. No. Which of the following is tightly bound ? Inheritance or Composition ? Ans. Inheritance. Does a class inherit the constructor of its super class ? Ans. No