Você está na página 1de 21

JavaScript Tutorials is one of the best Quick reference to the JavaScript.

In this JavaScript
reference you will find most of the things about java script. JavaScript tutorial is classified into
sections with examples. This tutorial is mainly for the beginners but experienced programmer
can also learn many things from this JavaScript tutorial series.
This JavaScript Tutorial will teach you the fundamentals of JavaScript programming, including
the use of the core JavaScript objects and the syntax of the language like statements,
conditionals, loops, functions, etc. You will also learn how to immediately put JavaScript to
validate forms, calculate values, work with image rollovers and create other user interface.
JavaScript is widely used scripting language for mainly validating the user input on the client
side (browser). It is also used with the DHTML for creating interactive user interface design.

What is JavaScript? - Definition

In this article you learn the basics of JavaScript and create your first JavaScript program.
What is JavaScript?
JavaScript is scripting language used for client side scripting. JavaScript developed by Netscape
in 1995 as a method for validating forms and providing interactive content to web site. Microsoft
and Netscape introduced JavaScript support in their browsers.
Benefits of JavaScript
Following are the benefits of JavaScript.
• associative arrays
• loosely typed variables
• regular expressions
• objects and classes
• highly evolved date, math, and string libraries
• W3C DOM support in the JavaScript
Disadvantages of JavaScript
• Developer depends on the browser support for the JavaScript
• There is no way to hide the JavaScript code in case of commercial application
Creating your first JavaScript Program
In the first lesson we will create very simple JavaScript program and run in the Internet Explorer.
This example simply displays "Welcome to JavaScript World!" message in the browser.
Test JavaScript program from here.
Here is the code of JavaScript program:
<html>
<head>
<title>First Java Script</title>
<script language="JavaScript">
function sayhello(){
alert("Welcome to JavaScript World!");
}
</script>
</head>
<body>

<p><b>Click the following link to run your first java script


example</b></p>
<p><a href="javascript:sayhello()">Run JavaScript First
Program</a></p>

</body>
Writing Simple Java Script Program

In this article you learn the basics of JavaScript and create your first JavaScript program.
Creating your first JavaScript Program
In the last lesson you learned how to create simple java script program. To run the program open
the html file in any browser and click on the "Run Java Script First Program". The will display
the message box. Here is the screen shot of the browser.

Test JavaScript program from here.


Here is the code of JavaScript program:
<html>
<head>
<title>First Java Script</title>
<script language="JavaScript">
function sayhello(){
alert("Welcome to JavaScript World!");
}
</script>
</head>
<body>

<p><b>Click the following link to run your first java script


example</b></p>
<p><a href="javascript:sayhello()">Run JavaScript First
Program</a></p>

</body>
Following is the JavaScript program that will show the message:
<script language="JavaScript">
function sayhello(){
alert("Welcome to JavaScript World!");
}
</script>
The alert() function of the java script displays message.

JavaScript Statements

In this article you learn the basics of JavaScript and create your first JavaScript program.
JavaScript Statement
The JavaScript language supported Two type Condition.
1.if statement
2.Function
if Statement
The if statement is used to make decisions in JavaScript. Boolean operators are also used in
along with the if statement. The if statement is the most used features of JavaScript. It is
basically the same in JavaScript as it is in other programming languages.
Example
<HTML>
<HEAD>
</HEAD>
<SCRIPT language="JavaScript">
<!--
var num = 10
if(num == 10)
{
document.write("<B>Statement!</B><BR>")
}
//--></SCRIPT>
my program successfully completed

</BODY>
</HTML>
Function
The function keyword identifies as a function. The parameters in the parenthesis ( ) provide a
means of passing values to the function. There can be as many parameters separated by commas
as you need. This is perfectly ok to have a function with no parameters. These parameters are
variables which are used by the JavaScript statements inside the curly braces { }. The variable
keyword is not needed to declare the parameters in a function as variables because they are
automatically declared and initialized when the function is called. The function can return a
value by using the return keyword.
Example

<HTML>
<HEAD>
</HEAD>
<script languane="JavaScript">

function prod(a,b)
{
var x=a*b
return x;
}

