JS 3
JS 3
JavaScript
Brendan Eich
1995
The language was initially called LiveScript and was later renamed JavaScript
What is JavaScript?
•JavaScript is a very powerful client-side scripting language.
•In other words, you can make your webpage more lively and
interactive, with the help of JavaScript.
Features of Java Script
Limitations of JavaScript
Client-side JavaScript does not allow the reading
or writing of files.
<SCRIPT>
JavaScript statements...
</SCRIPT>
• A document can have multiple SCRIPT tags, and each can enclose any
number of JavaScript statements.
Famous “Hello World” Program
<!DOCTYPE html>
<html>
<body>
<script language="JavaScript">
document.write(“Hello, World!”)
</script>
</body>
</html>
Script Where To use
• You can place any number of scripts in an HTML
document.
• Scripts can be placed in the <body>, or in
the <head> section of an HTML page, or in both.
– With in body section
– With in head section
– External file
JavaScript Display Possibilities
• JavaScript can "display" data in different ways:
Global Variable
Local Variable
<script> <script>
function abc(){ var value=50;//global variable
var x=10; //local variable function a(){ alert(value);
} }
</script> function b(){ alert(value);
}
</script>
Data Types
JavaScript provides different data types to hold different
types of values.
There are two types of data types in JavaScript.
1. Primitive data type
2. Non-primitive (reference) data type
Primitive data types
• There are five types of primitive data types in JavaScript.
They are as follows:
Data Type Description
String represents sequence of characters e.g. "hello"
Number represents numeric values e.g. 100
Boolean represents boolean value either false or true
Undefined represents undefined value
Null represents null i.e. no value at all
Cont..
• // Numbers:
let length = 16;
let weight = 7.5;
// Strings:
let color = "Yellow";
let lastName = "Johnson";
// Booleans
let x = true;
let y = false;
//undefined
let name=undefined;
//null
let name=null;
Non - Primitive data types
// Array object:
const cars =
["Saab", "Volvo", "BMW"];
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands.
For example:
var sum=10+20;
Here, + is the arithmetic operator and = is the assignment operator. There are
following types of operators in JavaScript.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
Arithmetic Operators
• if Statement
• if else statement
• if else if statement
Examples <script>
var a=20; if(a==10){
<script>
var a=20; document.write("a is equal to 10");
if(a>10){
document.write("value of a is greater than 10");
}
} else if(a==15){
</script> document.write("a is equal to 15");
<script> }
var a=20; else if(a==20){
if(a%2==0){ document.write("a is equal to 20");
document.write("a is even number"); }
} else{
else{ document.write("a is not equal to 10, 15 or
document.write("a is odd number"); 20");
}
}
</script>
</script>
JavaScript Switch
switch(expression){
case value1:
case value2:
......
default:
• The JavaScript loops are used to iterate the piece of code using for, while, do
while or for-in loops. It makes the code compact. It is mostly used in array.
1. for loop
2. while loop
3. do-while loop
4. for-in loop
while Loop Statements
while (condition)
{
code to be executed
}
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
Do while Loop Statements
do{
code to be executed
} while (condition);
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
For Loop Statements
for (initialization; condition; increment)
{
code to be executed
}
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>");
}
</script>
Break Statements
html>
<
<body>
<script type="text/javascript">
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20)
{
if (x == 5){
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Continue Statements
<html>
<body>
<script type="text/javascript"> var x = 1;
document.write("Entering the loop<br /> "); while (x < 10)
{
x = x + 1;
if (x == 5){
continue; // skill rest of the loop body
}
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Functions in Java Script
• A function is a JavaScript procedure a set of statements that
performs a specific task.
• A function definition has these basic parts:
• A function name.
1. Code reusability
2. Less coding
• Function Syntax
• The syntax of declaring function is given below.
function functionName([arg1, arg2, ...argN])
{
//code to be executed
}
Functions example
<script>
function msg(){
alert("hello! this is message");
}
</script>
<form>
<input type="button" onclick="msg()"/>
</form>
Function Arguments example
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
Function with Return Value
<script>
function getInfo(){
return “Welcome to Functions”;
}
</script>
<script>
document.write(getInfo());
</script>
JavaScript Array
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
By array literal
• The syntax of creating array using array literal is given below:
• var arrayname=[value 1,value 2,…… ,value N];
• As you can see, values are contained inside [ ] and separated by ,
(comma).
<script>
var emp=["abc", "xyz", "pqr"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
By creating instance of Array directly
• The syntax of creating array directly is given below:
• var arrayname=new Array();
• Here, new keyword is used to create instance of array. Let’s see the
example of creating array directly.
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++)
{
document.write(emp[i] + "<br>");
}
</script>
By using an Array constructor
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++)
{
document.write(emp[i] + "<br>");
}
</script>
Java Script Objects
<script>
// Create an Object:
const car = {type:"Fiat", model:"500", color:"white"};
1. By object literal
2. By creating instance of Object directly (using new
keyword)
3. By using an object constructor (using new keyword)
Creating Object by object literal
The syntax of creating object using object literal is given below:
object={property1:value1,property2:value2.propertyN:valueN}
<script>
emp={id:102,name:"Shyam
Kumar",salary:40000}
document.write(emp.id+" "+emp.name+"
"+emp.salary);</script>
By creating instance of Object
emp.id=101;
emp.name="Ravi Malik";
• You can use different Date constructors to create date object. It provides
methods to get and set day, month, year, hour, minute and seconds.
• Constructor
• You can use 4 variant of Date constructor to create date object.
1. Date()
2. Date(milliseconds)
3. Date(dateString)
4. Date(year, month, day, hours, minutes, seconds, milliseconds)
JavaScript date Methods
getFullYear()
getMonth() .
getDay()
getMinutes()
getSeconds()
getMilliseconds()
Examples on date Methods 1/2
• Let's see the simple example to print date object. It prints date and time both.
Current Date and Time:
<script>
var today=new Date();
document.getElementById('txt').innerHTML=today;
</script>
• Let's see another code to print date/month/year.
<script>
var date=new Date();
var day=date.getDate();
var month=date.getMonth()+1;
var year=date.getFullYear();
document.write("<br>Date is: "+day+"/"+month+"/"+year);
</script>
Examples on date Methods 2/2
• JavaScript Current Time Example
• Let's see the simple example to print current time of system. Current Time:
<span id="txt"></span>
<script>
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
</script>
By Math object
The JavaScript math object provides several constants and methods to perform
mathematical operation. Unlike date object, it doesn't have constructors.
Math.sqrt(n)
The JavaScript Math.sqrt(n) method returns the square root of the given number.
<script>
document.getElementById('p1').innerHTML=Math.sqrt(25);
</script>
JavaScript Math Object Methods
1. Math.sqrt(n)
• navigator Object
• The navigator object provides information about the browser and
device.
• Common navigator Properties:
• navigator.userAgent: Returns the user-agent string of the browser.
• navigator.language: Returns the language of the browser.
• navigator.platform: Indicates the platform (e.g., Windows, macOS).
• navigator.geolocation: Provides access to the device's location.
location Object
• 3. location Object
• The location object provides information about the current URL and allows
you to manipulate it.
• Common location Properties and Methods:
• location.href: Returns the full URL of the current page.
• location.hostname: Returns the domain name of the web host.
• location.pathname: Returns the path of the URL.
• location.search: Returns the query string (e.g., ?id=10).
• location.assign(url): Navigates to a new URL.
• location.reload(): Reloads the current page.
history Object
• 4. history Object
• The history object allows you to interact with the browser's
session history.
• Common history Methods:
• history.back(): Navigates to the previous page in history.
• history.forward(): Navigates to the next page in history.
• history.go(n): Navigates to a specific page in history (e.g., -1
for the previous page, 1 for the next page).
screen Object
• screen Object
• The screen object provides information about the user's screen.
• Common screen Properties:
• screen.width: Returns the width of the screen.
• screen.height: Returns the height of the screen.
• screen.availWidth: Returns the available width (excluding
taskbars).
• screen.availHeight: Returns the available height.
Document Object Model
The document object represents the whole html document.
JavaScript can access and change all the elements of an HTML document.
We can access and change the contents of document by its methods. The important
methods of document object are as follows:
Method Description
write("string") writes the given string on the document.
writeln("string") writes the given string on the document
with newline character at end.
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.
document.getElementById(id).style.property = new style
Accessing field value by document object
To get the value of input text by user, using document.form1.name.value to get the value
of name field. Here, document is the root element that represents the html document.
form1 is the name of the form. name is the attribute name of the input text. value is the
property, that returns the value of the input text. Simple example of document object that
prints name with welcome message.
<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>
document.getElementById() method
The document.getElementById() method returns the element of specified id.
In the previous slide, we have used document.form1.name.value to get the value of the input value.
Instead of this, we can use document.getElementById() method to get value of the input text. But we
need to define id for the input field.
Simple example of document.getElementById() method that prints cube of the given number.
<script type="text/javascript"> function getcube(){
var n=document.getElementById("number").value;
alert(n*n*n);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
document.getElementByName() method
The document.getElementsByName() method returns all the element of specified name.
document.getElementsByName("name").
Example of document.getElementsByName() method
In this example, we going to count total number of genders. Here, we are using getElementsByName()
method to get all the genders.
<script type="text/javascript">
function totalelements()
{
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male"> Female:<input type="radio"
name="gender" value="female">
The document.getElementsByTagName() method returns all the element of specified tag name.
The syntax of the getElementsByTagName() method is given below:
document.getElementsByTagName("name")
Example of document.getElementsByTagName() method
In this example, we going to count total number of paragraphs used in the document. To do this, we
have called the document.getElementsByTagName("p") method that returns the total paragraphs.
• DHTML is a TERM describing the art of making dynamic and interactive web pages.
image