[go: up one dir, main page]

0% found this document useful (0 votes)
19 views36 pages

WP-Unit 3

Unit 3 of the Web Programming course covers the fundamentals of JavaScript, including its integration with HTML, programming concepts such as variables, operators, control flow statements, functions, and objects. It emphasizes the use of external JavaScript files for better code organization and provides examples of key programming structures. Understanding these concepts is essential for developing interactive web applications.

Uploaded by

ay983754
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views36 pages

WP-Unit 3

Unit 3 of the Web Programming course covers the fundamentals of JavaScript, including its integration with HTML, programming concepts such as variables, operators, control flow statements, functions, and objects. It emphasizes the use of external JavaScript files for better code organization and provides examples of key programming structures. Understanding these concepts is essential for developing interactive web applications.

Uploaded by

ay983754
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

F.Y.C.

S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3


UNIT 3: Fundamentals of JavaScript
Description:
JavaScript : Using JavaScript in an HTML Document, Programming Fundamentals of
JavaScript – Using an external JavaScript file, Variables, Operators, Control Flow
Statements - if, if..else, switch, while loop, do..while loop, for loop, break statement,
continue statement, Popup Boxes - alert, confirm, prompt, Functions – Defining and
Invoking a Function, Defining Function arguments, Defining a Return Statement, Working
with onClick event. JavaScript Objects - String, RegExp, Math, Date

➢ JAVASCRIPT:
JavaScript is the world's most popular programming language. JavaScript is the programming language of
the Web. JavaScript is easy to learn. JavaScript is a scripting or programming language that allows you to
implement complex features on web pages — every time a web page does more than just sit there and
display static information for you to look at — displaying timely content updates, interactive maps,
animated 2D/3D graphics, scrolling video jukeboxes, etc. — you can bet that JavaScript is probably involved.
It is the third layer of the layer cake of standard web technologies, two of which HTML and CSS.

➢ Using JavaScript in an HTML Document:


The HTML <script> tag is used to define a client-side script (JavaScript). The <script> element either
contains script statements, or it points to an external script file through the src attribute. Common uses for
JavaScript are image manipulation, form validation, and dynamic changes of content. To select an HTML
element, JavaScript most often uses the document.getElementById() method. This JavaScript example
writes "Hello JavaScript!" into an HTML element with id="demo":
Example 1
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
Example 2
JavaScript can change content:
document.getElementById("demo").innerHTML = "Hello JavaScript!";
Example 3
JavaScript can change styles:
document.getElementById("demo").style.fontSize = "25px";
document.getElementById("demo").style.color = "red";
document.getElementById("demo").style.backgroundColor = "yellow";
1
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
Example 4
JavaScript can change attributes:
document.getElementById("image").src = "picture.gif";
Example – Code:
<html>
<head>
<title>JavaScript in HTML</title>
</head>
<body>
<h1>JavaScript in HTML Example</h1>

<p id="demo">This text will change when the button is clicked.</p>

<button onclick="changeText()">Click Me</button>

<script>
function changeText() {
document.getElementById("demo").innerHTML = "Text changed!";
}
</script>
</body>
</html>

In this example:
The <script> tag is used to contain JavaScript code.
Inside the <script> tags, a function changeText() is defined. This function changes the content of the
paragraph with the id demo.
The onclick attribute of the button element is set to call the changeText() function when the button is
clicked.
When the button is clicked, the content of the paragraph with id demo changes to "Text changed!".
This is a simple example, but JavaScript can be used for much more complex interactions and
manipulations within an HTML document.

The HTML <noscript> Tag


The HTML <noscript> tag defines an alternate content to be displayed to users that have disabled scripts in
their browser or have a browser that doesn't support scripts:
Example
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>

2
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
<noscript>Sorry, your browser does not support JavaScript!</noscript>

➢ Programming Fundamentals of JavaScript:


Variables: Variables are used to store data values. In JavaScript, you can declare variables using var, let, or
const.
var x = 10;
let y = "Hello";
const PI = 3.14;

Data Types: JavaScript supports several data types, including numbers, strings, booleans, arrays, objects,
and more.
var num = 10;
var str = "Hello";
var bool = true;
var arr = [1, 2, 3];
var obj = { name: "John", age: 30 };

Operators: JavaScript supports various operators for performing operations on variables and values, such
as arithmetic operators (+, -, *, /), comparison operators (==, !=, >, <), logical operators (&&, ||, !), etc.
var a = 5;
var b = 3;
var sum = a + b;
var isGreaterThan = a > b;

Control Flow: JavaScript provides structures for controlling the flow of your code, including if statements,
switch statements, for loops, while loops, and do-while loops.
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}

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


// code to be executed repeatedly
}

while (condition) {
// code to be executed while condition is true
}

3
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
Functions: Functions are blocks of code that can be reused. You can define functions using the function
keyword.
function greet(name) {
return "Hello, " + name + "!";
}
var message = greet("John");

Objects and Classes: JavaScript is an object-oriented language. Objects are collections of properties and
methods. Classes provide a blueprint for creating objects.
// Object
var person = {
name: "John",
age: 30,
greet: function() {
return "Hello, my name is " + this.name + ".";
}
};

// Class
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}

greet() {
return "Hello, my name is " + this.name + ".";
}
}
var john = new Person("John", 30);

These are some fundamental concepts in JavaScript. Understanding them will provide you with a solid
foundation for further learning and development.

➢ Using an External JavaScript File:


