0% found this document useful (0 votes)
31 views

UNIT-IV Webtechnology

Uploaded by

bowb1043
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

UNIT-IV Webtechnology

Uploaded by

bowb1043
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

UNIT-IV

JAVASCRIPT
HOW TO ADD SCRIPT TO YOUR PAGES:
What Is JavaScript?
 JavaScript was designed to add interactivity to HTML pages
 JavaScript is a scripting language
 A scripting language is a lightweight programming language
 JavaScript is usually embedded directly into HTML pages
 JavaScript is an interpreted language (means that scripts execute without
preliminary compilation)
 Everyone can use JavaScript without purchasing a license
Linking JavaScript with HTML
There are following three main ways to add JavaScript to your web pages:
1. Embedding code: Adding the JavaScript code between a pair of
<script>...</script> tag
2.Inline code: Placing JavaScript code directly inside HTML tags using some
special attributes.
3.External file: Making a separate JavaScript file having .js as an extension.

Inline JavaScript

Inline JavaScript is placed directly within <script> tags in the HTML document.
This method is useful for small scripts or scripts specific to a single page.

Example of inline JavaScript:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Inline JavaScript Example</title>
<!-- No external script, just inline -->
<script>
function sayHello() {
alert('Hello, world!');
}
</script>
</head>
<body>
<h1>Inline JavaScript Example</h1>

<button onclick="sayHello()">Say Hello</button>


</body>
</html>

External JavaScript

For larger scripts or reusable code, it’s common practice to create an external
JavaScript file and link to it using the src attribute of the <script> tag. This keeps
your HTML cleaner and separates content from behavior.

Example of external JavaScript:

 Create a JavaScript file (e.g., script.js) with your JavaScript code:

// script.js
function sayHello() {
alert('Hello, world!');
}

 Link to the external script in your HTML document:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>External JavaScript Example</title>
<!-- Link to external script -->
<script src="script.js"></script>
</head>
<body>
<h1>External JavaScript Example</h1>

<button onclick="sayHello()">Say Hello</button>


</body>
</html>

VARIABLES AND DATA TYPES:


Variables and data types are foundational concepts in programming, serving as the
building blocks for storing and manipulating information within a program. In
JavaScript, understanding these concepts is essential for writing effective and
efficient code.
Variables
In JavaScript, variables are used to store and manage data. They are created using
the var, let, or const keyword.
var Keyword
The var keyword is used to declare a variable. It has a function-scoped or globally-
scoped behavior.
var x = 10;
Example:
var a = "Hello"
var b = 10;
var c = 12;
var d = b + c;
console.log(a);
console.log(b);
console.log(c);
console.log(d);

Output
Hello
10
12
22

 let Keyword
The let keyword is a block-scoped variables. It’s commonly used for variables that
may change their value.
let y = "Hello";
Example:

let a = "Hello learners"


let b = "joining";
let c = " 12";
let d = b + c;
console.log(a);
console.log(b);
console.log(c);
console.log(d);

Output
Hello learners
joining
12
joining 12
 const Keyword

The const keyword declares variables that cannot be reassigned. It’s block-scoped
as well.

const PI = 3.14;
Example:

const a = "Hello learners"


console.log(a);

const b = 400;
console.log(b);

const c = "12";
console.log(c);

Output
Hello learners
400
12
Data Types
JavaScript is a dynamically typed (also called loosely typed) scripting language.
In JavaScript, variables can receive different data types over time. The latest
ECMAScript standard defines eight data types Out of which seven data types are
Primitive (predefined) and one complex or Non-Primitive.
Primitive Data Types
The predefined data types provided by JavaScript language are known as primitive
data types. Primitive data types are also known as in-built data types.
 Number: JavaScript numbers are always stored in double-precision 64-bit
binary format IEEE 754. Unlike other programming languages, you don’t need
int, float, etc to declare different numeric values.
 String: JavaScript Strings are similar to sentences. They are made up of a list of
characters, which is essentially just an “array of characters, like “Hello world”
etc.
 Boolean: Represent a logical entity and can have two values: true or false.
 Null: This type has only one value that is null.
 Undefined: A variable that has not been assigned a value is undefined.
 Symbol: Symbols return unique identifiers that can be used to add unique
property keys to an object that won’t collide with keys of any other code that
might add to the object.
 BigInt: BigInt is a built-in object in JavaScript that provides a way to represent
whole numbers larger than 2^53-1.

Non-Primitive Data Types

The data types that are derived from primitive data types of the JavaScript
language are known as non-primitive data types. It is also known as derived data
types or reference data types.
 Object: It is the most important data type and forms the building blocks for
