You are on page 1of 70

JavaScript

• Why Study JavaScript?


• JavaScript is one of the 3 languages all web
developers must learn:
  1. HTML to define the content of web pages
  2. CSS to specify the layout of web pages
  3. JavaScript to program the behavior of web pages
JavaScript Origins
• JavaScript, which was originally named LiveScript, was
developed by Netscape.
• In late 1995 LiveScript became a joint venture of Netscape and
Sun Microsystems and its name was changed to JavaScript.
• Netscape's JavaScript has gone through extensive evolution,
moving from version 1.0 to version 1.5, primarily by adding
many new features.
• A language standard for JavaScript was developed in the late
1990s by the European Computer Manufacturers Association
(ECMA) as ECMA-262.
• This standard has also been approved by the International
Standards Organization (ISO) as ISO-16262.
• The official name of the standard language is ECMA
SCRIPT.
• JavaScript can be divided into three parts: the core,
client side, and server side.
• The core is the heart of the language, including its
operators, expressions, statements, and subprograms.
• Client-side JavaScript is a collection of objects that
support control of a browser and interactions with users.
For example, with JavaScript, an XHTML document can be
made to be responsive to user inputs such as mouse clicks
and keyboard use.
• Server-side JavaScript is a collection of objects that make
the language useful on a Web server; for example, to
support communication with a database management
system.
What is JavaScript ?
• JavaScript is a dynamic computer programming
language.
• It is lightweight and most commonly used as a part
of web pages, whose implementations allow client-
side script to interact with the user and make
dynamic pages. It is an interpreted programming
language with object-oriented capabilities.
JavaScript - Syntax
• JavaScript can be implemented using JavaScript
statements that are placed within the <script>...
</script> HTML tags in a web page.
• You can place the <script> tags, containing your
JavaScript, anywhere within your web page, but it is
normally recommended that you should keep it
within the <head> tags.
• The <script> tag alerts the browser program to start
interpreting all the text between these tags as a
script. 
• A simple syntax of your JavaScript will appear as follows.
<script type=“text/javascript” src=“filename.js”>
JavaScript code
</script>
• The script tag takes two important attributes −
• Language − This attribute specifies what scripting
language you are using. Typically, its value will be
javascript. Although recent versions of HTML (and
XHTML, its successor) have phased out the use of this
attribute.
• Type − This attribute is what is now recommended to
indicate the scripting language in use and its value
should be set to "text/javascript".
Adding JavaScript to HTML
Pages
• There are typically three ways to add JavaScript
to a web page:
• Embedding the JavaScript code between a pair of
<script> and </script> tag.
• Creating an external JavaScript file with the .js
extension and then load it within the page
through the src attribute of the <script> tag.
• Placing the JavaScript code directly inside an
HTML tag using the special tag attributes such
as onclick, onmouseover, onkeypress, onload,
etc.
• Embedding the JavaScript Code
• You can embed the JavaScript code directly within
your web pages by placing it between the <script>
and </script> tags.
• The <script> tag indicates the browser that the
contained statements are to be interpreted as
executable script and not HTML.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Embedding JavaScript</title>
</head>
<body>
<script>
var greet = "Hello World!";
document.write(greet); // Prints: Hello World!
</script>
</body>
</html>
• Calling an External JavaScript File
• You can also place your JavaScript code into a
separate file with a .js extension, and then call that
file in your document through the src attribute of
the <script> tag.
Hello.js

// A function to display a message


function sayHello() {
alert("Hello World!");
document.write("hello world");
}

// Call function on click of the button


document.getElementById("myBtn").onclick = sayHello;
<!DOCTYPE html>
<html>
<head>

<title>Including External JavaScript File</title>


</head>
<body>
<button type="button" id="myBtn">Click Me</button>
<script src="hello.js"></script>
</body>
</html>
• Placing the JavaScript Code Inline
• You can also place JavaScript code inline by
inserting it directly inside the HTML tag using the
special tag attributes such as onclick, onmouseover,
onkeypress, onload, etc.
• However, you should avoid placing large amount of
JavaScript code inline as it clutters up your HTML
with JavaScript and makes your JavaScript code
difficult to maintain. 
<!DOCTYPE html>
<html>
<head>
<title>Inlining JavaScript</title>
</head>
<body>
<button onclick="alert('Hello World!')">Click Me</button>
</body>
</html>
Positioning of Script inside HTML
Document

• The <script> element can be placed in the <head>, or


<body> section of an HTML document. But ideally, scripts
should be placed at the end of the body section, just before
the closing </body> tag, it will make your web pages load
faster, since it prevents obstruction of initial page
rendering.

