SlideShare a Scribd company logo
1 of 87
JAVASCRIPT
Tutorial
Introduction of JavaScript
JavaScript developed by Branden Eiach in 1995.
JavaScript is a lightweight,
interpreted programming language.
It is designed for creating network-centric applications.
It is complimentary to and integrated with Java.
JavaScript is very easy to implement because it is
integrated with HTML. It is open and cross-platform.
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 was first known as LiveScript, but Netscape changed its
name to JavaScript, possibly because of the excitement being
generated by Java. JavaScript made its first appearance in Netscape
2.0 in 1995 with the name LiveScript. The general-purpose core of the
language has been embedded in Netscape, Internet Explorer, and
other web browsers.
Why to Learn JavaScript
JavaScript is a MUST for students and working professionals to become a great Software Engineer
specially when they are working in Web Development Domain. I will list down some of the key
advantages of learning JavaScript:
• JavaScript is the most popular programming language in the world and that makes it a
programmer’s great choice. Once you learnt JavaScript, it helps you developing great front-end as
well as back-end softwares using different JavaScript based frameworks like jQuery, Node.JS etc.
• JavaScript is everywhere, it comes installed on every modern web browser and so to learn
JavaScript you really do not need any special environment setup. For example Chrome, Mozilla
Firefox , Safari and every browser you know as of today, supports JavaScript.
• JavaScript helps you create really beautiful and crazy fast websites. You can develop your website
with a console like look and feel and give your users the best Graphical User Experience.
• JavaScript usage has now extended to mobile app development, desktop app development, and
game development. This opens many opportunities for you as JavaScript Programmer.
Client-Side JavaScript
❑Client-side JavaScript is the most common form of the language. The script
should be included in or referenced by an HTML document for the code to be
interpreted by the browser.
❑It means that a web page need not be a static HTML, but can include
programs that interact with the user, control the browser, and dynamically
create HTML content.
❑The JavaScript client-side mechanism provides many advantages over
traditional CGI server-side scripts. For example, you might use JavaScript to
check if the user has entered a valid e-mail address in a form field.
❑The JavaScript code is executed when the user submits the form, and only if
all the entries are valid, they would be submitted to the Web Server.
❑JavaScript can be used to trap user-initiated events such as button clicks, link
navigation, and other actions that the user initiates explicitly or implicitly.
Advantages of JavaScript
• Less server interaction − You can validate user input before sending
the page off to the server. This saves server traffic, which means less
load on your server.
• Immediate feedback to the visitors − They don't have to wait for a
page reload to see if they have forgotten to enter something.
• Increased interactivity − You can create interfaces that react when
the user hovers over them with a mouse or activates them via the
keyboard.
• Richer interfaces − You can use JavaScript to include such items as
drag-and-drop components and sliders to give a Rich Interface to your
site visitors.
Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the
following important features −
• Client-side JavaScript does not allow the reading or writing of files. This has been kept
for security reason.
• JavaScript cannot be used for networking applications because there is no such
support available.
• JavaScript doesn't have any multi-threading or multiprocessor capabilities.
Once again, JavaScript is a lightweight, interpreted programming language that allows
you to build interactivity into otherwise static HTML pages
Uses of JavaScript
✔Client side validation - This is really important to verify any user input before submitting it to
the server and Javascript plays an important role in validting those inputs at front-end itself.
✔Manipulating HTML Pages - Javascript helps in manipulating HTML page on the fly. This
helps in adding and deleting any HTML tag very easily using javascript and modify your HTML
to change its look and feel based on different devices and requirements.
✔User Notifications - You can use Javascript to raise dynamic pop-ups on the webpages to give
different types of notifications to your website visitors.
✔Back-end Data Loading - Javascript provides Ajax library which helps in loading back-end
data while you are doing some other processing. This really gives an amazing experience to
your website visitors.
✔Presentations - JavaScript also provides the facility of creating presentations which gives
website look and feel. JavaScript provides RevealJS and BespokeJS libraries to build a web-
based slide presentations.
✔Server Applications - Node JS is built on Chrome's Javascript runtime for building fast and
scalable network applications. This is an event based library which helps in developing very
sophisticated server applications including Web Servers.
There could be 1000s of good reasons
to learn JavaScript Programming. But
one thing for sure, to learn
any programming language, not only
JavaScript, you just need to code, and
code and finally code until you become
expert.
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 ...>
JavaScript code
</script>
Hello World using JavaScript
Just to give you a little excitement about JavaScript programming, I'm going to give you a small
conventional Javascript Hello World program
<html>
<body>
<script language = "javascript" type
= "text/javascript">
<!-- document.write("Hello World!")
//-->
</script>
</body>
</html>
This code will produce the following result −
Hello World!
Live Demo “Hello World using JavaScript”
Case Sensitivity
JavaScript is a case-sensitive language. This means that
the language keywords, variables, function names, and
any other identifiers must always be typed with a
consistent capitalization of letters.
So the identifiers Time and TIME will convey different
meanings in JavaScript.
NOTE − Care should be taken while writing variable and
function names in JavaScript.
Comments in JavaScript
JavaScript supports both C-style and C++-style comments, Thus −
• Any text between a // and the end of a line is treated as a comment and is
ignored by JavaScript.
• Any text between the characters /* and */ is treated as a comment. This may
span multiple lines.
• JavaScript also recognizes the HTML comment opening sequence <!--.
JavaScript treats this as a single-line comment, just as it does the // comment.
• The HTML comment closing sequence --> is not recognized by JavaScript so
it should be written as //-->.
The following example shows how to use comments in JavaScript.
<script language = "javascript" type = "text/javascript">
<!-- // This is a comment. It is similar to comments in C++
/*
*This is a multi-line comment in JavaScript
*It is very similar to comments in C Programming
*/
//-->
</script>
JavaScript Variables
◦ JavaScript has variables. Variables can be thought of as named containers. You can place data into
these containers and then refer to the data simply by naming the container.
◦ Before you use a variable in a JavaScript program, you must declare it. Variables are declared with
the var keyword as follows.
You can also declare multiple variables with the same var keyword as follows −
<script type = "text/javascript">
<!–
var money;
var name;
//-->
</script>
<script type = "text/javascript">
<!–
var money, name;
//-->
</script>
Live demo how to declare variables
JavaScript Datatypes
One of the most fundamental characteristics of a programming language is the set of data types it supports. These are
the type of values that can be represented and manipulated in a programming language.
JavaScript allows you to work with three primitive data types −
• Numbers, eg. 123, 120.50 etc.
var a = 25; // integer
var b = 80.5; // floating-point number
• Strings of text e.g. "This text string" etc.
var a = 'Hi there!'; // using single quotes
var b = "Hi there!"; // using double quotes
• Boolean e.g. true or false.
var isReading = true; // yes, I'm reading
var isSleeping = false; // no, I'm not sleeping
JavaScript does not make a distinction between integer values and floating-point values. All numbers in JavaScript are
represented as floating-point values. JavaScript represents numbers using the 64-bit floating-point format defined by
the IEEE 754 standard.
The Undefined Data Type
var a;
var b = "Hello World!“;
alert(a) // Output: undefined
alert(b) // Output: Hello World!
The Null Data Type
var a = null;
alert(a); // Output: null
var b = "Hello World!"
alert(b); // Output: Hello World!
b = null;
alert(b) // Output: null
Reserved Keywords
abstract else instanceof switch
boolean enum int synchronized
break export interface this
byte extends Long throw
case false native throws
catch final new transient
char finally null true
class float package try
const for private typeof
continue function protected var
debugger goto public void
default if return volatile
delete implements short while
do import static with
double in super
JavaScript Operators
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, while the
equal-to (==), greater-than (>) or less-than (<) symbols are the
operators that tells JavaScript engine to compare two
variables or values, and so on.
JavaScript Arithmetic Operators
Operator Description Example Result
+ Addition x + y Sum of x and y
- Subtraction x - y Difference of x and y.
* Multiplication x * y Product of x and y.
/ Division x / y Quotient of x and y
% Modulus x % y Remainder of x
divided by y
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:
Example of Arithmetic Operator
var x = 10;
var y = 4;
alert(x + y); // 0utputs: 14
alert(x - y); // 0utputs: 6
alert(x * y); // 0utputs: 40
alert(x / y); // 0utputs: 2.5
alert(x % y); // 0utputs: 2
JavaScript Assignment Operators
Operator Description Example Is The Same As
= Assign x = y x = y
+= Add and assign x += y x = x + y
-= Subtract and assign x -= y x = x - y
*= Multiply and assign x *= y x = x * y
/= Divide and assign
quotient
x /= y x = x / y
%= Divide and assign
modulus
x %= y x = x % y
The assignment operators are used to assign values to variables.
The following example will show you these
assignment operators in action:
var x; // Declaring Variable
x = 10; alert(x); // Outputs: 10
x = 20; x += 30; alert(x); // Outputs: 50
x = 50; x -= 20; alert(x); // Outputs: 30
x = 5; x *= 25; alert(x); // Outputs: 125
x = 50; x /= 10; alert(x); // Outputs: 5
x = 100; x %= 15; alert(x); // Outputs: 10
JavaScript String Operators
Operator Description Example Result
+ Concatenation str1 + str2 Concatenation of str1
and str2
+= Concatenation
assignment
str1 += str2 Appends the str2 to
the str1
There are two operators which can also used be for strings.
The following example will show you these string
operators in action:
var str1 = "Hello";
var str2 = " World!";
alert(str1 + str2); // Outputs: Hello World!
str1 += str2;
alert(str1); // Outputs: Hello World!
JavaScript Incrementing and Decrementing
Operators
Operator Name Effect
++x Pre-increment Increments x by one, then
returns x
x++ Post-increment Returns x, then increments x
by one
--x Pre-decrement Decrements x by one, then
returns x
x-- Post-decrement Returns x, then decrements x
by one
The increment/decrement operators are used to increment/decrement a variable's value.
The following example will show you how
increment and decrement operators actually
work:
var x; // Declaring Variable
x = 10;
alert(++x); // Outputs: 11
alert(x); // Outputs: 11
x = 10;
alert(x++); // Outputs: 10
alert(x); // Outputs: 11
x = 10;
alert(--x); // Outputs: 9
alert(x); // Outputs: 9
x = 10;
alert(x--); // Outputs: 10
alert(x); // Outputs: 9
JavaScript Logical Operators
Operator Name Example Result
&& And x && y True if both x and y
are true
|| Or x || y True if either x or y is
true
! Not !x True if x is not true
The logical operators are typically used to combine conditional statements.
The following example will show you how
these logical operators actually work:
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)))
{
alert(year + " is a leap year.");
}
Else
{
alert(year + " is not a leap year.");
}
JavaScript Comparison Operators
Operator Name Example Result
== Equal x == y True if x is equal to y
=== Identical x === y True if x is equal to y,
and they are of the
same type
!= Not equal x != y True if x is not equal
to y
!== Not identical x !== y True if x is not equal
to y, or they are not
of the same type
< Less than x < y True if x is less than y
> Greater than x > y True if x is greater
than y
>= Greater than or
equal to
x >= y True if x is greater
than or equal to y
<= Less than or equal to x <= y True if x is less than or
equal to y
The following example will show you these
comparison operators in action:
var x = 25;
var y = 35;
var z = "25";
alert(x == z); // Outputs: true
alert(x === z); // Outputs: false
alert(x != y); // Outputs: true
alert(x !== z); // Outputs: true
alert(x < y); // Outputs: true
alert(x > y); // Outputs: false
alert(x <= y); // Outputs: true
alert(x >= y); // Outputs: false
JavaScript Conditional Statements
◦ While writing a program, there may be a situation when you
need to adopt one out of a given set of paths. In such cases,
you need to use conditional statements that allow your
program to make correct decisions and perform right actions.
◦ JavaScript supports conditional statements which are used to
perform different actions based on different conditions. Here
we will explain the if..else statement.
Flow Chart of if-else JavaScript supports the following
forms of if..else statement −
• if statement
• if...else statement
• if...else if... statement.
Condition
Conditional Code
If
Condition
is True
If
Condition
is False
if statement
The if statement is the fundamental control
statement that allows JavaScript to make
decisions and execute statements
conditionally.
Syntax
Try the following example to understand
how the if statement works.
if(expression)
{
Statement(s)
to be executed
if expression
is true
}
<html>
<body>
<script type="text/javascript">
<!–
var age = 20; if( age > 18 ) {
document.write("<b>Qualifies
for driving</b>");
}
//-->
</script>
<p>Set the variable to
different value and then try...
</p>
</body>
</html>
if...else statement
The 'if...else' statement is the next form of control statement that allows JavaScript to execute statements in a more
controlled way.
Syntax
if (expression)
{
Statement(s) to be executed if
expression is true
}
else
{
Statement(s) to be executed if
expression is false
}
Example of ‘if...else’ statement
<html>
<body>
<script type = "text/javascript">
<!–
var age = 15;
if( age > 18 )
{
document.write("<b>Qualifies for driving</b>");
}
else
{
document.write("<b>Does not qualify for driving</b>");
}
//-->
</script>
<p>
Set the variable to different value and then try...
</p>
</body>
</html>
if...else if... statement
The if...else if... statement is an advanced form of if…else that allows JavaScript to make a correct decision
out of several conditions.
Syntax
if (expression 1)
{
Statement(s) to be executed if expression 1 is true
}
else if (expression 2)
{
Statement(s) to be executed if expression 2 is true
}
else if (expression 3)
{
Statement(s) to be executed if expression 3 is true
}
else
{
Statement(s) to be executed if no expression is true
}
Example of ‘if...else If’ statement
<script>
var now = new Date();
var dayOfWeek = now.getDay(); // Sunday - Saturday : 0 - 6
if(dayOfWeek == 5) {
document.write("Have a nice weekend!");
} else if(dayOfWeek == 0) {
document.write("Have a nice Sunday!");
} else {
document.write("Have a nice day!");
}
</script>
JavaScript Switch...Case Statements
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. It's syntax is:
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
}
Example of switch case
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>
<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;
JavaScript Arrays
What is an Array
Arrays are complex variables that allow us to store more
than one value or a group of values under a single
variable name. JavaScript arrays can store any valid
value, including strings, numbers, objects, functions, and
even other arrays, thus making it possible to create more
complex data structures such as an array of objects or an
array of arrays.
Let's suppose you want to store the name of colors in your JavaScript code.
Storing the color names one by one in a variable could look something like this:
Eg.
var color1 = "Red";
var color2 = "Green";
var color3 = "Blue";
But what happens if you need to store the state or city names of a country in
variables and this time this not just three may be hundred. It is quite hard and
boring to store each of them in a separate variable. Also, using so many
variables simultaneously and keeping track of them all will be a very difficult
task. And here array comes into play. Arrays solve this problem by providing an
ordered structure for storing multiple values or a group of values.
Creating an Array
The simplest way to create an array in JavaScript is enclosing
a comma-separated list of values in square brackets ([]), as
shown in the following syntax:
var myArray = [element0, element1, ..., elementN];
Array can also be created using the Array() constructor as shown in the following syntax.
However, for the sake of simplicity previous syntax is recommended.
var myArray = new Array(element0, element1, ..., elementN);
var cities = ["London", "Paris", "New
York"];
var person = ["John", "Wick", 32];
// Printing variable values
document.write(colors + "<br>");
document.write(fruits + "<br>");
document.write(cities + "<br>");
document.write(person);
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Creating Arrays in JavaScript</title>
</head>
<body>
<script>
// Creating variables
var colors = ["Red", "Green", "Blue"];
var fruits = ["Apple", "Banana", "Mango",
"Orange", "Papaya"];
Array Example
Accessing the Elements of an Array
Array elements can be accessed by their index using the square bracket notation. An index
is a number that represents an element's position in an array.
Array indexes are zero-based. This means that the first item of an array is stored at index 0,
not 1, the second item is stored at index 1, and so on. Array indexes start at 0 and go up to
the number of elements minus 1. So, array of five elements would have indexes from 0 to 4.
<script>
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
document.write(fruits[0] + "<br>"); // Prints: Apple
document.write(fruits[1] + "<br>"); // Prints: Banana
document.write(fruits[2] + "<br>"); // Prints: Mango
document.write(fruits[fruits.length - 1]); // Prints: Papaya
</script>
Getting the Length of an Array
The length property returns the length of an array, which is the total number of
elements contained in the array.
Array length is always greater than the index of any of its element.
<script>
var fruits = ["Apple", "Banana", "Mango", "Orange",
"Papaya"];
document.write(fruits.length); // 0utputs: 5
</script>
Adding New Elements to an Array
<script>
var colors = ["Red", "Green", "Blue"];
colors.push("Yellow");
document.write(colors + "<br>"); // Prints: Red,Green,Blue,Yellow
document.write(colors.length); // Prints: 4
</script>
Similarly, to add a new element at the beginning of an array use
the unshift() method, like this:
<script>
var colors = ["Red", "Green", "Blue"];
colors.push("Pink", "Voilet");
colors.unshift("Yellow", "Grey");
document.write(colors + "<br>"); // Prints: Yellow,Grey,Red,Green,Blue,Pink,Voilet
document.write(colors.length); // Prints: 7
</script>
Removing Elements from an Array
<script>
var colors = ["Red", "Green",
"Blue"];
var last = colors.pop();
document.write(last + "<br>"); //
Prints: Blue
document.write(colors.length);
// Prints: 2
</script>
Similarly, you can remove the first element from an
array using the shift() method. This method also
returns the value that was shifted out. Here's an
example:
<script>
var colors = ["Red", "Green",
"Blue"];
var first = colors.shift();
document.write(first + "<br>");
// Prints: Red
document.write(colors.length);
// Prints: 2
</script>
Creating a String from an Array
here may be situations where you simply want to create a string by joining the
elements of an array.
To do this you can use the join() method.
This method takes an optional parameter which is a separator string that is added
in between each element.
<script>
var colors = ["Red", "Green", "Blue"];
document.write(colors.join() + "<br>"); // Prints: Red,Green,Blue
document.write(colors.join("") + "<br>"); // Prints: RedGreenBlue
document.write(colors.join("-") + "<br>"); // Prints: Red-Green-Blue
document.write(colors.join(", ")); // Prints: Red, Green, Blue
</script>
Merging Two or More Arrays
The concat() method can be used to merge or combine two or more
arrays.
This method does not change the existing arrays, instead it returns a
new array. For example:
<script>
var pets = ["Cat", "Dog", "Parrot"];
var wilds = ["Tiger", "Wolf", "Zebra"];
// Creating new array by combining pets and wilds arrays
var animals = pets.concat(wilds);
document.write(animals); // Prints: Cat,Dog,Parrot,Tiger,Wolf,Zebra
</script>
Searching Through an Array
If you want to search an array for a specific value, you can simply use
the indexOf() and lastIndexOf().
If the value is found, both methods return an index representing the array element. If
the value is not found, -1 is returned.
<script>
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
document.write(fruits.indexOf("Apple") + "<br>"); // Prints: 0
document.write(fruits.indexOf("Banana") + "<br>"); // Prints: 1
document.write(fruits.indexOf("Pineapple")); // Prints: -1
</script>
JavaScript Sorting Arrays
Sorting is a common task when working with arrays. It would be used, for instance, if you
want to display the city or county names in alphabetical order.
The JavaScript Array object has a built-in method sort() for sorting array elements in
alphabetical order. The following example demonstrates how it works:
<script>
var fruits = ["Banana", "Orange", "Apple", "Papaya", "Mango"];
var sorted = fruits.sort();
document.write(fruits + "<br>"); // Outputs: Apple,Banana,Mango,Orange,Papaya
document.write(sorted); // Outputs: Apple,Banana,Mango,Orange,Papaya
</script>
Reversing an Array
You can use the reverse() method to reverse the order of the elements of an
array.
<script>
var counts = ["one", "two", "three", "four", "five"];
var reversed = counts.reverse();
document.write(counts + "<br>"); // Outputs: five,four,three,two,one
document.write(reversed); // Output: five,four,three,two,one
</script>
JavaScript Loops
Different Types of Loops in JavaScript
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.
different types of loops:
• while — loops through a block of code as long as the condition specified
evaluates to true.
• do…while — loops through 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 through a block of code until the counter reaches a specified number.
This is the simplest looping statement provided by JavaScript.
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
}
The while Loop
A
B
True
False
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
}
The following example defines a loop that will continue to run as long as the variable i is less than
or equal to 5. The variable i will increase by 1 each time the loop runs:
<script>
var i = 1;
while(i <= 5) {
document.write("<p>The number is " + i + "</p>");
i++;
}
</script>
The do...while Loop
The do-while loop is a variant of the while loop, which
evaluates the condition at the end of each loop iteration.
With a do-while loop the block of code executed once,
and then the condition is evaluated, if the condition is
true, the statement is repeated as long as the specified
condition evaluated to is true. The generic syntax of the
do-while loop is:
do {
// Code to be executed
}
while(condition);
Do.. While Loop
<script>
var i = 1;
do {
document.write("<p>The number is " + i + "</p>");
i++;
}
while(i <= 5);
</script>
The for Loop
The for loop repeats a block of code as long as a certain
condition is met. It is typically used to execute a block of code
for certain number of times. Its syntax is:
for(initialization; condition; increment) {
// Code to be executed
}
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.
The following example defines a loop that starts with i=1. The loop
will continued until the value of variable i is less than or equal to 5.
The variable i will increase by 1 each time the loop runs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript For Loop</title>
</head>
<body>
<script>
for(var i=1; i<=5; i++) {
document.write("<p>The number is " + i + "</p>");
}
</script>
</body>
</html>
The for loop is particularly useful for iterating over an array.
The following example will show you how to print each item or
element of the JavaScript array.
<script>
// An array with some elements
var fruits = ["Apple", "Banana", "Mango",
"Orange", "Papaya"];
// Loop through all the elements in the
array
for(var i=0; i<fruits.length; i++) {
document.write("<p>" + fruits[i] + "</p>");
}
</script>
Apple
Banana
Mango
Orange
Papaya
The For In Loop
The JavaScript for in statement loops through the properties of an
Object:
Syntax
for (key in object) {
// code block to be executed
}
The For In Loop
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For In Loop</h2>
<p>The for in statement loops through the properties of an
object:</p>
<p id="demo"></p>
<script>
const person = {fname:"John", lname:"Doe", age:25};
let txt = "";
for (let x in person) {
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>
</body>
</html>
JavaScript For In Loop
The for in statement loops through the properties
of an object:
John Doe 25
JavaScript Function
A function is a group of statements that perform specific tasks and can
be kept and maintained separately form main program. Functions
provide a way to create reusable code packages which are more
portable and easier to debug. Here are some advantages of using
functions:
1. Functions reduces the repetition of code within a program
2. Functions makes the code much easier to maintain
3. 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 {}.
Here's the basic syntax for declaring a function:
function functionName() {
// Code to be executed
}
Example of Function
<script>
// Defining function
function sayHello() {
document.write("Hello, welcome to
this website!");
}
// Calling function
sayHello(); // Prints: Hello, welcome to
this website!
</script>
Hello, welcome to this website!
Adding Parameters to Functions
<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>
26
12
You can specify parameters when you define your function to accept input values at
run time.
Adding Parameters to Functions
<script>
// Defining function
function showFullname(firstName, lastName) {
document.write(firstName + " " + lastName);
}
// Calling function
showFullname("Clark", "Kent"); // Prints: Clark
Kent
document.write("<br>");
showFullname("John"); // Prints: John
undefined
</script>
Clark Kent
John undefined
You can define as many parameters as you like.
Returning Values from a Function
<script>
// Defining function
function getSum(num1, num2) {
var total = num1 + num2;
return total;
}
// Displaying returned value
document.write(getSum(6, 20) + "<br>"); //
Prints: 26
document.write(getSum(-5, 17)); // Prints: 12
</script>
26
12
A function can return a value back to the script that called the function as a result using the return statement.
The value may be of any type, including arrays and objects.
Understanding the Variable Scope
<script>
// Defining function
function greetWorld() {
var greet = "Hello World!";
document.write(greet);
}
greetWorld(); // Prints: Hello World!
document.write(greet); // Uncaught
ReferenceError: greet is not defined
</script>
Hello World!
By default, variables declared within a function have local scope that means they cannot be
viewed or manipulated from outside of that function, as shown in the example below:
Understanding the Variable Scope
<script>
var greet = "Hello World!";
// Defining function
function greetWorld() {
document.write(greet);
}
greetWorld(); // Prints: Hello World!
document.write("<br>");
document.write(greet); // Prints: Hello World!
</script>
Hello World!
Hello World!
However, any variables declared in a program outside of a function has global scope i.e. it will be
available to all script, whether that script is inside a function or outside. Here's an example:
JavaScript Events
An event is something that happens when user interact with the
web page, such as when he clicked a link or button, entered text
into an input box or textarea, made selection in a select box,
pressed key on the keyboard, moved the mouse pointer, submits a
form, etc. In some cases, the Browser itself can trigger the events,
such as the page load and unload events.
When an event occur, you can use a JavaScript event handler (or
an event listener) to detect them and perform specific task or set of
tasks.
JavaScript Event Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Attaching Event Handlers in External
File</title>
</head>
<body>
<button type="button" id="myBtn">Click Me</button>
<script>
function sayHello(){
alert('Hello World!');
}
document.getElementById("myBtn").onclick = sayHello;
</script>
</body>
</html>
Click Me
Mouse Events (onclick)
The click event occurs when a user clicks on an element on a web page.
Often, these are form elements and links. You can handle a click event
with an onclick event handler.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Handling the Click Event</title>
</head>
<body>
<button type="button" onclick="alert('You have clicked a button!');">Click Me</button>
<a href="#" onclick="alert('You have clicked a link!');">Click Me</a>
</body>
</html>
Mouse Events (Context menu)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Handling the Contextmenu Event</title>
</head>
<body>
<button type="button" oncontextmenu="alert('You have right-clicked a
button!');">Right Click on Me</button>
<a href="#" oncontextmenu="alert('You have right-clicked a
link!');">Right Click on Me</a>
</body>
</html>
JavaScript Math Object
The JavaScript Math object allows you to perform mathematical
tasks on numbers.
There are 4 common methods to round a number to an integer:
Math.round(x) Returns x rounded to its nearest integer
Math.ceil(x) Returns x rounded up to its nearest integer
Math.floor(x) Returns x rounded down to its nearest integer
Math.trunc(x) Returns the integer part of x (new in ES6)
Math.round()
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.round()</h2>
<p>Math.round(x) returns the value of x
rounded to its nearest integer:</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTM
L = Math.round(4.6);
</script>
</body>
</html>
JavaScript Math.round()
Math.round(x) returns the value of x
rounded to its nearest integer:
5
Math.floor()
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.floor()</h2>
<p>Math.floor(x) returns the value of x
rounded <strong>down</strong> to its
nearest integer:</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTM
L = Math.floor(4.7);
</script>
</body>
</html>
JavaScript Math.floor()
Math.floor(x) returns the value of x
rounded down to its nearest integer:
4
Math.ceil()
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.ceil()</h2>
<p>Math.ceil() rounds a number
<strong>up</strong> to its nearest
integer:</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTM
L = Math.ceil(4.4);
</script>
</body>
</html>
JavaScript Math.ceil()
Math.ceil() rounds a number up to its
nearest integer:
5
Math.pow()
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.pow()</h2>
<p>Math.pow(x,y) returns the value of x to
the power of y:</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTM
L = Math.pow(8,2);
</script>
</body>
</html>
JavaScript Math.pow()
Math.pow(x,y) returns the value of x to
the power of y:
64
Math.min() and Math.max()
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.min() and Math.max()</h2>
<p>Math.min() returns the lowest value in a list of
arguments:</p>
<p id="demo"></p>
<p id="demo2"></p>
<script>
document.getElementById("demo").innerHTML =
Math.min(0, 150, 30, 20, -8, -200);
document.getElementById("demo2").innerHTML =
Math.max(0, 150, 30, 20, -8, -200);
</script>
</body>
</html>
JavaScript Math.round()
Math.round(x) returns the value of x rounded to its
nearest integer:
-200
150
Math.sqrt()
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.round()</h2>
<p>Math.round(x) returns the value of x
rounded to its nearest integer:</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTM
L = Math.round(4.6);
</script>
</body>
</html>
JavaScript Math.sqrt()
Math.sqrt(x) returns the square root
of x:
8
Math.random()
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.random()</h2>
<p>Math.random() returns a random number between 0
and 1:</p>
<p id="demo"></p>
<p>Tip: Click on "Run" several times.</p>
<script>
document.getElementById("demo").innerHTML =
Math.random();
</script>
</body>
</html>
JavaScript Math.random()
Math.random() returns a random number
between 0 and 1:
0.12864618934908667
Tip: Click on “F5" several times.
Math.random()
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math</h2>
<p>Math.floor(Math.random() * 10) + 1) returns a
random integer between 1 and 10
(both included):</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 10) + 1;
</script>
</body>
</html>
JavaScript Math
Math.floor(Math.random() * 10) + 1)
returns a random integer between 1 and 10
(both included):
4