modern JavaScript. We will learn about these data types in detail in further
articles.
STATEMENTS AND OPERTORS:
Operator:
In JavaScript, an operator is a symbol that performs an operation on one or more
operands, such as variables or values, and returns a result. Let us take a simple
expression 4 + 5 is equal to 9. Here 4 and 5 are called operands, and ‘+’ is called
the operator.
 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Bitwise Operators
 Assignment Operators
 Miscellaneous Operators
Arithmetic Operators

The JavaScript arithmetic operators are used to perform mathematical calculations


such as addition, multiplication, subtraction, division, etc. on numbers. JavaScript
supports the following arithmetic operators −

Assume variable x holds 10 and variable y holds 20, then −

Operator Description Example


+ (Addition) Adds two operands. x + y will give 30.
- (Subtraction) Subtracts the second operand x - y will give -10.
from the first.
* (Multiplication) Multiplies both operands. x * y will give 200.
/ (Division) Divides the numerator by the y / x will give 2.
denominator.
% (Modulus) Outputs the remainder of an y % x will give 0
integer division.
++ (Increment) Increases an integer value by x++ will give 11.
one.
-- (Decrement) Decreases an integer value by x-- will give 9.
one.

Comparison Operators

The JavaScript comparison operators compare two values and returns a boolean
result (true or false). JavaScript supports the following comparison operators −

Assume variable x holds 10 and variable y holds 20, then −

Operator Description Example


== (Equal) Checks if the value of two operands is (x == y) is not
equal or not. If yes, then the condition true.
becomes true.
!= (Not Equal) Checks if the value of two operands is (x != y) is true.
equal or not. If the values are not equal,
then the condition becomes true.
=== (Strict It checks whether the value and data (x === y) is not
equality) type of the variable is equal or not. If true.
yes, then the condition becomes true.
!== (Strict It checks whether the value and data (x !== y) is true.
inequality) type of the variable is equal or not. If
the values are not equal, then the
condition becomes true.
> (Greater than) Checks if the value of the left operand (x > y) is not true.
is greater than the value of the right
operand. If yes, then the condition
becomes true.
< (Less than) Checks if the value of the left operand (x < y) is true.
is less than the value of the right
operand. If yes, then the condition
becomes true.
>= (Greater than Checks if the value of the left operand (x >= y) is not
or Equal to) is greater than or equal to the value of true.
the right operand. If yes, then the
condition becomes true.
<= (Less than or Checks if the value of the left operand (x <= y) is true.
Equal to) is less than or equal to the value of the
right operand. If yes, then the condition
becomes true.
Logical Operators

The logical operators are generally used to perform logical operations on boolean
values. But logical operators can be applied to values of any types not only boolean.

JavaScript supports the following logical operators −

Assume that the value of x is 10 and y is 0.

Operator Description Example


&& (Logical If both the operands are non-zero, then (x && y) is false
AND) the condition becomes true.
|| (Logical OR)If any of the two operands are non-zero, (x || y) is true.
then the condition becomes true.
! (Logical NOT) Reverses the logical state of its operand. !x is false.
If a condition is true, then the Logical
NOT operator will make it false.
Bitwise Operators

The JavaScript bitwise operators are used to perform bit-level operations on


integers. JavaScript supports the following seven types of bitwise operators −

Assume variable x holds 2 and variable y holds 3, then −

Operator Description Example


& (Bitwise It performs a Boolean AND operation on (x & y) is 2.
AND) each bit of its integer arguments.
| (Bitwise OR) It performs a Boolean OR operation on (x | y) is 3.
each bit of its integer arguments.
^ (Bitwise XOR) It performs a Boolean exclusive OR (x ^ y) is 1.
operation on each bit of its integer
arguments. Exclusive OR means that
either operand one is true or operand two
is true, but not both.
~ (Bitwise Not) It is a unary operator and operates by (~y) is -4.
reversing all the bits in the operand.
<< (Left Shift) It moves all the bits in its first operand to (x << 1) is 4.
the left by the number of places specified
in the second operand. New bits are filled
with zeros. Shifting a value left by one
position is equivalent to multiplying it by
2, shifting two positions is equivalent to
multiplying by 4, and so on.
>> (Right Shift) Binary Right Shift Operator. The left (x >> 1) is 1.
operand’s value is moved right by the
number of bits specified by the right
operand.
>>> (Right shift This operator is just like the >> operator, (x >>> 1) is 1.
with Zero) except that the bits shifted in on the left
are always zero.

Assignment Operators

In JavaScript, an assignment operator is used to assign a value to a variable.


JavaScript supports the following assignment operators −

Operator Description Example