• Each <script> tag blocks the page rendering process until it


has fully downloaded and executed the JavaScript code, so
placing them in the head section (i.e. <head> element) of
the document without any valid reason will significantly
impact your website performance.
Control Statements (Conditional
Statements)
• Conditional statements are used to decide the flow
of execution based on different conditions.
• If a condition is true, you can perform one action
and if the condition is false, you can perform
another action.
Different Types of Conditional Statements

• There are mainly three types of conditional


statements in JavaScript.
• If statement
• If…Else statement
• If…Else If…Else statement
• If statement
• You can use If statement if you want to check only a
specific condition.
• Syntax
if (condition)
{
lines of code to be executed if condition is true
}
<html>
<head>
<title>IF Statments!!!</title>
<script>
var age = prompt("Please enter your age");
if(age>=18)
document.write("You are Eligible for license <br />");
if(age<18)
document.write("You are NOT eligible <br />");
</script>
</head>
<body>
</body>
</html>
• If…Else statement
• You can use If….Else statement if you have to check two
conditions and execute a different set of codes.
• Syntax

if (condition)
{
lines of code to be executed if the condition is true
}
else
{
lines of code to be executed if the condition is false
}
<html>
<head>
<title>If...Else Statments!!!</title>
<script type="text/javascript">
// Get the current hours
var hours = new Date().getHours();
if(hours<12)
document.write("Good Morning!!!<br />");
else
document.write("Good Afternoon!!!<br />");
</script>
</head>
<body>
</body>
</html>
• If…Else If…Else statement
• You can use If….Else If….Else statement if you want to check more
than two conditions.
if (condition1)
{
lines of code to be executed if condition1 is true
}
else if(condition2)
{
lines of code to be executed if condition2 is true
}
else
{
lines of code to be executed if condition1 is false and condition2 is false
}
<html>
<head>
<script type="text/javascript">
var one = prompt("Enter the first number");
var two = prompt("Enter the second number");
one = parseInt(one);
two = parseInt(two);
if (one == two)
document.write(one + " is equal to " + two + ".");
else if (one<two)
document.write(one + " is less than " + two + ".");
else
document.write(one + " is greater than " + two + ".");
</script>
</head>
<body>
</body>
</html>
Switch...Case Statement
• The switch..case statement is an alternative to
the if...else if...else statement, which does almost
the same thing.
• The switch...case statement tests a variable or
expression against a series of values until it finds a
match, and then executes the block of code
corresponding to that match. 
switch(x){
    case value1:
        // Code to be executed if x === value1
        break;
    case value2:
        // Code to be executed if x === value2
        break;
    ...
    default:
        // Code to be executed if x is different from all
values
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Switch Case Statement</title>
</head>
<body>
<script>
var d = new Date();

switch(d.getDay()) {
case 0:
document.write("Today is Sunday.");
break;
case 1:
document.write("Today is Monday.");
break;
case 2:
document.write("Today is Tuesday.");
break;
case 3:
document.write("Today is Wednesday.");
break;
case 4:
document.write("Today is Thursday.");
break;
case 5:
document.write("Today is Friday.");
break;
case 6:
document.write("Today is Saturday.");
break;
default:
document.write("No information available for that day.");
break;
}
</script>
</body>
</html>
Looping Statements
• Loops are used to execute the same block of code
again and again, as long as a certain condition is
met.
• The basic idea behind a loop is to automate the
repetitive tasks within a program to save the time
and effort.
• while — loops executes a block of code as long as
the condition specified evaluates to true.
• do…while — loops executes a block of code once;
then the condition is evaluated. If the condition is
true, the statement is repeated as long as the
specified condition is true.
• for — loops executes a block of code until the
counter reaches a specified number.
• The while Loop
• The while loop loops through a block of code as long
as the specified condition evaluates to true. As soon
as the condition fails, the loop is stopped.
• The generic syntax of the while loop is:

while(condition)
{
    // Code to be executed
}
<html >
<head>
<title>JavaScript While Loop</title>
</head>
<body>
<script>
var i = 1;
while(i <= 5) {
document.write("<p>The number is " + i + "</p>");
i++;
}
</script>
</body>
</html>
• do…while loop
• The do…while loop is very similar to while loop. The
only difference is that in do…while loop, the block of
code gets executed once even before checking the
condition.
• Syntax:
do
{
block of code to be executed
} while (condition)
<html>
<head>
<script type="text/javascript">
document.write("<b>Using do...while loops </b><br />");
var i = 2;
document.write("Even numbers less than 20<br />");
do
{
document.write(i + "<br />");
i = i + 2;
}while(i<20)
</script>
</head>
<body>
</body>
</html>
• for loop
• The parameters of the for loop statement have following
meanings:
• initialization — it is used to initialize the counter variables, and
evaluated once unconditionally before the first execution of the
body of the loop.
• condition — it is evaluated at the beginning of each iteration. If it
evaluates to true, the loop statements execute. If it evaluates to
false, the execution of the loop ends.
• increment — it updates the loop counter with a new value each
time the loop runs.
• Syntax:
for(initialization; condition; increment)
{
    // Code to be executed
}
<html>
<head>
<script type="text/javascript">
var students = new Array("John", "Ann", "Aaron", "Edwin", "Elizabeth");
document.write("<b>Using for loops </b><br />");
for (i=0;i<students.length;i++)
{
document.write(students[i] + "<br />");
}
</script>
</head>
<body>
</body>
</html>
JavaScript DOM
• The Document Object Model, or DOM for short, is a platform
and language independent model to represent the HTML or
XML documents.
• It defines the logical structure of the documents and the way
in which they can be accessed and manipulated by an
application program.
• In the DOM, all parts of the document, such as elements,
attributes, text, etc. are organized in a hierarchical tree-like
structure.
• HTML DOM which provides a standard interface for accessing
and manipulating HTML documents through JavaScript. 
JavaScript DOM methods 
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Mobile OS</h1>
<ul>
<li>Android</li>
<li>iOS</li>
</ul>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>

<title>JavaScript Select Topmost Elements</title>


</head>
<body>
<h1>hello</h1>
<script>
// Prints lang attribute value of html element
document.write(document.documentElement.getAttribute("lang")); // Prints: en
document.write("<br>");

// Set background color of body element


document.body.style.background = "yellow";

// Prints tag name of the head element's first child


document.write(document.body.firstElementChild.nodeName);
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Select an Element by its ID Attribute</title>
</head>
<body>
<p id="mark">This is a paragraph of text.</p>
<p>This is another paragraph of text.</p>

<script>
// Selecting element with id mark
var match = document.getElementById("mark");

// Highlighting element's background


match.style.background = "yellow";
</script>
</body>
</html>
JavaScript Operators
• What are Operators in JavaScript
• Operators are symbols or keywords that tell the
JavaScript engine to perform some sort of actions.
For example, the addition (+) symbol is an operator
that tells JavaScript engine to add two variables or
values
• JavaScript Arithmetic Operators
• The arithmetic operators are used to perform
common arithmetical operations, such as addition,
subtraction, multiplication etc. Here's a complete
list of JavaScript's arithmetic operators:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Arithmetic Operators</title>
</head>
<body>
<script>
var x = 10;
var y = 4;
document.write(x + y); // Prints: 14
document.write("<br>");
document.write(x - y); // Prints: 6
document.write("<br>");
document.write(x * y); // Prints: 40
document.write("<br>");
document.write(x / y); // Prints: 2.5
document.write("<br>");
document.write(x % y); // Prints: 2
</script>
</body>
</html>
• JavaScript Assignment Operators
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Assignment Operators</title>
</head>
<body>
<script>
var x; // Declaring Variable
x = 10;
document.write(x + "<br>"); // Prints: 10
x = 20;
x += 30;
document.write(x + "<br>"); // Prints: 50
x = 50;
x -= 20;
document.write(x + "<br>"); // Prints: 30
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript String Operators</title>
</head>
<body>
<script>
var str1 = "Hello";
var str2 = " World!";
document.write(str1 + str2 + "<br>"); // Outputs: Hello World!
str1 += str2;
document.write(str1); // Outputs: Hello World!
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Logical Operators</title>
</head>
<body>
<script>
var year = 2018;
// Leap years are divisible by 400 or by 4 but not 100
if((year % 400 == 0) || ((year % 100 != 0) && (year % 4 == 0))){
document.write(year + " is a leap year.");
} else{
document.write(year + " is not a leap year.");
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Comparison Operators</title>
</head>
<body>
<script>
var x = 25;
var y = 35;
var z = "25";
document.write(x == z); // Prints: true
document.write("<br>");
document.write(x === z); // Prints: false
document.write("<br>");
document.write(x != y); // Prints: true
document.write("<br>");
document.write(x !== z); // Prints: true
document.write("<br>");

document.write(x < y); // Prints: true


document.write("<br>");

document.write(x > y); // Prints: false


document.write("<br>");

document.write(x <= y); // Prints: true


document.write("<br>");

document.write(x >= y); // Prints: false


</script>
</body>
</html>
JavaScript Variable
• Variables are used to store values (name = “John”) or
expressions (sum = x + y).
• Declare Variables in JavaScript
• Before using a variable, you first need to declare it.
You have to use the keyword var to declare a variable
like this:
var name;
• Assign a Value to the Variable
• You can assign a value to the variable either while
declaring the variable or after declaring the
variable.
var name = "John";
OR
var name; name = "John";
// Declaring multiple Variables
var name = "Peter Parker", age = 21, isMarried = false;

/* Longer declarations can be written to span


multiple lines to improve the readability */
var name = "Peter Parker",
age = 21,
isMarried = false;
• Naming Variables
• Though you can name the variables as you like, it is a good
programming practice to give descriptive and meaningful
names to the variables. Moreover, variable names should
start with a letter and they are case sensitive. Hence the
variables student name and studentName are different
because the letter n in a name is different (n and N).
• These are the following rules for naming a JavaScript
variable:
• A variable name must start with a letter, underscore (_), or dollar
sign ($).
• A variable name cannot start with a number.
• A variable name can only contain alpha-numeric characters (A-
z, 0-9) and underscores.
• A variable name cannot contain spaces.
• A variable name cannot be a JavaScript keyword or a JavaScript
reserved word.
JavaScript Array
• What is an Array?
• An array is an object that can store a collection of
items. Arrays become really useful when you need
to store large amounts of data of the same type.
• JavaScript Create Array
• You can create an array in JavaScript as given below.
var students = ["John", "Ann", "Kevin"];
• Here, you are initializing your array as and when it
is created with values “John”, “Ann” and “Kevin”.
The index of “John”, “Ann” and “Kevin” is 0, 1 and 2
respectively. 
• You can also create an array using Array constructor like this:

var students = new Array("John", "Ann", "Kevin");


OR

var students = new Array();

students[0] = "John";

students[1] = "Ann";

students[2] = "Kevin";
JavaScript Array Methods
• length property –> If you want to know the number of elements
in an array, you can use the length property.
• prototype property –> If you want to add new properties and
methods, you can use the prototype property.
• reverse method –> You can reverse the order of items in an array
using a reverse method.
• sort method –> You can sort the items in an array using sort
method.
• pop method –> You can remove the last item of an array using a
pop method.
• shift method –> You can remove the first item of an array using
shift method.
• push method –> You can add a value as the last item of the array.
<html>
<head>
<title>Arrays!!!</title>
<script type="text/javascript">
var students = new Array("John", "Ann", "Aaron", "Edwin", "Elizabeth");
Array.prototype.displayItems=function(){
for (i=0;i<this.length;i++){
document.write(this[i] + "<br />");
}
}
document.write("students array<br />");
students.displayItems();
document.write("<br />The number of items in students array is " + students.length + "<br />");
document.write("<br />The SORTED students array<br />");
students.sort();
students.displayItems();
document.write("<br />The REVERSED students array<br />");
students.reverse();
students.displayItems();
document.write("<br />THE students array after REMOVING the LAST item<br />");
students.pop();
students.displayItems();
document.write("<br />THE students array after PUSH<br />");
students.push("New Stuff");
students.displayItems();

</script>
</head>
<body>
</body>
</html>
JavaScript Functions
• What is Function?
• A function is a group of statements that perform
specific tasks and can be kept and maintained
separately form main program.
• Advantages of using functions
• Functions reduces the repetition of code within a
program
• Functions makes the code much easier to maintain 
• Functions makes it easier to eliminate the errors
Defining and Calling a Function
• The declaration of a function start with the function
keyword, followed by the name of the function you want
to create, followed by parentheses i.e. ( ) and finally
place your function's code between curly brackets { }.
• Syntax:
function functionName() {
// Code to be executed
}
• Once a function is defined it can be called (invoked) from
anywhere in the document, by typing its name followed
by a set of parentheses
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Define and Call a Function</title>
</head>
<body>
<script>
// Defining function
function sayHello() {
document.write("Hello, welcome to this website!");
}
// Calling function
sayHello(); // Prints: Hello, welcome to this website!
</script>
</body>
</html>
Adding Parameters to
Functions
• You can specify parameters when you define your function to
accept input values at run time. The parameters work like
placeholder variables within a function; they're replaced at
run time by the values (known as argument) provided to the
function at the time of invocation.
• Parameters are set on the first line of the function inside the
set of parentheses, like this:

function functionName(parameter1, parameter2, parameter3)


{
// Code to be executed
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Add Parameters to a Function</title>
</head>
<body>
<script>
// Defining function
function displaySum(num1, num2) {
var total = num1 + num2;
document.write(total);
}
// Calling function
displaySum(6, 20); // Prints: 26
document.write("<br>");
displaySum(-5, 17); // Prints: 12
</script>
</body>
</html>

You might also like