More Related Content

Similar to JavaScript New Tutorial Class XI and XII.pptx

Web programming UNIT II by Bhavsingh Maloth
Web programming UNIT II by Bhavsingh MalothWeb programming UNIT II by Bhavsingh Maloth
Web programming UNIT II by Bhavsingh MalothBhavsingh Maloth
 
8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentationJohnLagman3
 
WT Module-3.pptx
WT Module-3.pptxWT Module-3.pptx
WT Module-3.pptxRamyaH11
 
introduction to js
introduction to jsintroduction to js
introduction to jsSireesh K
 
JS BASICS JAVA SCRIPT SCRIPTING
JS BASICS JAVA SCRIPT SCRIPTINGJS BASICS JAVA SCRIPT SCRIPTING
JS BASICS JAVA SCRIPT SCRIPTINGArulkumar
 
WT Unit-3 PPT.pptx
WT Unit-3 PPT.pptxWT Unit-3 PPT.pptx
WT Unit-3 PPT.pptxTusharTikia
 
A sneak peek into the similarities and differences between java and java script
A sneak peek into the similarities and differences between java and java scriptA sneak peek into the similarities and differences between java and java script
A sneak peek into the similarities and differences between java and java scriptAMC Square
 
JAVA SCRIPT
JAVA SCRIPTJAVA SCRIPT
JAVA SCRIPTGo4Guru
 