= (Simple Assigns values from the right side z = x + y will
Assignment) operand to the left side operand assign the value of
x + y into z
+= (Add and It adds the right operand to the left z += x is equivalent
Assignment) operand and assigns the result to the to z = z + x
left operand.
−= (Subtract and It subtracts the right operand from the z -= x is equivalent
Assignment) left operand and assigns the result to to z = z - x
the left operand.
*=(Multiply and It multiplies the right operand with the z *= x is equivalent
Assignment) left operand and assigns the result to to z = z * x
the left operand.
/= (Divide and It divides the left operand with the right z /= x is equivalent
Assignment) operand and assigns the result to the to z = z / x
left operand.
%= (Modules and It takes modulus using two operands z %= x is
Assignment) and assigns the result to the left equivalent to z =
operand. z%x

Miscellaneous Operators

There are few other operators supported by JavaScript. These operators are
conditional operator (? :), typeof operator, delete operator, etc.

In the below table, we have given the JavaScript miscellaneous operators with its
explanation.

Operator Description
? : (Conditional ) If Condition is true? Then value X : Otherwise value Y
typeof It returns the data type of the operand.
?? (Nullish Coalescing It returns its right-hand side operand when its left-hand
Operator) side operand is null or undefined, and otherwise returns
its left-hand side operand.
delete It removes a property from an object.
, (Comma) It evaluates its operands (from left to right) and returns
the value of the last operand.
() (Grouping) It allows to change the operator precedence.
yield It is used to pause and resume a generator function.
… (Spread) It is used to expand the iterables such as array or string.
** (Exponentiation) Raises the left operand to the power of the right operand
STATEMENTS:
In JavaScript, statements are instructions that are executed by the browser or Node.js.
A statement can be a simple or complex operation that performs an action, such as
assigning a value to a variable, calling a function, or controlling program flow with
conditional statements.
Declaration Statements
Declaration statements are variables, functions, or classes that are introduced into a
program. These statements begin with a keyword followed by its identifier or name.
Variables are containers for storing data values:

var x = 5;
var y = 6;

var X = 4;
var z = x + y;

In this example, x, y, X, and z, are declared with the var keyword.


Example

var x = 5; Output:
console.log(x) 5
var y = 6; 6
console.log(y) 4
var x = 4; 10
console.log(x)
var z = x + y;
console.log(z)

 Variable Declaration: Declares variables using var, let, or const.


var x;
let y = 10;
const PI = 3.14;

 Function Declaration: Defines functions.

function add(a, b) {
return a + b;
}

 Class Declaration: Defines classes.

class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}

Control Statements in JavaScript:


JavaScript control statement is used to control the execution of a program based
on a specific condition. If the condition meets then a particular block of action will
be executed otherwise it will execute another block of action that satisfies that
particular condition.
Types of Control Statements in JavaScript
 Conditional Statement: These statements are used for decision-making, a
decision
 n is made by the conditional statement based on an expression that is passed.
Either YES or NO.
 Iterative Statement: This is a statement that iterates repeatedly until a
condition is met. Simply said, if we have an expression, the statement will keep
repeating itself until and unless it is satisfied.
 if...else statement:

let num = 10;


if (num > 0) {
console.log("Number is positive");
} else if (num < 0) {
console.log("Number is negative");
} else {
console.log("Number is zero");
}

 switch statement: Allows you to execute one block of code among many
alternatives.

let day = "Monday";


switch (day) {
case "Monday":
console.log("Today is Monday");
break;
case "Tuesday":
console.log("Today is Tuesday");
break;
default:
console.log("Not a weekday");
}

Conditional Statements:
JavaScript conditional statements allow you to execute specific blocks of code
based on conditions. If the condition is met, a particular block of code will run;
otherwise, another block of code will execute based on the condition.
There are several methods that can be used to perform Conditional Statements in
JavaScript.
Conditional Description
Statement
if statement Executes a block of code if a specified condition is true.
else statement Executes a block of code if the same condition of the
preceding if statement is false.
else if statement Adds more conditions to the if statement, allowing for multiple
alternative conditions to be tested.
switch Evaluates an expression, then executes the case statement that
statement matches the expression’s value.
ternary operator Provides a concise way to write if-else statements in a single
line.
Nested if else Allows for multiple conditions to be checked in a hierarchical
statement manner.

Loop Statements:

Loops are used to execute a block of code repeatedly as long as a specified


condition is true.

 for loop: Executes a block of code a specified number of times.

for (let i = 0; i < 5; i++) {


console.log(i); // Outputs 0, 1, 2, 3, 4
}

 while loop: Executes a block of code while a specified condition is true.