Using an external JavaScript file is a common practice in web development as it helps to keep your HTML
code clean and separates concerns between markup and logic. Here's how you can use an external
JavaScript file:

• Create a JavaScript File: First, create a new file with a .js extension. For example, script.js.

4
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
• Write Your JavaScript Code: Inside the JavaScript file, write your JavaScript code just as you would
between <script> tags in your HTML document.

// script.js
function greet(name) {
alert("Hello, " + name + "!");
}

• Link the JavaScript File in HTML: In your HTML file, use the <script> tag to link to the external
JavaScript file. Place this <script> tag either in the <head> section or at the end of the <body>
section.

<html>
<head>
<title>External JavaScript Example</title>
<!-- Link to external JavaScript file -->
<script src="script.js"></script>
</head>
<body>
<h1>External JavaScript Example</h1>

<button onclick="greet('World')">Click Me</button>


</body>
</html>

In this example:
The JavaScript code is saved in an external file named script.js.
In the HTML file, we link to the script.js file using the <script> tag with the src attribute pointing to the
location of the JavaScript file.
Now, the greet() function defined in the external JavaScript file can be called directly from the HTML file.
This approach keeps your code modular and maintainable, especially for larger projects.

➢ Variables:
Variables in JavaScript are containers for storing data values. You can think of them as named storage
locations for holding information that can be referenced and manipulated within a program. Here are some
key points about variables in JavaScript:

Variable Declaration: You can declare variables using three different keywords: var, let, and const.
• var: The traditional way of declaring variables in JavaScript. It has function-level scope.
• let: Introduced in ECMAScript 6 (ES6). It has block-level scope.
• const: Also introduced in ES6. It declares a constant variable whose value cannot be reassigned.
var x = 10;
let y = "Hello";
const PI = 3.14;

5
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3

Variable Naming: Variable names (identifiers) can contain letters, digits, underscores, and dollar signs.
They must begin with a letter, dollar sign, or underscore. Variable names are case-sensitive.
var firstName = "John";
var age = 30;
var _variable = 5;

Data Types: Variables in JavaScript can hold various data types, including numbers, strings, booleans,
arrays, objects, and more.
var num = 10;
var str = "Hello";
var bool = true;
var arr = [1, 2, 3];
var obj = { name: "John", age: 30 };

Variable Scope: The scope of a variable defines where in your code the variable can be accessed. Variables
declared with var have function-level scope, while variables declared with let and const have block-level
scope.
function myFunction() {
var localVar = 10;
if (true) {
let blockVar = 20;
console.log(localVar); // Accessible
console.log(blockVar); // Accessible
}
console.log(localVar); // Accessible
console.log(blockVar); // Not accessible (ReferenceError)
}

Hoisting: In JavaScript, variable declarations are hoisted to the top of their scope. This means you can
access a variable before it's declared, but its value will be undefined.
console.log(myVar); // undefined
var myVar = 10;
Understanding variables is essential for writing JavaScript code because they are used extensively for
storing and manipulating data throughout your programs.

➢ Operators:
Operators in JavaScript are symbols that allow you to perform operations on variables and values.
JavaScript supports various types of operators, including arithmetic, assignment, comparison, logical,
bitwise, and more. Here's an overview of the main types of operators in JavaScript:

Arithmetic Operators: Used to perform arithmetic operations like addition, subtraction, multiplication,
division, and modulus (remainder).
var x = 10;

6
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
var y = 5;
var sum = x + y; // Addition
var difference = x - y; // Subtraction
var product = x * y; // Multiplication
var quotient = x / y; // Division
var remainder = x % y; // Modulus

Assignment Operators: Used to assign values to variables.


var x = 10;
x += 5; // Equivalent to x = x + 5

Comparison Operators: Used to compare two values and return a boolean result (true or false).
var x = 10;
var y = 5;
var isEqual = x == y; // Equality
var isGreater = x > y; // Greater than
var isLess = x < y; // Less than
var isNotEqual = x != y; // Inequality

Logical Operators: Used to perform logical operations on boolean values.


var x = true;
var y = false;
var result = x && y; // Logical AND
var result = x || y; // Logical OR
var result = !x; // Logical NOT

Bitwise Operators: Used to perform bitwise operations on integers.


var x = 5; // Binary representation: 101
var y = 3; // Binary representation: 011
var result = x & y; // Bitwise AND (1 & 1 = 1, others are 0)
var result = x | y; // Bitwise OR (0 | 1 = 1, others are 0)
var result = ~x; // Bitwise NOT (1's complement)

String Operators: Used to concatenate strings.


var firstName = "John";
var lastName = "Doe";
var fullName = firstName + " " + lastName; // Concatenation

These are some of the most used operators in JavaScript. Understanding how to use them effectively is
crucial for writing efficient and concise code.

➢ Control Flow Statements:


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.
7
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
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.
There are several methods that can be used to perform control statements in JavaScript:

• If Statement
• Using If-Else Statement
• Using Switch Statement
• Using the Ternary Operator (Conditional Operator)
• Using For loop

➢ Control Flow Statements - If:


In this approach, we are using an if statement to check a specific condition, the code block gets executed
when the given condition is satisfied.
Syntax:
if ( condition_is_given_here )
{
// If the condition is met,
//the code will get executed.
}

Example: In this example, we are using an if statement to check our given condition.
const num = 5;
if (num > 0)
{
console.log("The number is positive.");
};

Output
The number is positive.

➢ Control Flow Statements - If….else :


The if-else statement will perform some action for a specific condition. If the condition meets then a
particular code of action will be executed otherwise it will execute another code of action that satisfies that
particular condition.

Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2) {
// Executes when condition2 is true
8
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
}
}

Example: In this example, we are using the if..else statement to verify whether the given number is positive
or negative.

let num = -10;


if (num > 0)
console.log("The number is positive.");
else
console.log("The number is negative");

Output
The number is negative

➢ Control Flow Statements - Switch:


The switch case statement in JavaScript is also used for decision-making purposes. In some cases, using the
switch case statement is seen to be more convenient than if-else statements.

Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}

Example: In this example, we are using the above-explained approach.


let num = 5;
switch (num)
{
case 0:
console.log("Number is zero.");
break;
case 1:
console.log("Nuber is one.");
break;

9
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
case 2:
console.log("Number is two.");
break;
default:
console.log("Number is greater than 2.");
};

Output
Number is greater than 2.

➢ Control Flow Statements - While Loop:


A While Loop in JavaScript is a control flow statement that allows the code to be executed repeatedly based
on the given boolean condition. The while loop can be thought of as a repeating if statement. The loop can
be used to execute the specific block of code multiple times until it fails to match the condition.

There are mainly two types of loops:

• Entry Controlled loops: In this type of loop, the test condition is tested before entering the loop
body. For Loop and While Loops are entry-controlled loops.
• Exit Controlled Loops: In this type of loop the test condition is tested or evaluated at the end of the
loop body. Therefore, the loop body will execute at least once, irrespective of whether the test
condition is true or false. the do-while loop is exit controlled loop.
Syntax:
while (condition)
{
// Statements
}

Example: This example illustrates the use of a while loop.

// JavaScript code to use while loop


let val = 1;
while (val < 6)
{
console.log(val);
val += 1;
}

Output
1
2
3
4
5

➢ Control Flow Statements - Do…While Loop:


A do-while loop is a control flow statement that executes a block of code at least once, and then repeatedly
executes the block or not depending on a given boolean condition at the end of the block.
10
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3

Syntax:
do
{
// Statements
}
while (condition);

Example: This example illustrates the use of the do-while loop.

// JavaScript code to use while loop


let val = 1;
do
{
console.log(val);

val += 1;

} while (val < 6);

Output
1
2
3
4
5

➢ Control Flow Statements - For Loop:


In this approach, we are using for loop in which the execution of a set of instructions repeatedly until some
condition evaluates and becomes false

Syntax:
for (statement 1; statement 2; statement 3)
{
// Code here . . .
}

Example: In this example, we are using Iterative Statement as a for loop, in which we find the even number
between 0 to 10.

for (let i = 0; i <= 10; i++)


{
if (i % 2 === 0)
{
console.log(i);
}
};

11
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
Output
0
2
4
6
8
10

➢ Control Flow Statements - Break Statement:


The break statement "jumps out" of a loop.
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump
out" of a switch() statement.

The break statement can also be used to jump out of a loop:

Example
for (let i = 0; i < 10; i++)
{
if (i === 3) { break; }
text += "The number is " + i + "<br>";
}
In this example, the break statement ends the loop ("breaks" the loop) when the loop counter (i) is 3.

➢ Control Flow Statements - Continue Statement:


The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues
with the next iteration in the loop.
This example skips the value of 3:
Example
for (let i = 0; i < 10; i++)
{
if (i === 3) { continue; }
text += "The number is " + i + "<br>";
}

➢ Popup Boxes:
To Create Popups

Step 1) Add HTML:


Example
<div class="popup" onclick="myFunction()">Click me!

12
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
<span class="popuptext" id="myPopup">Popup text...</span>
</div>

Step 2) Add CSS:


Example
/* Popup container */
.popup {
position: relative;
display: inline-block;
cursor: pointer;
}

/* The actual popup (appears on top) */


.popup .popuptext {
visibility: hidden;
width: 160px;
background-color: #555;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 8px 0;
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
margin-left: -80px;
}

/* Popup arrow */
.popup .popuptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}

/* Toggle this class when clicking on the popup container (hide and show the popup) */
.popup .show {
visibility: visible;
-webkit-animation: fadeIn 1s;
animation: fadeIn 1s
}

/* Add animation (fade in the popup) */


@-webkit-keyframes fadeIn {

13
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
from {opacity: 0;}
to {opacity: 1;}
}

@keyframes fadeIn {
from {opacity: 0;}
to {opacity:1 ;}
}

Step 3) Add JavaScript:


Example
<script>
// When the user clicks on <div>, open the popup
function myFunction() {
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
}
</script>

In Javascript, popup boxes are used to display the message or notification to the user.
There are three types of pop-up boxes in JavaScript:

• Alert Box
• Prompt Box
• Confirm Box

➢ Popup Boxes – Alert:


It is used when a warning message is needed to be produced. When the alert box is displayed to the user,
the user needs to press ok and proceed.
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("sometext");

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

Syntax:
alert("your Alert here");

Example: This example shows the implementation of the alert box.


<html>
<head>
<title>Pop-up Box type | Alert Box</title>
<style>
h1{
color:green;
}
14
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
</style>
</head>

<body>
<center>
<h1>Welcome to Pop-up Alerts</h1>

<h3>Alert Box</h3>
<button onclick="newAlert()">
Click here for alert box
</button>

<!-- Alert box function -->


<script>
function newAlert() {
alert("An Online Computer Science"
+ "Portal for Alerts");
}
</script>
</center>
</body>
</html>