var mul=prod(2,5);
document.write("multipication:"+mul);
</script>
</BODY>
</HTML>
Conditional JavaScript if-else Statement
The JavaScript Conditional Statement used to different actions and used to based on different
conditions. you want to execute some code if a condition is true and another code the condition is
not true, use the if....else statement.

Example
<HTML>
<HEAD>
</HEAD>
script type="text/javascript">
var a = new Date()
var time = a.getHours()
if (time < 20)
{
document.write("Good morning!")
}
else
{
document.write("Good day!")
}
</script>
</BODY>
</HTML>

JavaScript Variables and Data types

In this article you will learn the basics of JavaScript Variables and Data types.
JavaScript Variables
.Every piece of data is known as a value. When a value is referred in a statement, it is called a
literal value. For the same reason people are identified by names as opposed to "human" or
"person", literal values can be named in order to make repeated reference to them practical,
efficient and readable. These names are called variables.
Declaring and Initializing the Variables
var num // declare variable, has null value
num = 20 // assign a value, null value is replaced
//OR
var num=20 // declare AND assign value (initialize)
var a,b,c,d //multiple variables may be declared simultaneously
var a = 5, b = 6, c = 7,d=8 //multiple variables may be initialized simultaneously
Variable Names
Variable names cannot contain spaces, begin with a number and can not be used the underscore
(_) . JavaScript Variable name can not use any reserved keywords. The two words can either be
separated by an underscore (my_variable) or (myVariable).
Variable Scope
There are two types of Variable scope:-
1. Globle scope Variable,
2 . Local scope Variable.
1.Globle scope Variable:- A variable declared or initialized outside a function body has a global
scope, making it accessible to all other statements within the same document.
2. Globle scope Variable:- A variable declared or initialized within a function body has a local
scope, making it accessible only to statements within the same function body.
[NOTE:- If a variable is initialized inside a function body but the var keyword is left off, the
variable has a global scope and is only accessible after the function containing it is invoked. It is
safer to always use the var keyword ]
Java script Data type
Data Type:- A data type is defined by the value assigned to it . A variable could be a number on
one line, then assigned a string value and later be assigned an object reference. JavaScript would
change its data type dynamically .It also represent the data's nature. Data is directly treated on
those data types and calculate up on the works .
There are two types of the data types, As follow:-
1.Primitive data types
2.Compositive data types
1.Primitive data types:- Primitive data types are the simplest building blocks of a program.
There are following types :-
• numeric:-JavaScript supports both integers and floating point numbers .Integers are
whole numbers and it does not support the decimal numbers .Such as : 145 . Floating
point numbers are fractional numbers or decimal numbers . Such as : 12.50
• string:- String is a collection of characters enclosed in either single quotes and double
quotes .If the string starts with a single quotes and it must end with single quotes .If the
string starts with a double quotes and it must end with double quotes . Such as :
'Welcome to JavaScript'
or "Welcome to JavaScript".
• Boolean:-Boolean literals are logical values that have only one of two values, true or
false. It used to conditional sanitations. Our statements
are checked true or false then we use the Boolean variables.
• null:-The null value represents no value that means strings are empty .
• undefined:- A variables to be declared but given no any initial value then it runtime error
display

Example for :-This example is represent the sum of two floating numbers and print the messages
in single quotes and double quotes.
<html>
<head>
<script language="javascript">
function showAlert()
{
var a=200.40;
var b=10.50;
var sum=0;
sum=a+b;
document.write(" sum= "+sum);
document.write("\t\tHello\nworld!\n");
document.write('\nWelcome to JavaScript');
}
</script>
</head>
<body>

<script language="javascript">
showAlert();

</script>

</body>
</html>