let i = 0;
while (i < 5) {
console.log(i); // Outputs 0, 1, 2, 3, 4
i++;
}

 do...while loop: Similar to a while loop, but it always executes the block of
code once before checking the condition.

let i = 0;
do {
console.log(i); // Outputs 0, 1, 2, 3, 4
i++;
} while (i < 5);

 for...in loop: Iterates over the enumerable properties of an object.


const person = { name: 'John', age: 30 };
for (let key in person) {
console.log(`${key}: ${person[key]}`); // Outputs "name: John" and "age: 30"
}

 for...of loop: Iterates over iterable objects (arrays, strings, etc.).

const colors = ['red', 'green', 'blue'];


for (let color of colors) {
console.log(color); // Outputs "red", "green", "blue"
}

FUNCTIONS IN JAVASCRIPT:

In JavaScript, functions are a fundamental building block of the language, allowing


you to encapsulate a block of code that can be called and executed later. Here are
some key aspects and examples of functions in JavaScript:

Function Declaration

Functions in JavaScript can be declared using the function keyword. There are
several ways to declare functions:

1. Function Declaration:
function greet(name) {
return `Hello, ${name}!`; }

This is a named function (greet), which takes a parameter name and returns a
greeting string.

2. Function Expression:

const greet = function(name) {


return `Hello, ${name}!`;
};
This is an anonymous function assigned to the variable greet.
3. Arrow Function:

const greet = (name) => {


return `Hello, ${name}!`;
};
Shorter syntax for writing functions introduced in ES6.

Calling Functions

Functions are called or invoked by using parentheses (), optionally passing


arguments inside them:

const result = greet("Alice");


console.log(result); // Output: Hello, Alice!

Function Parameters and Return Values

Functions can take parameters (values passed to the function) and return values
(values returned by the function after execution):

function add(a, b) {
return a + b;
}

const sum = add(3, 5);


console.log(sum); // Output: 8

Function Scope

Variables declared inside a function are scoped to that function (local scope),
unless declared with var (which would make them function-scoped), let, or
const (block-scoped):

function example() {
const localVar = "Hello";
console.log(localVar); // Output: Hello
}

Function Hoisting

In JavaScript, function declarations are hoisted, meaning they are moved to the top
of their scope during compilation, allowing you to call functions before they're
declared in the code:

console.log(add(2, 3)); // Output: 5


function add(x, y) {
return x + y;
}

Callback Functions

JavaScript functions can be passed as arguments to other functions, commonly


used in asynchronous programming (callbacks):

function fetchData(callback) {
setTimeout(() => {
const data = "Some fetched data";
callback(data);
}, 1000);
}

fetchData((data) => {
console.log(data); // Output after 1 second: Some fetched data
});
Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute
the code after the invoking statement.
Functions often compute a return value. The return value is "returned" back to the
"caller":

Example Calculate the product of two numbers, and return the result:

// Function is called, the return value will end up in x


let x = myFunction(4, 3);

function myFunction(a, b) {
// Function returns the product of a and b
return a * b;
}

Message Box

In JavaScript, "message box" generally refers to a simple popup window that


displays a message to the user. The most common example is the alert()
function:

alert("This is a message box!");

 Functionality: The alert() function displays a modal dialog box with a


message and an OK button. It's useful for showing notifications or alerts to
the user.
 Usage: Alerts should be used sparingly for important messages as they
interrupt the user's workflow until dismissed.

Dialog Box:
In JavaScript, "dialog boxes" refer to popup windows that interact with users by
displaying messages, asking for confirmation, or prompting for input. There are
several types of dialog boxes commonly used:
Alert Box
An alert box is often used if you want to make sure information comes through to
the user.

When an alert box pops up, the user will have to click "OK" to proceed.

Syntax

window.alert("hello world");

The window.alert() method can be written without the window prefix.

Example

alert("I am an alert box!");

Confirm Box:
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel"
to proceed.

If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false.

Syntax
window.confirm("Are you okay");

The window.confirm() method can be written without the window prefix.

Example
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}

Prompt Box:

A prompt box is often used if you want the user to input a value before entering a
page.

When a prompt box pops up, the user will have to click either "OK" or "Cancel" to
proceed after entering an input value.

If the user clicks "OK" the box returns the input value. If the user clicks "Cancel"
the box returns null.

Syntax
window.prompt("Are you okay"," Yes I’m Good");

The window.prompt() method can be written without the window prefix.

Example

let person = prompt("Please enter your name", "Harry Potter");


let text;
if (person == null || person == "") {
text = "User cancelled the prompt.";
} else {
text = "Hello " + person + "! How are you today?";
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy