0% found this document useful (0 votes)
119 views21 pages

2.1 Study Material - Javascript - An Introduction To Javascript

The document provides an introduction to JavaScript programming. It discusses key JavaScript concepts like variables, data types, operators, functions, and objects. It explains how to write JavaScript code and embed it in HTML pages using <script> tags. Examples are given to demonstrate how to declare variables, perform arithmetic, write functions, pass arguments to functions, and return values from functions.

Uploaded by

Meena M
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
119 views21 pages

2.1 Study Material - Javascript - An Introduction To Javascript

The document provides an introduction to JavaScript programming. It discusses key JavaScript concepts like variables, data types, operators, functions, and objects. It explains how to write JavaScript code and embed it in HTML pages using <script> tags. Examples are given to demonstrate how to declare variables, perform arithmetic, write functions, pass arguments to functions, and return values from functions.

Uploaded by

Meena M
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 21

III

3 V
5

CS8501
20CSPC501
THEORY OF COMPUTATION
INTERNET PROGRAMMING

UNIT No. 1
UNIT No. 2
1.3.Inductive Proof
2.1 JavaScript: An Introduction to Javascript

Version: 1.XX

1
CS8651
INTERNET PROGRAMMING

2.1 JavaScript Introduction

JavaScript is the scripting language of the Web. All modern HTML pages are using JavaScript.
Developed by Brendan Eich as a part of Netscape. JavaScript is the world's most popular
programming language.

It is an interpreted language. Scripting language is a specialized pgm language used to automate


tasks within s/w environments. It is the language for HTML, for the web, for servers, PCs,
laptops, tablets, phones, and more. JavaScripts in HTML must be inserted between <script> and
</script> tags. JavaScripts can be put in the <body> and in the <head> section of an HTML page.

The <script> Tag


To insert a JavaScript into an HTML page, use the <script> tag.

The <script> and </script> tells where the JavaScript starts and ends.
<script>
alert("My First JavaScript");
</script>

JavaScript in <body>
<!DOCTYPE html>
<html>
<body>
.
.
<script>
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph</p>");
</script>
.
.
</body>
</html>

JavaScript Statements
JavaScript statements are "commands" to the browser.
The purpose of the statements is to tell the browser what to do.
Semicolon separates JavaScript statements.

Normally you add a semicolon at the end of each executable statement.

2
CS8651
INTERNET PROGRAMMING

JavaScript Comments
Comments will not be executed by JavaScript.
Comments can be added to explain the JavaScript, or to make the code more readable.

Single line comments start with //.

// Write to a heading:
document.getElementById("myH1").innerHTML="Welcome to my Homepage";

JavaScript Multi-Line Comments

Multi line comments start with /* and end with */.

/*
The code below will write
to a heading and to a paragraph,
and will represent the start of
my homepage:
*/

Using Comments at the End of a Line

var x=5;    // declare x and assign 5 to it


var y=x+2;  // declare y and assign x+2 to it

JavaScript Variables

As with algebra, JavaScript variables can be used to hold values (x=5) or expressions (z=x+y).
Variable can have short names (like x and y) or more descriptive names (age, sum, totalvolume).

● Variable names must begin with a letter


● Variable names can also begin with $ and _ (but we will not use it)
● Variable names are case sensitive (y and Y are different variables)

Declaring (Creating) JavaScript Variables


Creating a variable in JavaScript is most often referred to as "declaring" a variable.

You declare JavaScript variables with the var keyword:

3
CS8651
INTERNET PROGRAMMING

var carname;

After the declaration, the variable is empty (it has no value).


To assign a value to the variable, use the equal sign:

carname="Tata";

However, you can also assign a value to the variable when you declare it:
var carname="Tata";

<button onclick="myFunction()">Try it</button>


<p id="demo"></p>
<script>
function myFunction()
{
var carname="Tata";
document.getElementById("demo").innerHTML=carname;
}
</script>

One Statement, Many Variables


You can declare many variables in one statement. Just start the statement with var and separate
the variables by comma:

var lastname="Sairam", age=30, job="carpenter";

Your declaration can also span multiple lines:

var lastname="Sairam",
age=30,
job="carpenter";

Value = undefined

4
CS8651
INTERNET PROGRAMMING

In computer programs, variables are often declared without a value. The value can be something
that has to be calculated, or something that will be provided later, like user input. Variable
declared without a value will have the value undefined.

The variable carname will have the value undefined after the execution of the following
statement:

var carname;