This program is used to Boolean expression and it display the numbers between 1 to 500 and if
user to not enter the number then it display the you
did not enter any number.
<html>
<body>
<script type="text/javascript">
var n=0;
n=prompt("Enter a number");
document.write("Your entered number is :"+n);
if (n>=1 && n<10)
document.write("Your entered number is greater than 1 and
less than 10");
else if(n>=10 && n<20)
document.write("Your entered number is greater than 10 and
less than 20");
else if(n>=20 && n<30)
document.write("Your entered number is greater than 20 and
less than 30");
else if(n>=30 && n<40)
document.write("Your entered number is greater than 30 and
less than 40");
else if(n>=40 && n<100)
document.write("Your entered number is greater than 40 and
less than 100");
else if(n>=100 && n<=500)
document.write("Your entered number is greater than 100 or
less than 500");
else
document.write("You did not enter any number!")
</script>
</body>
</html>

String Number Operations in JavaScript

In this article you learn the basics of JavaScript and create your first JavaScript program.
What is String Number Operation?
The JavaScript String is a loosely type language. This is not mean that it has no data types that
the value of a variable or a JavaScript object property does not need to have a particular type of
the value assigned, or that it should be always hold the same type of value. JavaScript also freely
type-converts values into a type require by the context of their use. JavaScript being is the
loosely typed and willing to type-convert still does not save the programmer from need to the
think about the actual type of values that they are dealing with. A very common error in browser
scripting. for example, it is to read the value property of a form control into which the user is
expected to type a number and then add that value to another number. Because the value
properties of form controls are strings if the even then character is sequence they contain
represents a number of the attempt to add that string to a value, even if the value happens to be a
number, results in the second value being type-converted into a string and concatenated to the
end of the first string value from the from control. The problem arises from dual nature of the +
operator used for the both numeric addition and string concatenation. which the nature of the
operation performed is determined by the context, where only both the operation are numbers to
start with the + operator perform addition. Otherwise it converts all of its operands to strings and
does concatenation.
Converting String:
The String most often from the action + Operators. when one of its operators not a number. The
easy way of getting the string that results from type-conversion is to concatenate a value to
string. The alternative method of convert a value into a string to pass it is argument to the String
constructor called as a function. Exam:-
Var string Value=
String(d);
Converting Number:
The Converting values to numbers especially to strings numbers, it is an extremely common
requirement and many methods can be used. There are any mathematical operation except the
concatenation addition operator will force type-conversion. So the conversion of a string to a
number might entail performing a mathematical operation on the string representation of the
number that would not affect the resulting number, such as subtracting zero or multiplying by
one.
var numValue =
stringValue - 0;
var numValue =
stringValue * 1;
var numValue =
stringValue / 1;
String in JavaScript
The JavaScript language until now we have been focusing on the language constructs of
JavaScript: if statements, loops, functions, etc. This primer are going to take a step back and
cover the inner workings of some of the native JavaScript objects: Strings, Numbers and Arrays.

Example:
<html>
<head>
<Script language="JavaScript">
document.write(' Test'.indexOf('T'));
document.write('This '.lastIndexOf('T'));
document.write('This is test'.charAt(10));
document.write('This program
Test'.length);
document.write(' program'.substring(1,
10));
document.write('my exam Test'.substr(7,
10));
document.write('my
program'.toUpperCase());
document.write(' first JavaScript
program'.toLowerCase());
document.write("<br />")
</script>
</table>
</body>
</html>

Array in JavaScript
Array is the basically just a list of items. Each item an array can be whatever you want, but they
are usually related to one-another.
Example:
<html>
<head>
<script language="JavaScript">
var students = ['amar', 'rani', 'vinod',
'susil','santosh'];
var suffixes = ['1st', '2nd', '3rd',
'4th','5th'];
for(var i=0; i<=4; i++)
{
alert('The '+suffixes[i]+' student is
'+students[i]);
}
</script>
</head>
</body>
</html>
JavaScript in Number Operation
The numbers is a central task for the many programs. In fact, the desire to automate number
operations was the motivation that drove the invention of digital computers decades ago. we will
learn how to work with numbers in Java, including arithmetic, conversions, and other numeric
operations.
Example:

<html>
<head>
<Script
language="JavaScript">
var sum = 10 + 10;
sub = 15 - 5;
mul = 25 * 5; //multiplication
divided = 30 / 5;
modulus = 10 % 10;
//modulus division
document.write("sum:"+sum
);
document.write("sub:"+sub);
document.write("mul:"+mul)
;
document.write("divided:"+
divided);
document.write("modulus:"+
modulus);
</script>
</head>
</body>
</html>

Conditional Examples(if - else- switch case)


in JavaScript

In this article you will learn the basics of JavaScript conditions and create your conditional
examples in JavaScript .
About Conditional Statement
First of all we write the code after that we want to perform the different actions for different
decisions. We can use conditional statements in our code. Conditional statements in JavaScript
are used to perform different actions based on different conditions.
There are following types of Conditional Statements:-
• if statement:- It means the condition is true then our writing code is executed other wise
our code is not execute .
Syntax for the if statement:-
if ( expression )
{
statement1
statement2
}
• if - else statement:- This statement is used to when the condition is true then our code to
execute and when the condition is false then our written code is not execute.
Syntax for the if - else statement:-
if (expression)
statement1
else if (expression2)
statement2
else
statement3
• if...else if....else statement -This statement is used to if you want to select one of many
blocks of code to be executed .
• switch statement:-This statement is used to if you want to select one of many blocks of
code to be executed.
Syntax for the switch statement:-
switch (expression)
{
case1:
statement1
break
case2:
statement2
break
default:
statement3;
}
This example is if - else statement. It display the first of all the sum of two numbers and check
the condition after that it execute the code.
<html>
<head>
<script language="javascript">
function showAlert()
{
var a=20;
var b=10;
var sum=0;
sum=a+b;
document.write(" sum= "+sum);
if(sum==3)
{
document.write("Condition is true");
document.write("This is my first if statement program");
}
false
{
document.write("Condition is false");
document.write(" This is my first if -else statement program");
}
}
</script>
</head>
<body>

<script language="javascript">

showAlert();

</script>

</body>
</html>

This example is display to all months in a year for using the switch case:-
<body>
<script type="text/javascript">
var n=0;
n=prompt("Enter a number between 1 to 12:")
switch(n)
{
case(n="1"):
document.write("January");
break
case(n="2"):
document.write("Febuary");
break
case(n="3"):
document.write("March");
break
case(n="4"):
document.write("April");
break
case(n="5"):
document.write("May");
break
case(n="6"):
document.write("June");
break
case(n="7"):
document.write("July");
break
case(n="8"):
document.write("August");
break
case(n="9"):
document.write("September");
break
case(n="10"):
document.write("October");
break
case(n="11"):
document.write("November");
break
default:
document.write("December");
break
}
</script>
</body>

Conditions In Java Script

In this article you learn the basics of JavaScript and create your first JavaScript program.
About JavaScript
Java Script is Netscape's Cross - platform, Object - based Scripting language for Client and
Server applications. It is a Case sensitive application. JavaScript programs are usually embedded
directly in HTML files. The script executes when the user's browser opens the HTML file.
JavaScript is different from the Java language. Now the biggest problem is the imperfect
JavaScript implementations that today's browsers offer. Although all major browsers that are
version 3.0 or higher include JavaScript code support, they deal with JavaScript differently. In
fact, different versions of the same browser handle JavaScript differently. This makes it difficult
to create a complicated JavaScript code that work across all browsers. So always check your
pages on as many different browsers (and even platforms) as possible.
The Simple Example to display the Sum of two Digits :-
<html>
<head>
<script language="javascript">
function showAlert()
{
val1=20;
val2=10;
document.write("sum="+(val1+val2));
}
</script>
</head>
</body>

<script type="text/javascript">

showAlert();

</script>

</body>
</html>
JavaScript code is embedded in HTML within a <SCRIPT> tag. It can be used to any number of
JavaScript Statements. showAlert() is a function to use in JavaScript language. Val1 and Val2 is
a data type. we take the value 20 and 10 in val1 and val2. Document.write is also a function to
use print the Message and values. The result is 20 display on the Screen.

Looping In Java Script

In this article you learn the basics of JavaScript and create your first JavaScript program.
What is JavaScript loop?
The JavaScript loops used to execute the same block or code a specified number of times and
while a specified condition. JavaScript loops Very often write code, you want the same block of
code to run over and over again in a row. The Instead of adding several almost equal lines in a
script we can use loops to perform a task.

JavaScript supported Two different type looping :-


1.The For Loop
2.The while Loop
For Loop:
The JavaScript for loop is used the know in advance how many times of the script should run.
JavaScript loop Use a For loop to run time same block of code a specified the number.
Example:
<html>
<body>
<script language="javascript">
var i=0
for (i=0;i<=6;i++)
{
alert("The number is " + i)
}
</script>
</body>
</html>

The while Loop:


The while loop is used when the loop to execute and continue executing while the specified
condition
<html>
<body>
<script language="Javascript">
var i=0
while (i<=10)
{
document.write("serial number" + i)
document.write("<br />")
i=i+1
}
</script>
</table>
</body>
</html>
.
The do while loop
The JavaScript do...while loop is a variant of the while loop. The loop will be always execute a
block of code once and then it will repeat the loop as long as the specified condition is true. This
loop will be always executed once, even if the condition is false, because the loop code are
executed before the condition is tested.

Example:
<html>
<body>
<script language="Javascript">
var i=0
do
{
alert("number" + i)
i=i+1
}
while (i<3)
</script>
</table>
</body>
</html>

The for in:


This is not same as the for loop . The javascript for...in loop is used to provide to the enumerate
properties of a JavaScript object . This loop only found in JavaScript . This statement in the loop
are executed for each property of an object until every property has been accessed.
Example:
<html>
<head>
<Script language="Javascript">
var i;
var num= new Array(8,4,5,7,10);
for(i in num)
{
document.write(" " ,num[i]);
document.write("<br />")
}
</script>
</head>
</body>
</html>
Javascript looping Break and continue
There are two statements supported in javascript used in loop:- Break and continue
Break:
The JavaScript break command will break the loop and continue executing the code the follows
after the loop.
Example:
<html>
<head>
<Script language="Javascript">
var i=0
for (i=0;i<=6;i++)
{
if (i==3){break}
alert("number" + i)
}
</script>
</head>
</body>
</html>
Continue:
The JavaScript continue command will be break the current loop and continue with the next
value.
Example

<html>
<head>
<script language="JavaScript">
var i=0;
for (i=0;i<=8;i++)
{
if (i==4){continue}
document.write("value" + i)
document.write("</br>")
}
</script>
</head>
</body>
</html>

JavaScript Functions

In this article you will learn about the JavaScript functions.


What is JavaScript Function?
Java script Function is nothing but it is a reusable code-block that is execute when the function is
called. Function is defined in the head section of the code. The syntax of JavaScript function is
as follows:
function fname(prameter1,parameter2, ...)
{
JavaScript code 1
JavaScript code 2
....
}
While defining JavaScript function its important to remember that the keyword function should
be in lowercase other wise JavaScript won't understand it as function. If you write function in
uppercase the code will generate error. In the JavaScript semicolon is optional but its better to
put semi-colon as part of best practices. All the java script code are written inside the curly
braces.
Example:
<html>
<head>
<script language="javascript">
function showmessage(){
alert("How are you");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click
Here!"
onclick="showmessage()" >
</form>
</body>
</html>
Function starts with the function keyword and code of the function is enclosed in {..} brackets.
Functions are written inside the head section of the html document, because function does not
execute when the page loads. The alert function displays the message "How are you", when you
clicked on the button ("Click Here")..

To test the program click here.


What is the use of JavaScript Functions:
The java Script Function is very useful in writing the JavaScript code. It is used to group many
JavaScript codes under one name. For example you can write a function to validate email
address.
Built-in functions
JavaScript provides many built in functions that ease the development of JavaScript programs.
Here are the list of the built-in JavaScript functions:
JavaScript Build in Function Function Description
alert() The alert() built-in function displays the
alert dialog box.
The confirm() built-in function display the
confirm() confirmation dialog box. and ask the user
to determine from the two option .
The focus() built -in function built the
focus() pointed object active and put the curser on
the text field.
indexOf()
The prompt() built -in function display the
prompt() prompt dialog box. Inquiring the user for
input.
The select() built -in function used to
select()
select the pointed object.
The write() built in function used to write
write()
something on the document.

Function arguments: Through variable you can pass argument to function. The out put of the
function looks on the arguments given by you .
Example:
<html>
<head>
<script language="javascript">
function myfunction(text)
{
confirm(text)
}
</script>
</head>

<body>
<form>
<input type="button"
onclick="myfunction('Do you want to delete
it!')"
value="Delete">

<input type="button"
onclick="myfunction('Do you want to save it!')"
value="Save">
</form>
</body>
</html>

Você também pode gostar