➢ Popup Boxes – Confirm:


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. It is a type of pop-up box that is used to get
authorization or permission from the user. The user has to press the ok or cancel button to proceed.

Syntax
window.confirm("sometext");
or
confirm("your query here");

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

Example
<html>
<body>

<h2>JavaScript Confirm Box</h2>

<button onclick="myFunction()">Try it</button>

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

<script>

15
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
function myFunction()
{
var txt;
if (confirm("Press a button!"))
{
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>

➢ Popup Boxes – Prompt:


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. It is a
type of pop up box which is used to get the user input for further use. After entering the required details
user have to click ok to proceed next stage else by pressing the cancel button user returns the null value.

Syntax
window.prompt("sometext","defaultText");
or
prompt("your Prompt here");

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

Example
<html>
<body>
<h2>JavaScript Prompt</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
let text;
let person = prompt("Please enter your name:", "Harry Potter");
if (person == null || person == "")
{
text = "User cancelled the prompt.";
}
else
{
text = "Hello " + person + "! How are you today?";

16
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>

➢ Functions:
JavaScript function is a set of statements that take inputs, do some specific computation, and produce
output. A JavaScript function is executed when “something” invokes it (calls it).

Example 1: A basic javascript function, here we create a function that divides the 1st element by the
second element.

function myFunction(g1, g2)


{
return g1 / g2;
}
const value = myFunction(8, 2); // Calling the function
console.log(value);

Output:
4

You must already have seen some commonly used functions in JavaScript like alert(), which is a built-in
function in JavaScript. But JavaScript allows us to create user-defined functions also. We can create
functions in JavaScript using the keyword `function`.

Syntax: The basic syntax to create a function in JavaScript is shown below.

function functionName(Parameter1, Parameter2, ...)


{
// Function body
}

To create a function in JavaScript, we have to first use the keyword function, separated by the name of the
function and parameters within parenthesis. The part of the function inside the curly braces {} is the body
of the function. In javascript, functions can be used in the same way as variables for assignments, or
calculations.

➢ Functions – Defining and Invoking a Function:


Defining Function:
Before, using a user-defined function in JavaScript we have to create one. We can use the above syntax to
create a function in JavaScript. A function definition is sometimes also termed a function declaration or
function statement. Below are the rules for creating a function in JavaScript:

• Every function should begin with the keyword function followed by,
17
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
• A user-defined function name that should be unique,
• A list of parameters enclosed within parentheses and separated by commas,
• A list of statements composing the body of the function enclosed within curly braces {}.

Example: This example shows a basic declaration of a function in javascript.

function calcAddition(number1, number2) {


return number1 + number2;
}
console.log(calcAddition(6,9));

Output
15

In the above example, we have created a function named calcAddition,


• This function accepts two numbers as parameters and returns the addition of these two numbers.
• Accessing the function with just the function name without () will return the function object instead
of the function result.
There are three ways of writing a function in JavaScript:
• Function Declaration
• Function Expression
• Arrow Function

• Function Declaration: It declares a function with a function keyword. The function declaration
must have a function name.
Syntax:
function functionName(paramA, paramB) {
// Set of statements
}

• Function Expression:
It is similar to a function declaration without the function name. Function expressions can be stored in a
variable assignment.
Syntax:
let functionName= function(paramA, paramB) {
// Set of statements
}

Example: This example explains the usage of the Function expression.


const square = function (number) {
return number * number;
};
const x = square(4); // x gets the value 16
console.log(x);

Output
16

18
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
• Arrow Function:
It is one of the most used and efficient methods to create a function in JavaScript because of its
comparatively easy implementation. It is a simplified as well as a more compact version of a regular or
normal function expression or syntax.
Syntax:
let function_name = (argument1, argument2 ,..) => expression
Example: This example describes the usage of the Arrow function.
const a = ["Hydrogen", "Helium", "Lithium", "Beryllium"];
const a2 = a.map(function (s) {
return s.length;
});
console.log("Normal way ", a2); // [8, 6, 7, 9]
const a3 = a.map((s) => s.length);
console.log("Using Arrow Function ", a3); // [8, 6, 7, 9]
Output
Normal way [ 8, 6, 7, 9 ]
Using Arrow Function [ 8, 6, 7, 9 ]

Invoking (Calling) a Function:


Once a function is defined, you can invoke or call it to execute the code inside it. To invoke a function,
simply write its name followed by parentheses () containing any arguments (if required). Here's the syntax:
functionName(argument1, argument2, ...);
Example:
greet("John"); // Output: Hello, John!
Function Invocation happens when;
• Triggered by an event (e.g., a button click by a user).
• When explicitly called from JavaScript code.
• Automatically executed, such as in self-invoking functions.

➢ Functions – Defining Function Arguments:


Parameters are placeholders for the values that a function needs to perform its task. When you define a
function, you specify its parameters. Arguments, on the other hand, are the actual values passed to a
function when it's invoked. These arguments are substituted for the parameters inside the function body
during execution.

19
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
Parameters are additional information passed to a function. For example, in the above example, the task of
the function calcAddition is to calculate the addition of two numbers. These two numbers on which we
want to perform the addition operation are passed to this function as parameters. The parameters are
passed to the function within parentheses after the function name and separated by commas. A function in
JavaScript can have any number of parameters and also at the same time, a function in JavaScript can not
have a single parameter.

Example: In this example, we pass the argument to the function.


function multiply(a, b) {
b = typeof b !== "undefined" ? b : 1;
return a * b;
}
console.log(multiply(69)); // 69

Output
69

Example:
function add(a, b) {
console.log(a + b);
}

add(5, 3);

Output: 8

Function parameters are the names listed in the function definition.


Function arguments are the real values passed to (and received by) the function.

Parameter Rules:
• JavaScript function definitions do not specify data types for parameters.
• JavaScript functions do not perform type checking on the passed arguments.
• JavaScript functions do not check the number of arguments received.

Default Parameters
If a function is called with missing arguments (less than declared), the missing values are set to undefined.
Sometimes this is acceptable, but sometimes it is better to assign a default value to the parameter.
Example:
function myFunction(x, y) {
if (y === undefined) {
y = 2;
}
}

Function Rest Parameter: The rest parameter (...) allows a function to treat an indefinite number of
arguments as an array:

Example
function sum(...args) {

20
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
let sum = 0;
for (let arg of args) sum += arg;
return sum;
}
let x = sum(4, 9, 16, 25, 29, 100, 66, 77);

The Arguments Object


JavaScript functions have a built-in object called the arguments object. The argument object contains an
array of the arguments used when the function was called (invoked). This way you can simply use a
function to find (for instance) the highest value in a list of numbers:

Example
x = findMax(1, 123, 500, 115, 44, 88);
function findMax() {
let max = -Infinity;
for (let i = 0; i < arguments.length; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}

Or create a function to sum all input values:

Example
x = sumAll(1, 123, 500, 115, 44, 88);

function sumAll() {
let sum = 0;
for (let i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}

If a function is called with too many arguments (more than declared), these arguments can be reached
using the arguments object.

Arguments are Passed by Value


The parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value:
The function only gets to know the values, not the argument's locations. If a function changes an
argument's value, it does not change the parameter's original value. Changes to arguments are not visible
(reflected) outside the function.

Objects are Passed by Reference


In JavaScript, object references are values. Because of this, objects will behave like they are passed by
reference. If a function changes an object property, it changes the original value. Changes to object
properties are visible (reflected) outside the function.

21
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
➢ Functions – Defining a Return Statement:
The return statement ends function execution and specifies a value to be returned to the function caller.
Syntax
return;
return expression;
Expression is Optional. The expression whose value is to be returned. If omitted, undefined is returned.

The return statement can only be used within function bodies. When a return statement is used in a
function body, the execution of the function is stopped. The return statement has different effects when
placed in different functions:
• In a plain function, the call to that function evaluates to the return value.
• In an async function, the produced promise is resolved with the returned value.
• In a generator function, the produced generator object's next() method returns { done: true, value:
returnedValue }.
• In an async generator function, the produced async generator object's next() method returns a
promise fulfilled with { done: true, value: returnedValue }.
If a return statement is executed within a try block, its finally block, if present, is first executed, before the
value is actually returned.

Automatic semicolon insertion


The syntax forbids line terminators between the return keyword and the expression to be returned.
return
a + b;

The code above is transformed by automatic semicolon insertion (ASI) into:


return;
a + b;

This makes the function return undefined and the a + b expression is never evaluated. This may generate a
warning in the console. To avoid this problem (to prevent ASI), you could use parentheses:
return (
a+b
);

➢ Working with onClick event:


The onclick event generally occurs when the user clicks on an element. It allows the programmer to execute
a JavaScript's function when an element gets clicked. This event can be used for validating a form, warning
messages and many more.

Using JavaScript, this event can be dynamically added to any element. It supports all HTML elements except
<html>, <head>, <title>, <style>, <script>, <base>, <iframe>, <bdo>, <br>, <meta>, and <param>. It means
we cannot apply the onclick event on the given tags.

22
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
In HTML, we can use the onclick attribute and assign a JavaScript function to it. We can also use the
JavaScript's addEventListener() method and pass a click event to it for greater flexibility.

Syntax
Now, we see the syntax of using the onclick event in HTML and in javascript (without addEventListener()
method or by using the addEventListener() method).

In HTML
<element onclick = "fun()">

In JavaScript
object.onclick = function() { myScript };

In JavaScript by using the addEventListener() method


object.addEventListener("click", myScript);

Let's see how to use onclick event by using some illustrations. Now, we will see the examples of using the
onclick event in HTML, and in JavaScript.

Example - Using onclick attribute in HTML


In this example, we are using the HTML onclick attribute and assigning a JavaScript's function to it. When
the user clicks the given button, the corresponding function will get executed, and an alert dialog box will
be displayed on the screen.

<!DOCTYPE html>
<html>
<head>
<script>
function fun() {
alert("Welcome to the javaTpoint.com");
}
</script>
</head>
<body>
<h3> This is an example of using onclick attribute in HTML. </h3>
<p> Click the following button to see the effect. </p>
<button onclick = "fun()">Click me</button>
</body>
</html>

➢ JavaScript Objects:
Objects, in JavaScript, are the most important data type and form the building blocks for modern
JavaScript. These objects are quite different from JavaScript’s primitive data types (Number, String,
Boolean, null, undefined, and symbol) in the sense that these primitive data types all store a single value
each (depending on their types).
23
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3

Syntax:
new Object(value)
Object(value)
let object_name = {
key_name : value,
...
}
Note:- Object() can be called with or without new. Both create a new object.
Example: Below is an example of Objects in JavaScript.
const o = new Object();
o.foo = 42;
console.log(o);
// { foo: 42 }

Output
{ foo: 42 }

Example: In this example “name”, “location”, and “established” are all “keys” and “Vivekananda School”,
“Delhi” and 1971 are values of these keys respectively. Each of these keys is referred to as properties of the
object. An object in JavaScript may also have a function as a member, in which case it will be known as a
method of that object. Here “displayinfo” is a method of the school object that is being used to work with
the object’s data, stored in its properties.
// JavaScript code demonstrating a simple object
let school = {
name: 'Vivekananda School',
location: 'Delhi',
established: '1971',
displayInfo: function () {
console.log(`${school.name} was established
in ${school.established} at ${school.location}`);
}
24
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
}
school.displayInfo();

Output
Vivekananda School was established
in 1971 at Delhi
Objects are more complex and each object may contain any combination of these primitive data-types as
well as reference data-types.
An object is a reference data type. Variables that are assigned a reference value are given a reference or a
pointer to that value. That reference or pointer points to the location in memory where the object is
stored. The variables don’t actually store the value.
Loosely speaking, objects in JavaScript may be defined as an unordered collection of related data, of
primitive or reference types, in the form of “key: value” pairs. These keys can be variables or functions and
are called properties and methods, respectively, in the context of an object.
An object can be created with figure brackets {…} with an optional list of properties. A property is a “key:
value” pair, where a key is a string (also called a “property name”), and the value can be anything.
Creating Objects:
In JavaScript, Objects can be created using two different methodologies namely Literal Form and
Constructed Form.

• Literal Form: The literal form uses the construction of object literals that can be said as a collection
of key-value pairs enclosed within a pair of curly braces. The syntaxial form is shown below.
let obj = {
key1: value1,
key2: value2,
...
};

• Constructed Form: The Constructed form uses either an object constructor function or the new
keyword to create an empty object ad then adds properties to the object one by one. The syntaxial
forms are shown below.
o Object Constructor Function: In this methodology, the user creates an explicit function to
take required values as parameters and assign them as the properties of the desired object.
function obj(value1, value2, ...) {
this.key1 = value1;
this.key2 = value2;

25
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
...
}

• Using New Keyword: This methodology uses the New keyword in front of any constructor method
or any built-in constructor method ( such as Object, Date, String, etc) and creates a new instance of
the following object by mounting it on memory.
let obj = new Object();
obj.key1 = value1;
obj.key2 = value2;
...
Differences between using Object Literals and the Constructed Form: Both the constructed form and literal
form result in creating exactly the same sort of object i.e. the end result is the same for both
methodologies. The only difference between the both is that object literals can take care of several key-
value pairs at once and thus is more convenient while on the other hand with the constructed-form
objects, we must add the properties one-by-one in separate statements.

➢ JavaScript Objects – String:


JavaScript String is a sequence of characters, typically used to represent text. It is enclosed in single or
double quotes and supports various methods for text manipulation.

You can create JavaScript Strings by enclosing text in single or double quotes. String literals and the String
constructor provide options. Strings allow dynamic manipulation, making it easy to modify or extract
elements as needed.

Basic Terminologies of JavaScript String


• String: A sequence of characters enclosed in single (‘ ‘) or double (” “) quotes.
• Length: The number of characters in a string, obtained using the length property.
• Index: The position of a character within a string, starting from 0.
• Concatenation: The process of combining two or more strings to create a new one.
• Substring: A portion of a string, obtained by extracting characters between specified indices.

Declaration of a String
1. Using Single Quotes
Single Quotes can be used to create a string in JavaScript. Simply enclose your text within single quotes to
declare a string.
Syntax:
let str = 'String with single quote';

Example:
let str = 'Create String with Single Quote';
console.log(str);

Output
Create String with Single Quote

26
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
2. Using Double Quotes
Double Quotes can also be used to create a string in JavaScript. Simply enclose your text within double
quotes to declare a string.
Syntax:
let str = “String with double quote”;

Example:
let str = "Create String with Double Quote";
console.log(str);

Output
Create String with Double Quote

3. String Constructor
You can create a string using the String Constructor. The String Constructor is less common for direct string
creation, it provides additional methods for manipulating strings. Generally, using string literals is preferred
for simplicity.

Example
let str = new String('Create String with String Constructor');
console.log(str);

Output
[String: 'Create String with String Constructor']

4. Using Template Literals (String Interpolation)


You can create strings using Template Literals. Template literals allow you to embed expressions within
backticks (`) for dynamic string creation, making it more readable and versatile.
Syntax:
let str = 'Template Litral String';
let newStr = `String created using ${str}`;

Example:
let str = 'Template Litral String';
let newStr = `String created using ${str}`;
console.log(newStr);

Output
String created using Template Litral String

5. Empty String
You can create an empty string by assigning either single or double quotes with no characters in between.
Syntax:
// Create Empty Strign with Single Quotes
let str1 = '';
// Create Empty Strign with Double Quotes
let str2 = "";

Example:

27
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
let str1 = '';
let str2 = "";
console.log("Empty String with Single Quotes: " + str1);
console.log("Empty String with Double Quotes: " + str2);

Output
Empty String with Single Quotes:
Empty String with Double Quotes:

6. Multiline Strings (ES6 and later)


You can create a multiline string using backticks (“) with template literals. The backticks allows you to span
the string across multiple lines, preserving the line breaks within the string.
Syntax:
let str = `
This is a
multiline
string`;

Example:
let str = `
This is a
multiline
string`;
console.log(str);

Output
This is a
multiline
string

➢ JavaScript Objects – RegExp:


A regular expression is a sequence of characters that forms a search pattern. The search pattern can be
used for text search and text replace operations. A regular expression is a sequence of characters that
forms a search pattern. When you search for data in a text, you can use this search pattern to describe
what you are searching for. A regular expression can be a single character, or a more complicated pattern.
Regular expressions can be used to perform all types of text search and text replace operations.

Syntax
/pattern/modifiers;
Example
/modelcollege/i;

Example explained:
/modelcoellge/i is a regular expression.
model college is a pattern (to be used in a search). i is a modifier (modifies the search to be case-
insensitive).

Using String Methods


28
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
In JavaScript, regular expressions are often used with the two string methods: search() and replace().

• The search() method uses an expression to search for a match, and returns the position of the
match.
• The replace() method returns a modified string where the pattern is replaced.

➢ Using String search() With a String


The search() method searches a string for a specified value and returns the position of the match:

Example
Use a string to do a search for "Model College" in a string:

let text = "Visit Model College!";


let n = text.search("Model College");

The result in n will be:


6

➢ Using String search() With a Regular Expression

Example
Use a regular expression to do a case-insensitive search for "Model College" in a string:

let text = "Visit Model College";


let n = text.search(/modelcollege/i);

The result in n will be:


6

➢ Using String replace() With a String


The replace() method replaces a specified value with another value in a string:

let text = "Visit Microsoft!";


let result = text.replace("Microsoft", "ModelCollege");

➢ Use String replace() With a Regular Expression

Example
Use a case insensitive regular expression to replace Microsoft with ModelCollege in a string:

let text = "Visit Microsoft!";


let result = text.replace(/microsoft/i, "ModelCollege");

The result in res will be:


Visit ModelCollege!

Regular Expression Modifiers


Modifiers can be used to perform case-insensitive more global searches:

29
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
Modifier Description
i Perform case-insensitive matching
g Perform a global match (find all)
m Perform multiline matching
d Perform start and end matching (New in ES2022)

Regular Expression Patterns


➢ Brackets are used to find a range of characters:

Expression Description
[abc] Find any of the characters between the brackets
[0-9] Find any of the digits between the brackets
(x|y) Find any of the alternatives separated with |

➢ Metacharacters are characters with a special meaning:

Metacharacter Description
\d Find a digit
\s Find a whitespace character
\b Find a match at the beginning of a word like this: \bWORD,
or at the end of a word like this: WORD\b
\uxxxx Find the Unicode character specified by the hexadecimal number xxxx

➢ Quantifiers define quantities:

Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n

Using the RegExp Object


In JavaScript, the RegExp object is a regular expression object with predefined properties and methods.

➢ Using test()
The test() method is a RegExp expression method. It searches a string for a pattern, and returns true or
false, depending on the result. The following example searches a string for the character "e":

Example
const pattern = /e/;
pattern.test("The best things in life are free!");

Since there is an "e" in the string, the output of the code above will be:
true

You don't have to put the regular expression in a variable first. The two lines above can be shortened to
one:

/e/.test("The best things in life are free!");

30
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
➢ Using exec()
The exec() method is a RegExp expression method. It searches a string for a specified pattern, and returns
the found text as an object. If no match is found, it returns an empty (null) object. The following example
searches a string for the character "e":

Example
/e/.exec("The best things in life are free!");

➢ JavaScript Objects – Math:


Javascript Math object is used to perform mathematical operations on numbers. All the properties of Math
are static and unlike other objects, it does not have a constructor. We use Math only on Number data type
and not on BigInt

Math is an inbuilt object that has attributes and methods for mathematical functions and constants. It’s not
a function object.

Math object works with the Number type. The Math object does not have a constructor. All properties and
methods of Math are fixed/static. The cosine function is known as Math.cos(y) while the constant pi is
known as Math.PI, where y is the method’s argument. All the properties and methods of Math are static
and can be called by using Math as an object without creating it.

We will start with the Math properties in Javascript.

Static Math Properties: The Math properties & their descriptions are listed below:

Syntax:
Math.property

31
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3

Example 1: This example uses math object properties to return their values.
console.log("Math.LN10: " + Math.LN10);
console.log("Math.LOG2E: " + Math.LOG2E);
console.log("Math.Log10E: " + Math.LOG10E);
console.log("Math.SQRT2: " + Math.SQRT2);
console.log("Math.SQRT1_2: " + Math.SQRT1_2);
console.log("Math.LN2: " + Math.LN2);
console.log("Math.E: " + Math.E);
console.log("Math.PI: " + Math.PI);

Output
Math.LN10: 2.302585092994046
Math.LOG2E: 1.4426950408889634
Math.Log10E: 0.4342944819032518
Math.SQRT2: 1.4142135623730951
Math.SQRT1_2: 0.7071067811865476
Math.LN2: 0.6931471805599453
Math.E: 2.71828...

Static Math Methods: The methods associated with the Math object are listed below, along with their
descriptions.

Syntax:
Math.method(number)

Method Description
32
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
Math.abs(y) The positive value of y is returned.
Math.ceil(y) Returns the smallest integer greater than or equal to y.
Math.cos(y) Returns the cosine of the angle y.
Math.floor(y) Returns the largest integer less than or equal to y.
Math.max([x[, y[, …]]]) Largest number is returned from x,y.
Math.min([x[, y[, …]]]) The smallest of all the numbers is returned from x,y.
Math.pow(x, y) Returns the exponent power y of the base value x (that is, x^y).
Math.random() An arbitrary number between 0 and 1 is returned.
Math.round(y) The value of y, rounded to the closest integer, is returned.
Math.sin(y) The sine of the angle y is returned.
Math.tan(y) The tangent of y is returned.

Example 2: Math object methods are used in this example.


console.log("Math.abs(-4.7): " + Math.abs(-4.7));
console.log("Math.ceil(4.4): " + Math.ceil(4.4));
console.log("Math.floor(4.7): " + Math.floor(4.7));
console.log("Math.sin(90 * Math.PI / 180): " +
Math.sin(90 * Math.PI / 180));
console.log("Math.min(0, 150, 30, 20, -8, -200): " +
Math.min(0, 150, 30, 20, -8, -200));
console.log("Math.random(): " + Math.random());

Output
Math.abs(-4.7): 4.7
Math.ceil(4.4): 5
Math.floor(4.7): 4
Math.sin(90 * Math.PI / 180): 1
Math.min(0, 150, 30, 20, -8, -200): -200
Math.random(): 0.7416861489868538

Supported Browsers:
Chrome
Edge
Firefox
Opera
Safari

➢ JavaScript Objects – Date:


By default, JavaScript will use the browser's time zone and display a date as a full text string:

Wed Feb 21 2024 20:12:03 GMT+0530 (India Standard Time)

Creating Date Objects


Date objects are created with the new Date() constructor. There are 9 ways to create a new date object:
• new Date()
• new Date(date string)
• new Date(year,month)
• new Date(year,month,day)

33
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
• new Date(year,month,day,hours)
• new Date(year,month,day,hours,minutes)
• new Date(year,month,day,hours,minutes,seconds)
• new Date(year,month,day,hours,minutes,seconds,ms)
• new Date(milliseconds)

➢ JavaScript new Date()


new Date() creates a date object with the current date and time:

Example
const d = new Date();

➢ new Date(date string)


new Date(date string) creates a date object from a date string:

Examples
const d = new Date("October 13, 2014 11:13:00");
const d = new Date("2022-03-25");
Date string formats are described in the next chapter.

➢ new Date(year, month, ...)


new Date(year, month, ...) creates a date object with a specified date and time.

7 numbers specify year, month, day, hour, minute, second, and millisecond (in that order):

Example
const d = new Date(2018, 11, 24, 10, 33, 30, 0);

Note:
JavaScript counts months from 0 to 11:
January = 0.
….
December = 11.

Specifying a month higher than 11, will not result in an error but add the overflow to the next year:

Specifying:

const d = new Date(2018, 15, 24, 10, 33, 30);


Is the same as:

const d = new Date(2019, 3, 24, 10, 33, 30);


Specifying a day higher than max, will not result in an error but add the overflow to the next month:

Specifying:

const d = new Date(2018, 5, 35, 10, 33, 30);


Is the same as:

34
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
const d = new Date(2018, 6, 5, 10, 33, 30);
Using 6, 4, 3, or 2 Numbers

6 numbers specify year, month, day, hour, minute, second:


Example
const d = new Date(2018, 11, 24, 10, 33, 30);

5 numbers specify year, month, day, hour, and minute:


Example
const d = new Date(2018, 11, 24, 10, 33);

4 numbers specify year, month, day, and hour:


Example
const d = new Date(2018, 11, 24, 10);

3 numbers specify year, month, and day:


Example
const d = new Date(2018, 11, 24);

2 numbers specify year and month:


Example
const d = new Date(2018, 11);

You cannot omit month. If you supply only one parameter it will be treated as milliseconds.
Example
const d = new Date(2018);

Previous Century
One and two digit years will be interpreted as 19xx:
Example
const d = new Date(99, 11, 24);

Example
const d = new Date(9, 11, 24);

➢ JavaScript Stores Dates as Milliseconds


JavaScript stores dates as number of milliseconds since January 01, 1970.

Zero time is January 01, 1970 00:00:00 UTC.

One day (24 hours) is 86 400 000 milliseconds.

Now the time is: 1708526523291 milliseconds past January 01, 1970

➢ new Date(milliseconds)
new Date(milliseconds) creates a new date object as milliseconds plus zero time:

Examples
01 January 1970 plus 100 000 000 000 milliseconds is:

35
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
const d = new Date(100000000000);

January 01 1970 minus 100 000 000 000 milliseconds is:


const d = new Date(-100000000000);

January 01 1970 plus 24 hours is:


const d = new Date(24 * 60 * 60 * 1000);
// or
const d = new Date(86400000);

01 January 1970 plus 0 milliseconds is:


const d = new Date(0);

Date Methods
When a date object is created, a number of methods allow you to operate on it.

Date methods allow you to get and set the year, month, day, hour, minute, second, and millisecond of date
objects, using either local time or UTC (universal, or GMT) time.

➢ Displaying Dates
JavaScript will (by default) output dates using the toString() method. This is a string representation of the
date, including the time zone. The format is specified in the ECMAScript specification:

Example
Wed Feb 21 2024 20:12:03 GMT+0530 (India Standard Time)
When you display a date object in HTML, it is automatically converted to a string, with the toString()
method.

Example
const d = new Date();
d.toString();
The toDateString() method converts a date to a more readable format:

Example
const d = new Date();
d.toDateString();
The toUTCString() method converts a date to a string using the UTC standard:

Example
const d = new Date();
d.toUTCString();
The toISOString() method converts a date to a string using the ISO standard:

Example
const d = new Date();
d.toISOString();

36

You might also like