JavaScript Arithmetic

As with algebra, you can do arithmetic with JavaScript variables, using operators like = and +:
y=5;
x=y+2;

JavaScript Data Types


String, Number, Boolean, Array, Object, Null, Undefined.

JavaScript Strings
A string is a variable which stores a series of characters like "John Sairam".
A string can be any text inside quotes. You can use single or double quotes:

var carname="Tata XC60";


var carname='Tata XC60';

You can use quotes inside a string, as long as they don't match the quotes surrounding the string:

var answer="It's alright";


var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';

JavaScript Numbers
JavaScript has only one type of numbers. Numbers can be written with, or without decimals:

var x1=34.00;      // Written with decimals


var x2=34;         // Written without decimals

Extra large or extra small numbers can be written with scientific (exponential) notation:

5
CS8651
INTERNET PROGRAMMING

var y=123e5;      // 12300000


var z=123e-5;     // 0.00123

JavaScript Booleans

Booleans can only have two values: true or false.

var x=true;
var y=false;

Booleans are often used in conditional testing. You will learn more about conditional testing in a
later chapter of this tutorial.

JavaScript Arrays
The following code creates an Array called cars:

var cars=new Array();

cars[0]="Maruti";
cars[1]="Tata";
cars[2]="RENAULT";
or (condensed array):

var cars=new Array("Maruti","Tata","RENAULT");

<body>
<script>
var i;
var cars = new Array();
cars[0] = "Maruti";
cars[1] = "Tata";
cars[2] = "RENAULT";
for (i=0;i<cars.length;i++)
{
document.write(cars[i] + "<br>");
}
</script>

6
CS8651
INTERNET PROGRAMMING

</body>

JavaScript Objects – we will see it separately

JavaScript Functions

JavaScript Function Syntax


A function is written as a code block (inside curly { } braces), preceded by the function
keyword:

function functionname()
{
some code to be executed
}

The code inside the function will be executed when "someone" calls the function.
The function can be called directly when an event occurs (like when a user clicks a button), and it
can be called from "anywhere" by JavaScript code.

<head>
<script>
function myFunction()
{
alert("Hello World!");
}
</script>
</head>

<body>
<button onclick="myFunction()">Try it</button>
</body>

A JavaScript Function in <head>


In this example, a JavaScript function is placed in the <head> section of an HTML page.

The function is called when a button is clicked:

7
CS8651
INTERNET PROGRAMMING

<head>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML="My First JavaScript Function";
}
</script>
</head>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>

A JavaScript Function in <body>

In this example, a JavaScript function is placed in the <body> section of an HTML page.

The function is called when a button is clicked:

<html>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>

function myFunction()
{
document.getElementById("demo").innerHTML="My First JavaScript Function";
}
</script>
</body>
</html>

Calling a Function with Arguments

When you call a function, you can pass along some values to it, these values are called
arguments or parameters.

8
CS8651
INTERNET PROGRAMMING

These arguments can be used inside the function.


You can send as many arguments as you like, separated by commas (,)

myFunction(argument1,argument2)

Declare the argument, as variables, when you declare the function:

function myFunction(var1,var2)
{
some code
}
The variables and the arguments must be in the expected order. The first variable is given the
value of the first passed argument etc.

<body>

<p>Click the button to call a function with arguments</p>

<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>

<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>

</body>
The function above will alert "Welcome Harry Potter, the Wizard" when the button is
clicked.

Functions With a Return Value

Sometimes you want your function to return a value back to where the call was made.

This is possible by using the return statement.

9
CS8651
INTERNET PROGRAMMING

When using the return statement, the function will stop executing, and return the specified value.

Syntax
function myFunction()
{
var x=5;
return x;
}
The function above will return the value 5.

<body>

<p>This example calls a function which performs a calculation, and returns the result:</p>

<h1><p id="demo"></p></h1>

<script>
function myFunction(a,b)
{
return a*b;
}

document.getElementById("demo").innerHTML=myFunction(4,3);
</script>

</body>

O/P: This example calls a function which performs a calculation, and returns the result:
12

JavaScript Operators
= is used to assign values.
+ is used to add values.
<body>

10
CS8651
INTERNET PROGRAMMING

<p>Click the button to calculate x.</p>


<button onclick="myFunction()">Try it</button>

<p id="demo"></p>
<h1 id="d"></h1>

<script>
function myFunction()
{
y=5;
z=2;
x=y+z;
document.getElementById("demo").innerHTML=x;
document.getElementById("d").innerHTML=x;
}
</script>

