0% found this document useful (0 votes)
4 views56 pages

Module 4-JavaScript

Uploaded by

pg.piyush18
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
4 views56 pages

Module 4-JavaScript

Uploaded by

pg.piyush18
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 56

WEB TECHNOLOGY AND ITS

APPLICATIONS
MODULE 4 - SYLABUS
• JavaScript:
• Client-Side Scripting
• What is JavaScript and What can it do?
• How to develop Javascript
• Simple Javascript
• Variables,
• Functions
• Conditions
• loops and repetition
JavaScript: Client-Side Scripting
Section 1 of 8

WHAT IS JAVASCRIPT
What is JavaScript

• JavaScript runs right inside the browser


• JavaScript is dynamically typed (Weakly Typed)
• JavaScript is object oriented in that almost everything
in the language is an object
• The objects in JavaScript are prototype-based rather
than class-based, which means that while JavaScript
shares some syntactic features of PHP, Java or C#, it is
also quite different from those languages
What isn’t JavaScript
It’s not Java

❖Although it contains the word Java, JavaScript and Java are


vastly different programming languages with different uses.
❖Java is a full-fledged compiled, object-oriented language,
popular for its ability to run on any platform with a JVM
installed.
❖Conversely, JavaScript is one of the world’s most popular
languages, with fewer of the object-oriented features of Java,
and runs directly inside the browser, without the need for the
JVM.
Client-Side Scripting
Let the client compute
Client-Side Scripting
It’s good

There are many advantages of client-side scripting:


• Processing can be offloaded from the server to client
machines, thereby reducing the load on the server.
• The browser can respond more rapidly to user events than
a request to a remote server ever could, which improves
the user experience.
• JavaScript can interact with the downloaded HTML in a
way that the server cannot, creating a user experience
more like desktop software than simple HTML ever could.
Client-Side Scripting
There are challenges

The disadvantages of client-side scripting are mostly related to


how programmers use JavaScript in their applications.
• There is no guarantee that the client has JavaScript enabled
• The idiosyncrasies between various browsers and operating
systems make it difficult to test for all potential client
configurations. What works in one browser, may generate
an error in another.
• JavaScript-heavy web applications can be complicated to
debug and maintain.
JavaScript History

• JavaScript was introduced by Netscape in their Navigator


browser back in 1996.
• It was originally called LiveScript
• JavaScript is in fact an implementation of a standardized
scripting language called ECMAScript
• JavaScript was only slightly useful, and quite often, very
annoying to many users
HTTP request-response loop
Without JavaScript
HTTP request-response loop
Detail
JavaScript in Modern Times
AJAX

JavaScript became a much more important part of web


development in the mid 2000s with AJAX.

AJAX is both an acronym as well as a general term.


• As an acronym it means Asynchronous JavaScript And XML.

• The most important feature of AJAX sites is the asynchronous


data requests.
Asynchronous data requests
The better AJAX way
Frameworks
Lots of this is done for you, once you get the basics
Section 3 of 8

WHERE DOES JAVASCRIPT GO?


Where does JavaScript go?

JavaScript can be linked to an HTML page in a number of


ways.

• Inline
• Embedded
• External
Inline JavaScript
Mash it in

Inline JavaScript refers to the practice of including JavaScript


code directly within certain HTML attributes

Inline JavaScript is a real maintenance nightmare


Inline
<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can change HTML content.</p>

<button type="button"
onclick='document.getElementById("demo").innerHTML = "Hello
JavaScript!"'>Click Me!</button>

</body>
</html>
Embedded JavaScript

<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<script>
//Script logic
</script>
</body>
</html
Embedded JavaScript
Better

Embedded JavaScript refers to the practice of placing


JavaScript code within a <script> element
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-
scale=1.0" />
<link rel="stylesheet" src="style.css" />
<title>Document</title>
</head>
<body>
<button onclick="myFun()">Alert</button>

<script>
function myFun(){
alert("Hello there!");
}
</script>
</body>
</html>
External JavaScript
Better

JavaScript supports this separation by allowing links to an external


file that contains the JavaScript.

By convention, JavaScript external files have the extension


.js.
External JavaScript

<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
//Referencing external javascript file
<script src="script.js"></script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-
scale=1.0" />
<link rel="stylesheet" src="style.css" />
<title>Document</title>
<script src="script.js"></script>
</head>
<body>
<button onclick="myFun()">Alert</button>
</body>
</html
// Script.js
function myFun(){
alert("Hello there!");
}
How to Reference External
JavaScript Files
• By using a full URL:
src = https://www.geeksforgeek.org/js/script.js

• By using a file path:


src = "/js/script.js“

• Without using any path:


src = "script.js"
Section 4 of 8

SYNTAX
JavaScript Syntax

We will briefly cover the fundamental syntax for the most


common programming constructs including
• variables,
• assignment,
• conditionals,
• loops, and
• arrays
before moving on to advanced topics such as events and
classes.
JavaScript’s Reputation
Precedes it?

JavaScript’s reputation for being quirky not only stems from its strange
way of implementing object-oriented principles but also from some odd
syntactic gotchas:
• Everything is type sensitive, including function, class, and variable
names.
• The scope of variables in blocks is not supported. This means
variables declared inside a loop may be accessible outside of the
loop, counter to what one would expect.
• There is a === operator, which tests not only for equality but type
equivalence.
• Null and undefined are two distinctly different states for a variable.
• Semicolons are not required, but are permitted (and encouraged).
• There is no integer type, only number, which means floating-point
rounding errors are prevalent even with values intended to be
integers.
Variables
var

❖Variables in JavaScript are dynamically typed, meaning a


variable can be an integer, and then later a string, then later an
object, if so desired.
❖This simplifies variable declarations, so that we do not require
the familiar type fields like int, char, and String. Instead we use
var
❖Assignment can happen at declaration-time by appending the
value to the declaration, or at run time with a simple right-to-
left assignment
JavaScript Identifiers

JavaScript variables must have unique names. These names


are called Identifiers.

Basic rules to declare a variable in JavaScript:


These are case-sensitive
•Can only begin with a letter, underscore(“_”) or “$” symbol
•It can contain letters, numbers, underscore, or “$” symbol
•A variable name cannot be a reserved keyword.
JavaScript Variables can be declared in 4 ways:

• Automatically
• Using var
• Using let
• Using const
Variables
Assignment
Automatically declaredVariables
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript automatic Variables</h1>
<p>In this example, x, y, and z are undeclared.</p>
<p>They are automatically declared when first used.</p>
<p id="sum"></p>
<script>
x = 1;
y = 2;
z = x + y;
document.getElementById("sum").innerHTML =
"The value of z is: " + z;
</script>

</body>
</html>
JavaScript Let

The let keyword in JavaScript is used to make variables that are scoped to
the block they’re declared in.

Once you’ve used let to define a variable, you cannot declare it again
within the same block. It’s important to declare let variables before using
them.

The variables which are declared inside the { } block are known as block-
scoped variables. variables declared by the var keyword cannot be block-
scoped.
Let Example

{
let num = 5;

// calling the function inside block


console.log(num)
}

// Calling a function outside


// block throws an Error
console.log(num)

Output:
5
Uncaught ReferenceError: num is not defined
let Example
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript let Variables</h1>

<p>In this example, x, y, and z are variables.</p>

<p id="let"></p>

<script>
let x = 1;
let y = 2;
let z = x + y;
document.getElementById("let").innerHTML =
"The value of z is: " + z;
</script>

</body>
</html>
Const Example
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>

<p>In this example, x, y, and z are variables.</p>

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

<script>
const x = 5;
const y = 6;
const z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>

</body>
</html>
Comparison Operators
True or not True

Operator Description Matches (x=9)

== Equals
(x==9) is true
(x=="9") is true

(x==="9") is false
=== Exactly equals, including type
(x===9) is true

<,> Less than, Greater Than (x<5) is false


<= , >= Less than or equal, greater (x<=9) is true
than or equal
!= Not equal (4!=x) is true

(x!=="9") is true
!== Not equal in either value or
type (x!==9) is false
== equal to

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The == Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x == 9):</p>

<p id="test"></p>

<script>
let x = 6;
document.getElementById("test").innerHTML = (x == 9);
</script>

</body>
</html>
=== equal value and equal type

=== (Triple Equals):Strict Equality: Does not perform type coercion.


It checks both the value and the type.

Comparison: Only returns true if both the value and the type of the
operands are exactly the same.

Examples:5 === '5' returns false because the types (number vs.
string) are different.

0 === false returns false because the types (number vs. boolean) are
different.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Comparison</h1>
<h2>The === Operator</h2>
<p>Assign 5 to x, and display the value of the comparison (x === 5):</p>
<p id="test"></p>
<script>
let x = 7;
document.getElementById("test").innerHTML = (x === '7');
</script>
</body>
</html>
Logical Operators

The Boolean operators and, or, and not and their truth tables
are listed in Table 6.2. Syntactically they are represented with
&& (and), || (or), and ! (not).
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Comparison</h1>
<h2>The && Operator (Logical AND)</h2>
<p>The && operator returns true if both expressions are true,
otherwise it returns false.</p>
<p id="demo"></p>
<script>
let x = 6;
let y = 3;
document.getElementById("demo").innerHTML =
(x < 10 && y > 1) + "<br>" +
(x < 10 && y < 1);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Comparison</h2>
<p>The NOT operator (!) returns true for false statements and false for
true statements.</p>
<p id="demo"></p>
<script>
let x = 3;
let y = 6;
document.getElementById("demo").innerHTML =
!(x > y);
</script>
</body>
</html>
Conditionals
If, else if, …, else

JavaScript’s syntax is almost identical to that of PHP, Java, or C


when it comes to conditional structures such as if and if else
statements. In this syntax the condition to test is contained
within ( ) brackets with the body contained in { } blocks.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Comparison</h1>
<h2>The () ? : Ternary Operator</h2>
<p>Input your age and click the button:</p>
<input id="age" value="18" />
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
let age = document.getElementById("age").value;
let voteable = (age < 18) ? "Too young":"Old enough";
document.getElementById("demo").innerHTML = voteable + " to vote.";
}
</script>
</body>
</html>
Loops
Round and round we go

▪Like conditionals, loops use the ( ) and { } blocks to define the


condition and the body of the loop.
▪You will encounter the while and for loops

▪While loops normally initialize a loop control variable before


the loop, use it in the condition, and modify it within the loop.
var i=0; // initialise the Loop Control Variable
while(i < 10){ //test the loop control variable
i++; //increment the loop control variable
}
For Loops
Counted loops

A for loop combines the common components of a loop:


initialization, condition, and post-loop operation into one
statement.
This statement begins with the for keyword and has the
components placed between ( ) brackets, semicolon (;)
separated as shown
Functions
Functions are the building block for modular code in
JavaScript, and are even used to build pseudo-classes, which
you will learn about later.
They are defined by using the reserved word function and
then the function name and (optional) parameters.
Since JavaScript is dynamically typed, functions do not require
a return type, nor do the parameters require type.
Functions
Example

Therefore a function to raise x to the yth power might be defined as:


function power(x,y){
var pow=1;
for (var i=0;i<y;i++){
pow = pow*x;
}
return pow;
}
And called as
power(2,10);
Alert
Not really used anymore, console instead

✓ The alert() function makes the browser show a pop-up to the


user, with whatever is passed being the message displayed. The
following JavaScript code displays a simple hello world message in
a pop-up:
alert ( "Good Morning" );
✓ Using alerts can get tedious fast. When using debugger tools in
your browser you can write output to a log with:
console.log("Put Messages Here");
And then use the debugger to access those logs.
Errors using try and catch

❑When the browser’s JavaScript engine encounters an error, it


will throw an exception. These exceptions interrupt the regular,
sequential execution of the program and can stop the
JavaScript engine altogether.
❑However, you can optionally catch these errors preventing
disruption of the program using the try–catch block
Throw your own
Exceptions that is.

❑Although try-catch can be used exclusively to catch built-in


JavaScript errors, it can also be used by your programs, to throw
your own messages.
❑The throw keyword stops normal sequential execution, just like
the built-in exceptions
Tips
With Exceptions

❖Try-catch and throw statements should be used for abnormal or


exceptional cases in your program.
❖Throwing an exception disrupts the sequential execution of a
program. When the exception is thrown all subsequent code is
not executed until the catch statement is reached.
❖This reinforces why try-catch is for exceptional cases.

You might also like