WEB MODULE 3.pdf
WEB MODULE 3.pdfWEB MODULE 3.pdf
WEB MODULE 3.pdfDeepika A B
 

Similar to JavaScript New Tutorial Class XI and XII.pptx (20)

Web programming UNIT II by Bhavsingh Maloth
Web programming UNIT II by Bhavsingh MalothWeb programming UNIT II by Bhavsingh Maloth
Web programming UNIT II by Bhavsingh Maloth
 
8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation
 
WT Module-3.pptx
WT Module-3.pptxWT Module-3.pptx
WT Module-3.pptx
 
introduction to js
introduction to jsintroduction to js
introduction to js
 
Javascript
JavascriptJavascript
Javascript
 
Java script
Java scriptJava script
Java script
 
Java script introduction
Java script introductionJava script introduction
Java script introduction
 
JS BASICS JAVA SCRIPT SCRIPTING
JS BASICS JAVA SCRIPT SCRIPTINGJS BASICS JAVA SCRIPT SCRIPTING
JS BASICS JAVA SCRIPT SCRIPTING
 
WT Unit-3 PPT.pptx
WT Unit-3 PPT.pptxWT Unit-3 PPT.pptx
WT Unit-3 PPT.pptx
 
A sneak peek into the similarities and differences between java and java script
A sneak peek into the similarities and differences between java and java scriptA sneak peek into the similarities and differences between java and java script
A sneak peek into the similarities and differences between java and java script
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Java script
Java scriptJava script
Java script
 