</body>
O/P: Click the button to calculate x.
7
7
JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic between variables and/or values.
Given that y=5, the table below explains the arithmetic operators:
Re Re
Op Ex
sul sul
era Description am
t of t of
tor ple
x y
x=
+ Addition y+ 7 5
2
x=
- Subtraction 3 5
y-2
x=
* Multiplication 10 5
y*2
x=
/ Division 2.5 5
y/2

11
CS8651
INTERNET PROGRAMMING

Modulus x=
% (division y 1 5
remainder) %2
x=
+ 6 6
+y
++ Increment
x=
y+ 5 6
+
x=-
4 4
-y
-- Decrement
x=
5 4
y--

JavaScript Assignment Operators


Assignment operators are used to assign values to JavaScript variables.
Given that x=10 and y=5, the table below explains the assignment operators:
Op Sa Re
era Example me sul
tor As t
x=
= x=y  
5
x=x x=
+= x+=y
+y 15
x=x x=
-= x-=y
-y 5
x=x x=
*= x*=y
*y 50
x=x x=
/= x/=y
/y 2
x=x x=
%= x%=y
%y 0

Comparison operators are used in logical statements to determine equality or difference between
variables or values.
Given that x=5, the table below explains the comparison operators:
Ope Description Comp Retu
rato aring rns

12
CS8651
INTERNET PROGRAMMING

r
x==8 false
== equal to
x==5 true
x==="
exactly equal to (equal false
=== 5"
value and equal type)
x===5 true
!=  not equal x!=8 true
x!
 not equal (different true
!== =="5"
value or different type)
x!==5 false
>  greater than x>8 false
<  less than x<8 true
>=  greater than or equal to x>=8 false
<=  less than or equal to x<=8 true

How Can it be Used


Comparison operators can be used in conditional statements to compare values and take action
depending on the result:

if (age<18) x="Too young";

You will learn more about the use of conditional statements in the next chapter of this tutorial.

Logical Operators
Logical operators are used to determine the logic between variables or values.
Given that x=6 and y=3, the table below explains the logical operators:
O
pe
Description Example
rat
or
& and (x < 10 && y > 1) is

13
CS8651
INTERNET PROGRAMMING

& true
(x==5 || y==5) is
|| or
false
! not !(x==y) is true

Conditional Operator
JavaScript also contains a conditional operator that assigns a value to a variable based on some
condition.
Syntax
variablename=(condition)?value1:value2 
<body>

<p>Click the button to check the


age.</p>

Age:<input id="age" value="18" />


<p>Old enough to vote?</p>
<button onclick="myFunction()">Try
it</button>

<p id="demo"></p>

<script>
function myFunction()
{
var age,voteable;
age=document.getElementById("age").
value;
voteable=(age<18)?"Too young":"Old
enough";
document.getElementById("demo").inn
erHTML=voteable;
}
</script>

</body>

JavaScript If...Else Statements


Conditional Statements

14
CS8651
INTERNET PROGRAMMING

Very often when you write code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
● if statement - use this statement to execute some code only if a specified condition is true
● if...else statement - use this statement to execute some code if the condition is true and another
code if the condition is false
● if...else if....else statement - use this statement to select one of many blocks of code to be
executed
● switch statement - use this statement to select one of many blocks of code to be executed
If Statement
Use the if statement to execute some code only if a specified condition is true.
Syntax Make a "Good day" greeting if
if (condition) the time is less than 20:00:
 { if (time<20)
  code to be executed if condition   {
is true   x="Good day";
 }   }
Note that if is written in The result of x will be:
lowercase letters. Using Good day
uppercase letters (IF) will
generate a JavaScript error!

If...else Statement
Use the if....else statement to execute some code if a condition is true and another code if the
condition is not true.
Syntax If the time is less than 20:00,
if (condition) you will get a "Good day"
 { greeting, otherwise you will get
  code to be executed if condition a "Good evening" greeting
is true if (time<20)
 }   {
else   x="Good day";
 {   }
  code to be executed if condition else
is not true   {
 }   x="Good evening";
  }
The result of x will be:
Good day

15
CS8651
INTERNET PROGRAMMING

If...else if...else Statement


Use the if....else if...else statement to select one of several blocks of code to be executed.
Syntax if (time<10)
if (condition1)   {
 {   x="Good morning";
  code to be executed if   }
condition1 is true else if (time<20)
 }   {
else if (condition2)   x="Good day";
 {   }
  code to be executed if else
condition2 is true   {
 }   x="Good evening";
else   }
 { The result of x will be:
  code to be executed if neither Good day
condition1 nor condition2 is true
 }