Java script
Java scriptJava script
Java script
 
web designing course bangalore
web designing course bangaloreweb designing course bangalore
web designing course bangalore
 
Java script
Java scriptJava script
Java script
 
Java script
Java scriptJava script
Java script
 
JAVA SCRIPT
JAVA SCRIPTJAVA SCRIPT
JAVA SCRIPT
 
WEB MODULE 3.pdf
WEB MODULE 3.pdfWEB MODULE 3.pdf
WEB MODULE 3.pdf
 
Java scipt
Java sciptJava scipt
Java scipt
 
Js syntax
Js syntaxJs syntax
Js syntax
 

Recently uploaded

WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...caitlingebhard1
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMKumar Satyam
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
ChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityVictorSzoltysek
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAnitaRaj43
 
Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxMarkSteadman7
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data SciencePaolo Missier
 
API Governance and Monetization - The evolution of API governance
API Governance and Monetization -  The evolution of API governanceAPI Governance and Monetization -  The evolution of API governance
API Governance and Monetization - The evolution of API governanceWSO2
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)Samir Dash
 
Navigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseNavigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseWSO2
 

Recently uploaded (20)

WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
ChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps Productivity
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptx
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 
API Governance and Monetization - The evolution of API governance
API Governance and Monetization -  The evolution of API governanceAPI Governance and Monetization -  The evolution of API governance
API Governance and Monetization - The evolution of API governance
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
Navigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseNavigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern Enterprise
 

JavaScript New Tutorial Class XI and XII.pptx

  • 2. Introduction of JavaScript JavaScript developed by Branden Eiach in 1995. JavaScript is a lightweight, interpreted programming language. It is designed for creating network-centric applications. It is complimentary to and integrated with Java. JavaScript is very easy to implement because it is integrated with HTML. It is open and cross-platform.
  • 3. 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 was first known as LiveScript, but Netscape changed its name to JavaScript, possibly because of the excitement being generated by Java. JavaScript made its first appearance in Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers.
  • 4. Why to Learn JavaScript JavaScript is a MUST for students and working professionals to become a great Software Engineer specially when they are working in Web Development Domain. I will list down some of the key advantages of learning JavaScript: • JavaScript is the most popular programming language in the world and that makes it a programmer’s great choice. Once you learnt JavaScript, it helps you developing great front-end as well as back-end softwares using different JavaScript based frameworks like jQuery, Node.JS etc. • JavaScript is everywhere, it comes installed on every modern web browser and so to learn JavaScript you really do not need any special environment setup. For example Chrome, Mozilla Firefox , Safari and every browser you know as of today, supports JavaScript. • JavaScript helps you create really beautiful and crazy fast websites. You can develop your website with a console like look and feel and give your users the best Graphical User Experience. • JavaScript usage has now extended to mobile app development, desktop app development, and game development. This opens many opportunities for you as JavaScript Programmer.
  • 5. Client-Side JavaScript ❑Client-side JavaScript is the most common form of the language. The script should be included in or referenced by an HTML document for the code to be interpreted by the browser. ❑It means that a web page need not be a static HTML, but can include programs that interact with the user, control the browser, and dynamically create HTML content. ❑The JavaScript client-side mechanism provides many advantages over traditional CGI server-side scripts. For example, you might use JavaScript to check if the user has entered a valid e-mail address in a form field. ❑The JavaScript code is executed when the user submits the form, and only if all the entries are valid, they would be submitted to the Web Server. ❑JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and other actions that the user initiates explicitly or implicitly.
  • 6. Advantages of JavaScript • Less server interaction − You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server. • Immediate feedback to the visitors − They don't have to wait for a page reload to see if they have forgotten to enter something. • Increased interactivity − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard. • Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors.
  • 7. Limitations of JavaScript We cannot treat JavaScript as a full-fledged programming language. It lacks the following important features − • Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason. • JavaScript cannot be used for networking applications because there is no such support available. • JavaScript doesn't have any multi-threading or multiprocessor capabilities. Once again, JavaScript is a lightweight, interpreted programming language that allows you to build interactivity into otherwise static HTML pages
  • 8. Uses of JavaScript ✔Client side validation - This is really important to verify any user input before submitting it to the server and Javascript plays an important role in validting those inputs at front-end itself. ✔Manipulating HTML Pages - Javascript helps in manipulating HTML page on the fly. This helps in adding and deleting any HTML tag very easily using javascript and modify your HTML to change its look and feel based on different devices and requirements. ✔User Notifications - You can use Javascript to raise dynamic pop-ups on the webpages to give different types of notifications to your website visitors. ✔Back-end Data Loading - Javascript provides Ajax library which helps in loading back-end data while you are doing some other processing. This really gives an amazing experience to your website visitors. ✔Presentations - JavaScript also provides the facility of creating presentations which gives website look and feel. JavaScript provides RevealJS and BespokeJS libraries to build a web- based slide presentations. ✔Server Applications - Node JS is built on Chrome's Javascript runtime for building fast and scalable network applications. This is an event based library which helps in developing very sophisticated server applications including Web Servers.
  • 9. There could be 1000s of good reasons to learn JavaScript Programming. But one thing for sure, to learn any programming language, not only JavaScript, you just need to code, and code and finally code until you become expert.
  • 10. 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 ...> JavaScript code </script>
  • 11. Hello World using JavaScript Just to give you a little excitement about JavaScript programming, I'm going to give you a small conventional Javascript Hello World program <html> <body> <script language = "javascript" type = "text/javascript"> <!-- document.write("Hello World!") //--> </script> </body> </html> This code will produce the following result − Hello World!
  • 12. Live Demo “Hello World using JavaScript”
  • 13. Case Sensitivity JavaScript is a case-sensitive language. This means that the language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters. So the identifiers Time and TIME will convey different meanings in JavaScript. NOTE − Care should be taken while writing variable and function names in JavaScript.
  • 14. Comments in JavaScript JavaScript supports both C-style and C++-style comments, Thus − • Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript. • Any text between the characters /* and */ is treated as a comment. This may span multiple lines. • JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this as a single-line comment, just as it does the // comment. • The HTML comment closing sequence --> is not recognized by JavaScript so it should be written as //-->.
  • 15. The following example shows how to use comments in JavaScript. <script language = "javascript" type = "text/javascript"> <!-- // This is a comment. It is similar to comments in C++ /* *This is a multi-line comment in JavaScript *It is very similar to comments in C Programming */ //--> </script>
  • 16. JavaScript Variables ◦ JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container. ◦ Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows. You can also declare multiple variables with the same var keyword as follows − <script type = "text/javascript"> <!– var money; var name; //--> </script> <script type = "text/javascript"> <!– var money, name; //--> </script>
  • 17. Live demo how to declare variables
  • 18. JavaScript Datatypes One of the most fundamental characteristics of a programming language is the set of data types it supports. These are the type of values that can be represented and manipulated in a programming language. JavaScript allows you to work with three primitive data types − • Numbers, eg. 123, 120.50 etc. var a = 25; // integer var b = 80.5; // floating-point number • Strings of text e.g. "This text string" etc. var a = 'Hi there!'; // using single quotes var b = "Hi there!"; // using double quotes • Boolean e.g. true or false. var isReading = true; // yes, I'm reading var isSleeping = false; // no, I'm not sleeping JavaScript does not make a distinction between integer values and floating-point values. All numbers in JavaScript are represented as floating-point values. JavaScript represents numbers using the 64-bit floating-point format defined by the IEEE 754 standard.
  • 19. The Undefined Data Type var a; var b = "Hello World!“; alert(a) // Output: undefined alert(b) // Output: Hello World! The Null Data Type var a = null; alert(a); // Output: null var b = "Hello World!" alert(b); // Output: Hello World! b = null; alert(b) // Output: null
  • 20. Reserved Keywords abstract else instanceof switch boolean enum int synchronized break export interface this byte extends Long throw case false native throws catch final new transient char finally null true class float package try const for private typeof continue function protected var debugger goto public void default if return volatile delete implements short while do import static with double in super
  • 21. JavaScript Operators 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, while the equal-to (==), greater-than (>) or less-than (<) symbols are the operators that tells JavaScript engine to compare two variables or values, and so on.
  • 22. JavaScript Arithmetic Operators Operator Description Example Result + Addition x + y Sum of x and y - Subtraction x - y Difference of x and y. * Multiplication x * y Product of x and y. / Division x / y Quotient of x and y % Modulus x % y Remainder of x divided by y 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:
  • 23. Example of Arithmetic Operator var x = 10; var y = 4; alert(x + y); // 0utputs: 14 alert(x - y); // 0utputs: 6 alert(x * y); // 0utputs: 40 alert(x / y); // 0utputs: 2.5 alert(x % y); // 0utputs: 2
  • 24. JavaScript Assignment Operators Operator Description Example Is The Same As = Assign x = y x = y += Add and assign x += y x = x + y -= Subtract and assign x -= y x = x - y *= Multiply and assign x *= y x = x * y /= Divide and assign quotient x /= y x = x / y %= Divide and assign modulus x %= y x = x % y The assignment operators are used to assign values to variables.
  • 25. The following example will show you these assignment operators in action: var x; // Declaring Variable x = 10; alert(x); // Outputs: 10 x = 20; x += 30; alert(x); // Outputs: 50 x = 50; x -= 20; alert(x); // Outputs: 30 x = 5; x *= 25; alert(x); // Outputs: 125 x = 50; x /= 10; alert(x); // Outputs: 5 x = 100; x %= 15; alert(x); // Outputs: 10
  • 26. JavaScript String Operators Operator Description Example Result + Concatenation str1 + str2 Concatenation of str1 and str2 += Concatenation assignment str1 += str2 Appends the str2 to the str1 There are two operators which can also used be for strings.
  • 27. The following example will show you these string operators in action: var str1 = "Hello"; var str2 = " World!"; alert(str1 + str2); // Outputs: Hello World! str1 += str2; alert(str1); // Outputs: Hello World!
  • 28. JavaScript Incrementing and Decrementing Operators Operator Name Effect ++x Pre-increment Increments x by one, then returns x x++ Post-increment Returns x, then increments x by one --x Pre-decrement Decrements x by one, then returns x x-- Post-decrement Returns x, then decrements x by one The increment/decrement operators are used to increment/decrement a variable's value.
  • 29. The following example will show you how increment and decrement operators actually work: var x; // Declaring Variable x = 10; alert(++x); // Outputs: 11 alert(x); // Outputs: 11 x = 10; alert(x++); // Outputs: 10 alert(x); // Outputs: 11 x = 10; alert(--x); // Outputs: 9 alert(x); // Outputs: 9 x = 10; alert(x--); // Outputs: 10 alert(x); // Outputs: 9
  • 30. JavaScript Logical Operators Operator Name Example Result && And x && y True if both x and y are true || Or x || y True if either x or y is true ! Not !x True if x is not true The logical operators are typically used to combine conditional statements.
  • 31. The following example will show you how these logical operators actually work: 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))) { alert(year + " is a leap year."); } Else { alert(year + " is not a leap year."); }
  • 32. JavaScript Comparison Operators Operator Name Example Result == Equal x == y True if x is equal to y === Identical x === y True if x is equal to y, and they are of the same type != Not equal x != y True if x is not equal to y !== Not identical x !== y True if x is not equal to y, or they are not of the same type < Less than x < y True if x is less than y > Greater than x > y True if x is greater than y >= Greater than or equal to x >= y True if x is greater than or equal to y <= Less than or equal to x <= y True if x is less than or equal to y
  • 33. The following example will show you these comparison operators in action: var x = 25; var y = 35; var z = "25"; alert(x == z); // Outputs: true alert(x === z); // Outputs: false alert(x != y); // Outputs: true alert(x !== z); // Outputs: true alert(x < y); // Outputs: true alert(x > y); // Outputs: false alert(x <= y); // Outputs: true alert(x >= y); // Outputs: false
  • 34. JavaScript Conditional Statements ◦ While writing a program, there may be a situation when you need to adopt one out of a given set of paths. In such cases, you need to use conditional statements that allow your program to make correct decisions and perform right actions. ◦ JavaScript supports conditional statements which are used to perform different actions based on different conditions. Here we will explain the if..else statement.
  • 35. Flow Chart of if-else JavaScript supports the following forms of if..else statement − • if statement • if...else statement • if...else if... statement. Condition Conditional Code If Condition is True If Condition is False
  • 36. if statement The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally. Syntax Try the following example to understand how the if statement works. if(expression) { Statement(s) to be executed if expression is true } <html> <body> <script type="text/javascript"> <!– var age = 20; if( age > 18 ) { document.write("<b>Qualifies for driving</b>"); } //--> </script> <p>Set the variable to different value and then try... </p> </body> </html>
  • 37. if...else statement The 'if...else' statement is the next form of control statement that allows JavaScript to execute statements in a more controlled way. Syntax if (expression) { Statement(s) to be executed if expression is true } else { Statement(s) to be executed if expression is false }
  • 38. Example of ‘if...else’ statement <html> <body> <script type = "text/javascript"> <!– var age = 15; if( age > 18 ) { document.write("<b>Qualifies for driving</b>"); } else { document.write("<b>Does not qualify for driving</b>"); } //--> </script> <p> Set the variable to different value and then try... </p> </body> </html>
  • 39. if...else if... statement The if...else if... statement is an advanced form of if…else that allows JavaScript to make a correct decision out of several conditions. Syntax if (expression 1) { Statement(s) to be executed if expression 1 is true } else if (expression 2) { Statement(s) to be executed if expression 2 is true } else if (expression 3) { Statement(s) to be executed if expression 3 is true } else { Statement(s) to be executed if no expression is true }
  • 40. Example of ‘if...else If’ statement <script> var now = new Date(); var dayOfWeek = now.getDay(); // Sunday - Saturday : 0 - 6 if(dayOfWeek == 5) { document.write("Have a nice weekend!"); } else if(dayOfWeek == 0) { document.write("Have a nice Sunday!"); } else { document.write("Have a nice day!"); } </script>
  • 41. JavaScript Switch...Case Statements 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. It's syntax is: 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 }
  • 42. Example of switch case 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> <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;
  • 43. JavaScript Arrays What is an Array Arrays are complex variables that allow us to store more than one value or a group of values under a single variable name. JavaScript arrays can store any valid value, including strings, numbers, objects, functions, and even other arrays, thus making it possible to create more complex data structures such as an array of objects or an array of arrays.
  • 44. Let's suppose you want to store the name of colors in your JavaScript code. Storing the color names one by one in a variable could look something like this: Eg. var color1 = "Red"; var color2 = "Green"; var color3 = "Blue"; But what happens if you need to store the state or city names of a country in variables and this time this not just three may be hundred. It is quite hard and boring to store each of them in a separate variable. Also, using so many variables simultaneously and keeping track of them all will be a very difficult task. And here array comes into play. Arrays solve this problem by providing an ordered structure for storing multiple values or a group of values.
  • 45. Creating an Array The simplest way to create an array in JavaScript is enclosing a comma-separated list of values in square brackets ([]), as shown in the following syntax: var myArray = [element0, element1, ..., elementN]; Array can also be created using the Array() constructor as shown in the following syntax. However, for the sake of simplicity previous syntax is recommended. var myArray = new Array(element0, element1, ..., elementN);
  • 46. var cities = ["London", "Paris", "New York"]; var person = ["John", "Wick", 32]; // Printing variable values document.write(colors + "<br>"); document.write(fruits + "<br>"); document.write(cities + "<br>"); document.write(person); </script> </body> </html> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Creating Arrays in JavaScript</title> </head> <body> <script> // Creating variables var colors = ["Red", "Green", "Blue"]; var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"]; Array Example
  • 47. Accessing the Elements of an Array Array elements can be accessed by their index using the square bracket notation. An index is a number that represents an element's position in an array. Array indexes are zero-based. This means that the first item of an array is stored at index 0, not 1, the second item is stored at index 1, and so on. Array indexes start at 0 and go up to the number of elements minus 1. So, array of five elements would have indexes from 0 to 4. <script> var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"]; document.write(fruits[0] + "<br>"); // Prints: Apple document.write(fruits[1] + "<br>"); // Prints: Banana document.write(fruits[2] + "<br>"); // Prints: Mango document.write(fruits[fruits.length - 1]); // Prints: Papaya </script>
  • 48. Getting the Length of an Array The length property returns the length of an array, which is the total number of elements contained in the array. Array length is always greater than the index of any of its element. <script> var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"]; document.write(fruits.length); // 0utputs: 5 </script>
  • 49. Adding New Elements to an Array <script> var colors = ["Red", "Green", "Blue"]; colors.push("Yellow"); document.write(colors + "<br>"); // Prints: Red,Green,Blue,Yellow document.write(colors.length); // Prints: 4 </script> Similarly, to add a new element at the beginning of an array use the unshift() method, like this: <script> var colors = ["Red", "Green", "Blue"]; colors.push("Pink", "Voilet"); colors.unshift("Yellow", "Grey"); document.write(colors + "<br>"); // Prints: Yellow,Grey,Red,Green,Blue,Pink,Voilet document.write(colors.length); // Prints: 7 </script>
  • 50. Removing Elements from an Array <script> var colors = ["Red", "Green", "Blue"]; var last = colors.pop(); document.write(last + "<br>"); // Prints: Blue document.write(colors.length); // Prints: 2 </script> Similarly, you can remove the first element from an array using the shift() method. This method also returns the value that was shifted out. Here's an example: <script> var colors = ["Red", "Green", "Blue"]; var first = colors.shift(); document.write(first + "<br>"); // Prints: Red document.write(colors.length); // Prints: 2 </script>
  • 51. Creating a String from an Array here may be situations where you simply want to create a string by joining the elements of an array. To do this you can use the join() method. This method takes an optional parameter which is a separator string that is added in between each element. <script> var colors = ["Red", "Green", "Blue"]; document.write(colors.join() + "<br>"); // Prints: Red,Green,Blue document.write(colors.join("") + "<br>"); // Prints: RedGreenBlue document.write(colors.join("-") + "<br>"); // Prints: Red-Green-Blue document.write(colors.join(", ")); // Prints: Red, Green, Blue </script>
  • 52. Merging Two or More Arrays The concat() method can be used to merge or combine two or more arrays. This method does not change the existing arrays, instead it returns a new array. For example: <script> var pets = ["Cat", "Dog", "Parrot"]; var wilds = ["Tiger", "Wolf", "Zebra"]; // Creating new array by combining pets and wilds arrays var animals = pets.concat(wilds); document.write(animals); // Prints: Cat,Dog,Parrot,Tiger,Wolf,Zebra </script>
  • 53. Searching Through an Array If you want to search an array for a specific value, you can simply use the indexOf() and lastIndexOf(). If the value is found, both methods return an index representing the array element. If the value is not found, -1 is returned. <script> var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"]; document.write(fruits.indexOf("Apple") + "<br>"); // Prints: 0 document.write(fruits.indexOf("Banana") + "<br>"); // Prints: 1 document.write(fruits.indexOf("Pineapple")); // Prints: -1 </script>
  • 54. JavaScript Sorting Arrays Sorting is a common task when working with arrays. It would be used, for instance, if you want to display the city or county names in alphabetical order. The JavaScript Array object has a built-in method sort() for sorting array elements in alphabetical order. The following example demonstrates how it works: <script> var fruits = ["Banana", "Orange", "Apple", "Papaya", "Mango"]; var sorted = fruits.sort(); document.write(fruits + "<br>"); // Outputs: Apple,Banana,Mango,Orange,Papaya document.write(sorted); // Outputs: Apple,Banana,Mango,Orange,Papaya </script>
  • 55. Reversing an Array You can use the reverse() method to reverse the order of the elements of an array. <script> var counts = ["one", "two", "three", "four", "five"]; var reversed = counts.reverse(); document.write(counts + "<br>"); // Outputs: five,four,three,two,one document.write(reversed); // Output: five,four,three,two,one </script>
  • 56. JavaScript Loops Different Types of Loops in JavaScript 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. different types of loops: • while — loops through a block of code as long as the condition specified evaluates to true. • do…while — loops through 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 through a block of code until the counter reaches a specified number.
  • 57. This is the simplest looping statement provided by JavaScript. 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 } The while Loop A B True False
  • 58. 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 } The following example defines a loop that will continue to run as long as the variable i is less than or equal to 5. The variable i will increase by 1 each time the loop runs: <script> var i = 1; while(i <= 5) { document.write("<p>The number is " + i + "</p>"); i++; } </script>
  • 59. The do...while Loop The do-while loop is a variant of the while loop, which evaluates the condition at the end of each loop iteration. With a do-while loop the block of code executed once, and then the condition is evaluated, if the condition is true, the statement is repeated as long as the specified condition evaluated to is true. The generic syntax of the do-while loop is: do { // Code to be executed } while(condition);
  • 60. Do.. While Loop <script> var i = 1; do { document.write("<p>The number is " + i + "</p>"); i++; } while(i <= 5); </script>
  • 61. The for Loop The for loop repeats a block of code as long as a certain condition is met. It is typically used to execute a block of code for certain number of times. Its syntax is: for(initialization; condition; increment) { // Code to be executed }
  • 62. 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.
  • 63. The following example defines a loop that starts with i=1. The loop will continued until the value of variable i is less than or equal to 5. The variable i will increase by 1 each time the loop runs: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JavaScript For Loop</title> </head> <body> <script> for(var i=1; i<=5; i++) { document.write("<p>The number is " + i + "</p>"); } </script> </body> </html>
  • 64. The for loop is particularly useful for iterating over an array. The following example will show you how to print each item or element of the JavaScript array. <script> // An array with some elements var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"]; // Loop through all the elements in the array for(var i=0; i<fruits.length; i++) { document.write("<p>" + fruits[i] + "</p>"); } </script> Apple Banana Mango Orange Papaya
  • 65. The For In Loop The JavaScript for in statement loops through the properties of an Object: Syntax for (key in object) { // code block to be executed }
  • 66. The For In Loop <!DOCTYPE html> <html> <body> <h2>JavaScript For In Loop</h2> <p>The for in statement loops through the properties of an object:</p> <p id="demo"></p> <script> const person = {fname:"John", lname:"Doe", age:25}; let txt = ""; for (let x in person) { txt += person[x] + " "; } document.getElementById("demo").innerHTML = txt; </script> </body> </html> JavaScript For In Loop The for in statement loops through the properties of an object: John Doe 25
  • 67. JavaScript Function A function is a group of statements that perform specific tasks and can be kept and maintained separately form main program. Functions provide a way to create reusable code packages which are more portable and easier to debug. Here are some advantages of using functions: 1. Functions reduces the repetition of code within a program 2. Functions makes the code much easier to maintain 3. Functions makes it easier to eliminate the errors
  • 68. 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 {}. Here's the basic syntax for declaring a function: function functionName() { // Code to be executed }
  • 69. Example of Function <script> // Defining function function sayHello() { document.write("Hello, welcome to this website!"); } // Calling function sayHello(); // Prints: Hello, welcome to this website! </script> Hello, welcome to this website!
  • 70. Adding Parameters to Functions <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> 26 12 You can specify parameters when you define your function to accept input values at run time.
  • 71. Adding Parameters to Functions <script> // Defining function function showFullname(firstName, lastName) { document.write(firstName + " " + lastName); } // Calling function showFullname("Clark", "Kent"); // Prints: Clark Kent document.write("<br>"); showFullname("John"); // Prints: John undefined </script> Clark Kent John undefined You can define as many parameters as you like.
  • 72. Returning Values from a Function <script> // Defining function function getSum(num1, num2) { var total = num1 + num2; return total; } // Displaying returned value document.write(getSum(6, 20) + "<br>"); // Prints: 26 document.write(getSum(-5, 17)); // Prints: 12 </script> 26 12 A function can return a value back to the script that called the function as a result using the return statement. The value may be of any type, including arrays and objects.
  • 73. Understanding the Variable Scope <script> // Defining function function greetWorld() { var greet = "Hello World!"; document.write(greet); } greetWorld(); // Prints: Hello World! document.write(greet); // Uncaught ReferenceError: greet is not defined </script> Hello World! By default, variables declared within a function have local scope that means they cannot be viewed or manipulated from outside of that function, as shown in the example below:
  • 74. Understanding the Variable Scope <script> var greet = "Hello World!"; // Defining function function greetWorld() { document.write(greet); } greetWorld(); // Prints: Hello World! document.write("<br>"); document.write(greet); // Prints: Hello World! </script> Hello World! Hello World! However, any variables declared in a program outside of a function has global scope i.e. it will be available to all script, whether that script is inside a function or outside. Here's an example:
  • 75. JavaScript Events An event is something that happens when user interact with the web page, such as when he clicked a link or button, entered text into an input box or textarea, made selection in a select box, pressed key on the keyboard, moved the mouse pointer, submits a form, etc. In some cases, the Browser itself can trigger the events, such as the page load and unload events. When an event occur, you can use a JavaScript event handler (or an event listener) to detect them and perform specific task or set of tasks.
  • 76. JavaScript Event Example <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JavaScript Attaching Event Handlers in External File</title> </head> <body> <button type="button" id="myBtn">Click Me</button> <script> function sayHello(){ alert('Hello World!'); } document.getElementById("myBtn").onclick = sayHello; </script> </body> </html> Click Me
  • 77. Mouse Events (onclick) The click event occurs when a user clicks on an element on a web page. Often, these are form elements and links. You can handle a click event with an onclick event handler. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JavaScript Handling the Click Event</title> </head> <body> <button type="button" onclick="alert('You have clicked a button!');">Click Me</button> <a href="#" onclick="alert('You have clicked a link!');">Click Me</a> </body> </html>
  • 78. Mouse Events (Context menu) <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JavaScript Handling the Contextmenu Event</title> </head> <body> <button type="button" oncontextmenu="alert('You have right-clicked a button!');">Right Click on Me</button> <a href="#" oncontextmenu="alert('You have right-clicked a link!');">Right Click on Me</a> </body> </html>
  • 79. JavaScript Math Object The JavaScript Math object allows you to perform mathematical tasks on numbers. There are 4 common methods to round a number to an integer: Math.round(x) Returns x rounded to its nearest integer Math.ceil(x) Returns x rounded up to its nearest integer Math.floor(x) Returns x rounded down to its nearest integer Math.trunc(x) Returns the integer part of x (new in ES6)
  • 80. Math.round() <!DOCTYPE html> <html> <body> <h2>JavaScript Math.round()</h2> <p>Math.round(x) returns the value of x rounded to its nearest integer:</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTM L = Math.round(4.6); </script> </body> </html> JavaScript Math.round() Math.round(x) returns the value of x rounded to its nearest integer: 5
  • 81. Math.floor() <!DOCTYPE html> <html> <body> <h2>JavaScript Math.floor()</h2> <p>Math.floor(x) returns the value of x rounded <strong>down</strong> to its nearest integer:</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTM L = Math.floor(4.7); </script> </body> </html> JavaScript Math.floor() Math.floor(x) returns the value of x rounded down to its nearest integer: 4
  • 82. Math.ceil() <!DOCTYPE html> <html> <body> <h2>JavaScript Math.ceil()</h2> <p>Math.ceil() rounds a number <strong>up</strong> to its nearest integer:</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTM L = Math.ceil(4.4); </script> </body> </html> JavaScript Math.ceil() Math.ceil() rounds a number up to its nearest integer: 5
  • 83. Math.pow() <!DOCTYPE html> <html> <body> <h2>JavaScript Math.pow()</h2> <p>Math.pow(x,y) returns the value of x to the power of y:</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTM L = Math.pow(8,2); </script> </body> </html> JavaScript Math.pow() Math.pow(x,y) returns the value of x to the power of y: 64
  • 84. Math.min() and Math.max() <!DOCTYPE html> <html> <body> <h2>JavaScript Math.min() and Math.max()</h2> <p>Math.min() returns the lowest value in a list of arguments:</p> <p id="demo"></p> <p id="demo2"></p> <script> document.getElementById("demo").innerHTML = Math.min(0, 150, 30, 20, -8, -200); document.getElementById("demo2").innerHTML = Math.max(0, 150, 30, 20, -8, -200); </script> </body> </html> JavaScript Math.round() Math.round(x) returns the value of x rounded to its nearest integer: -200 150
  • 85. Math.sqrt() <!DOCTYPE html> <html> <body> <h2>JavaScript Math.round()</h2> <p>Math.round(x) returns the value of x rounded to its nearest integer:</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTM L = Math.round(4.6); </script> </body> </html> JavaScript Math.sqrt() Math.sqrt(x) returns the square root of x: 8
  • 86. Math.random() <!DOCTYPE html> <html> <body> <h2>JavaScript Math.random()</h2> <p>Math.random() returns a random number between 0 and 1:</p> <p id="demo"></p> <p>Tip: Click on "Run" several times.</p> <script> document.getElementById("demo").innerHTML = Math.random(); </script> </body> </html> JavaScript Math.random() Math.random() returns a random number between 0 and 1: 0.12864618934908667 Tip: Click on “F5" several times.
  • 87. Math.random() <!DOCTYPE html> <html> <body> <h2>JavaScript Math</h2> <p>Math.floor(Math.random() * 10) + 1) returns a random integer between 1 and 10 (both included):</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = Math.floor(Math.random() * 10) + 1; </script> </body> </html> JavaScript Math Math.floor(Math.random() * 10) + 1) returns a random integer between 1 and 10 (both included): 4