The JavaScript Switch Statement


Use the switch statement to select one of many blocks of code to be executed.

16
CS8651
INTERNET PROGRAMMING

Syntax var day=new Date().getDay();


switch(n) switch (day)
{ {
case 1: case 0:
  execute code block 1   x="Today is Sunday";
  break;   break;
case 2: case 1:
  execute code block 2   x="Today is Monday";
  break;   break;
default: case 2:
  code to be executed if n is   x="Today is Tuesday";
different from case 1 and 2   break;
} case 3:
  x="Today is Wednesday";
  break;
case 4:
  x="Today is Thursday";
  break;
case 5:
  x="Today is Friday";
  break;
case 6:
  x="Today is Saturday";
  break;
}

The default Keyword


Use the default keyword to specify what to do if there is no match:

Example
If the day is NOT Saturday or Sunday, then write a default message:

var day=new Date().getDay();


switch (day)
{
case 6:
  x="Today is Saturday";
  break;
case 0:
  x="Today is Sunday";

17
CS8651
INTERNET PROGRAMMING

  break;
default:
  x="Looking forward to the Weekend";
}
The result of x will be:
Looking forward to the Weekend

JavaScript Loops
Different Kinds of Loops
JavaScript supports different kinds of loops:
● for - loops through a block of code a number of times
● for/in - loops through the properties of an object
● while - loops through a block of code while a specified condition is true
● do/while - also loops through a block of code while a specified condition is true

The For Loop

The for loop is often the tool you will use when you want to create a loop.
The for loop has the following syntax:
for (statement 1; statement 2; statement 3)
 {
  the code block to be executed
 }
for (var i=0; i<5; i++)
 {
  x=x + "The number is " + i + "<br>";
 }

<script> <script>
cars=["RENAULT","Tata","M cars=["RENAULT","Tata","
aruti","Ford"]; Maruti","Ford"];
for (var i=0,l=cars.length; i<l; i+ var i=2,len=cars.length;
+) for (; i<len; i++)
{ {
document.write(cars[i] + document.write(cars[i] +
"<br>"); "<br>");
} }
</script> </script>

18
CS8651
INTERNET PROGRAMMING

The For/In Loop


The JavaScript for/in statement loops through the properties of an object:
<html>
<body>
<p>Click the button to loop through
the properties of an object named
"person".</p>
<button onclick="myFunction()">Try
it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var txt="";
var
person={fname:"Suresh",lname:"M",a
ge:35};

for (var x in person)


{
//txt=txt + person[x];
document.write(x);
document.write(person[x]);
}
//
document.getElementById("demo").in
nerHTML=txt;
}
</script>
</body>
</html></body>
Output

The While Loop


The while loop loops through a block of code as long as a specified condition is true.

19
CS8651
INTERNET PROGRAMMING

Syntax while (i<5)


while (condition)  {
 {   x=x + "The number is " + i +
  code block to be executed "<br>";
 }   i++;
 }

The Do/While Loop


The do/while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition is true.
Syntax do
do  {
 {   x=x + "The number is " + i +
  code block to be executed "<br>";
 }   i++;
while (condition);  }
while (i<5);

The Break Statement

You have already seen the break statement used in an earlier chapter of this tutorial. It was used
to "jump out" of a switch() statement.

The break statement can also be used to jump out of a loop. 

for (i=0;i<10;i++)
 {
  if (i==3)
    {
    break;
    }
  x=x + "The number is " + i + "<br>";
 }

The Continue Statement

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.

for (i=0;i<=10;i++)
 {

20
CS8651
INTERNET PROGRAMMING

 if (i==3) continue; // i==3 will be skipped


  x=x + "The number is " + i + "<br>";
 }

JavaScript Labels

As you have already seen, in the chapter about the switch statement, JavaScript statements can be
labeled.

To label JavaScript statements you precede the statements with a colon:

label:
statements

cars=["RENAULT","Tata","Maruti","Ford"];
list:
{
document.write(cars[0] + "<br>");
document.write(cars[1] + "<br>");
document.write(cars[2] + "<br>");
break list; // after this stmt break in o/p ie no o/p
document.write(cars[3] + "<br>");
document.write(cars[4] + "<br>");
document.write(cars[5] + "<br>");
}

21

You might also like