Kakinada Institute of Engineering &
Technology
Department of CSE with Cyber Security Engineering
WEB SERVICES
Lab Manual
Department of Cyber Security
Perform experiments related to the following
concepts:
1) Introduction to JavaScript:
JavaScript is a high-level, interpreted programming language
primarily used for creating interactive web pages and web
applications. It was originally developed by Brendan Eich at
Netscape Communications in 1995 and has since become one
of the most popular programming languages on the web.
JavaScript is primarily known as a client-side scripting
language, which means it runs on the user's web browser
rather than on the web server. This allows JavaScript to
dynamically manipulate the content and behavior of web pages
in response to user interactions.
Over time, JavaScript has evolved to also be used on the
server-side, thanks to the introduction of frameworks like
Node.js. This expansion allows developers to build full-stack
web applications using a single programming language.
Key features of JavaScript include:
1. Syntax: JavaScript has a syntax similar to other C-style
languages such as C++, Java, and C#. It uses curly braces
for code blocks and has support for variables, loops,
conditionals, and functions.
2. Dynamic typing: JavaScript is a dynamically typed
language, meaning you don't have to explicitly declare the
data type of a variable. Variables can hold values of different
types throughout the execution of a program.
Department of Cyber Security
3. Prototypal inheritance: JavaScript follows a prototypal
object-oriented programming paradigm. Instead of using
classes to create objects, JavaScript uses prototypes. Objects
can inherit properties and methods from other objects, allowing
for flexible and powerful object-oriented programming.
4. Functions as first-class citizens: In JavaScript, functions
are treated as first-class citizens, meaning they can be
assigned to variables, passed as arguments to other functions,
and returned as values from functions. This functional
programming aspect allows for more flexible and modular
code.
5. DOM manipulation: JavaScript has extensive support for
manipulating the Document Object Model (DOM), which
represents the structure of an HTML document. It allows you
to dynamically modify the content, structure, and styling of
web pages, enabling interactive user experiences.
JavaScript has a vast ecosystem of libraries and frameworks
that further enhance its capabilities, such as React, Angular,
and Vue.js for building user interfaces, and Express.js for
building server-side applications.
Overall, JavaScript is a versatile and powerful programming
language that plays a crucial role in modern web development,
enabling developers to create dynamic and interactive web
applications.
Department of Cyber Security
2)Applying JavaScript (internal and external)
JavaScript can be applied to web pages in two main ways:
internally (inline) and externally. Let's explore both methods:
Internal JavaScript:
Internal JavaScript refers to including JavaScript code directly
within an HTML document. This is typically done within the
<script> tags placed in the <head> or <body> section of an
HTML file. Here's an example:
CODE:-
<!DOCTYPE html>
<html>
<head>
<title>Internal JavaScript Example</title>
<script>
// Inline JavaScript code
function greet() {
alert('Hello, world!');
}
</script>
</head>
<body>
<h1>Welcome to my webpage</h1>
<button onclick="greet()">Click me</button>
</body>
</html>
Department of Cyber Security
In the above example, the JavaScript code is placed directly
within the <script> tags in the <head> section. The greet()
function is defined inline and can be called when the user
clicks the button using the onclick attribute.
External JavaScript:
External JavaScript involves creating a separate JavaScript
file and linking it to an HTML document using the <script>
tag's src attribute. This method allows for better separation of
concerns and reusability of code. Here's an example:
index.html:
CODE:-
<!DOCTYPE html>
<html>
<head>
<title>External JavaScript Example</title>
<script src="script.js"></script>
</head>
<body>
<h1>Welcome to my webpage</h1>
<button onclick="greet()">Click me</button>
</body>
</html>
script.js
CODE:-
// External JavaScript code in script.js
function greet()
{
Department of Cyber Security
alert('Hello, world!');
}
In this case, the JavaScript code is placed in an external file
called script.js. The <script> tag in the HTML file references
this external file using the src attribute, which points to the
location of the JavaScript file.
By using external JavaScript files, you can reuse the same
code across multiple web pages and keep your HTML files
clean and focused on structure and content.
Both internal and external JavaScript can be used to perform
various tasks, such as manipulating the DOM, handling user
interactions, making HTTP requests, validating forms, and
much more. JavaScript's versatility allows you to enhance the
functionality and interactivity of your web pages and
applications.
Department of Cyber Security
3)Understanding JS Syntax
JavaScript syntax is the set of rules, how JavaScript programs
are constructed:
// How to create variables:
var x;
let y;
// How to use variables:
x = 5;
y = 6;
let z = x + y;
JavaScript Values
The JavaScript syntax defines two types of values:
• Fixed values
• Variable values
Fixed values are called Literals.
Variable values are called Variables.
JavaScript Literals
The two most important syntax rules for fixed values are:
1. Numbers are written with or without decimals:
10.50
1001
2. Strings are text, written within double or single quotes:
Department of Cyber Security
"John Doe"
'John Doe'
JavaScript Variables
In a programming language, variables are used to store data
values.
JavaScript uses the
keywords var, let and const to declare variables.
An equal sign is used to assign values to variables.
In this example, x is defined as a variable. Then, x is assigned
(given) the value 6:
let x;
x = 6;
JavaScript Operators
JavaScript uses arithmetic operators ( + - * / )
to compute values:
(5 + 6) * 10
JavaScript uses an assignment operator ( = ) to assign values
to variables:
let x, y;
x = 5;
y = 6;
JavaScript Expressions
Department of Cyber Security
An expression is a combination of values, variables, and
operators, which computes to a value.
The computation is called an evaluation.
For example, 5 * 10 evaluates to 50:
5 * 10
Expressions can also contain variable values:
x * 10
The values can be of various types, such as numbers and
strings.
For example, "John" + " " + "Doe", evaluates to "John Doe":
"John" + " " + "Doe"
JavaScript Keywords
JavaScript keywords are used to identify actions to be performed.
The let keyword tells the browser to create variables:
let x, y;
x = 5 + 6;
y = x * 10;
The var keyword also tells the browser to create variables:
var x, y;
x = 5 + 6;
y = x * 10;
Department of Cyber Security
JavaScript Comments
Not all JavaScript statements are "executed".
Code after double slashes // or between /* and */ is treated as
a comment.
Comments are ignored, and will not be executed:
let x = 5; // I will be executed
// x = 6; I will NOT be executed
JavaScript Identifiers / Names
Identifiers are JavaScript names.
Identifiers are used to name variables and keywords, and
functions.
The rules for legal names are the same in most programming
languages.
A JavaScript name must begin with:
• A letter (A-Z or a-z)
• A dollar sign ($)
• Or an underscore (_)
Subsequent characters may be letters, digits, underscores, or
dollar signs.
Note
Department of Cyber Security
Numbers are not allowed as the first character in names.
This way JavaScript can easily distinguish identifiers from
numbers.
JavaScript is Case Sensitive
All JavaScript identifiers are case sensitive.
The variables lastName and lastname, are two different variables:
let lastname, lastName;
lastName = "Doe";
lastname = "Peterson";
JavaScript does not interpret LET or Let as the keyword let.
JavaScript and Camel Case
Historically, programmers have used different ways of joining
multiple words into one variable name:
Hyphens:
first-name, last-name, master-card, inter-city.
Underscore:
first_name, last_name, master_card, inter_city.
Upper Camel Case (Pascal Case):
FirstName, LastName, MasterCard, InterCity.
Lower Camel Case:
Department of Cyber Security
JavaScript programmers tend to use camel case that starts with a
lowercase letter:
firstName, lastName, masterCard, interCity.
JavaScript Character Set
JavaScript uses the Unicode character set.
Unicode covers (almost) all the characters, punctuations, and
symbols in the world.
Department of Cyber Security
4)Introduction to Document and Window Object
In web development, the Document and Window objects are
fundamental components of the Document Object Model (DOM),
representing the web page and the browser window, respectively.
They provide access to various properties, methods, and events
that allow manipulation and interaction with the web page content
and the browser environment.
Document Object:
The Document object represents the web page loaded in the
browser and provides access to its content and structure.
It serves as an entry point to interact with HTML elements, modify
their attributes and styles, manipulate the document structure, and
handle events.
Some commonly used properties and methods of the Document
object include:
document.getElementById(): Retrieves an HTML element with the
specified ID.
document.querySelector(): Returns the first element that matches a
CSS selector.
document.createElement(): Creates a new HTML element.
document.getElementById().innerHTML: Gets or sets the HTML
content of an element.
document.title: Gets or sets the title of the document.
Department of Cyber Security
document.addEventListener(): Registers an event listener for a
specific event type.
Window Object:
The Window object represents the browser window or tab that
contains the web page.
It provides access to the browser's properties, methods, and events,
enabling control over the window's behavior and interaction with
other windows.
Some commonly used properties and methods of the Window object
include:
window.alert(): Displays an alert dialog box with a message.
window.open(): Opens a new browser window or tab.
window.location: Provides information about the current URL and
allows navigation to new URLs.
window.innerWidth and window.innerHeight: Returns the width and
height of the window's content area.
window.addEventListener(): Registers an event listener for a specific
event type.
window.setTimeout(): Sets a timer to execute a function after a
specified delay.
The Document and Window objects are closely related, with the
Window object being the global object that holds the Document
object and provides a broader scope for accessing browser-related
features. Through these objects, web developers can manipulate
Department of Cyber Security
the web page's structure, modify its content dynamically, handle
user interactions, and perform various operations within the browser
environment.
It's important to note that the examples provided above are just a
subset of the available properties, methods, and events offered by
the Document and Window objects. The DOM API provides a rich
set of functionality for web development, allowing developers to
create dynamic and interactive web applications.
Department of Cyber Security
5)Variables and Operators
In JavaScript, variables are used to store and manipulate data,
while operators are used to perform operations on that data. Here's
an overview of variables and operators in JavaScript:
Variables:
Variables are declared using the var, let, or const keywords.
The var keyword is used to declare variables with function scope.
The let keyword is used to declare variables with block scope
(introduced in ES6).
The const keyword is used to declare variables with block scope
that cannot be reassigned after initialization.
Example variable declarations:
var name = "John";
let age = 25;
const PI = 3.14159;
Operators:
JavaScript provides various types of operators to perform different
operations on variables and values.
Arithmetic operators:
+ Addition
- Subtraction
* Multiplication
Department of Cyber Security
/ Division
% Modulo (remainder)
++ Increment
-- Decrement
Assignment operators:
= Assigns a value to a variable
+= Adds and assigns a value
-=, *=, /=, %= perform the respective operation and assign the
result
Comparison operators:
== Equality (loose equality)
=== Strict equality (checks value and type)
!= Inequality (loose inequality)
!== Strict inequality
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
Logical operators:
&& Logical AND
|| Logical OR
Department of Cyber Security
! Logical NOT
Other operators:
. Dot operator: Access object properties or methods.
[] Bracket notation: Access object properties dynamically.
typeof Returns the type of a value.
instanceof Checks if an object is an instance of a particular class.
? : Ternary operator: Short form of an if-else statement.
, Comma operator: Evaluates multiple expressions and returns the
result of the last one.
These are just some of the commonly used variables and operators
in JavaScript. JavaScript provides a rich set of operators to perform
mathematical computations, assign values, compare values, and
perform logical operations. Understanding variables and operators
is essential for manipulating and transforming data in JavaScript.
Department of Cyber Security
6)Data Types and Num Type Conversion
JavaScript has several built-in data types that represent different
kinds of values. Here are the commonly used data types in
JavaScript:
Primitive Data Types:
Number: Represents numeric values, including integers and floating-
point numbers.
String: Represents a sequence of characters enclosed in single or
double quotes.
Boolean: Represents a logical value, either true or false.
null: Represents the intentional absence of any object value.
undefined: Represents an uninitialized variable or missing property
value.
Symbol (introduced in ES6): Represents a unique identifier.
Object Data Type:
Object: Represents a collection of key-value pairs or properties.
Objects can be created using object literals {}, the new keyword,
or built-in constructors like Array, Date, etc.
Special Data Type:
BigInt (introduced in ES2020): Represents integers with arbitrary
precision.
Type Conversion:
Department of Cyber Security
JavaScript provides automatic and explicit type conversion (also
known as type casting) to convert values between different data
types. Here are some ways to perform type conversion:
Implicit Type Conversion (Coercion):
JavaScript automatically converts values of one type to another
during operations or comparisons.
Examples:
var num = 5 + "2"; // "52" (string concatenation)
var result = 10 * "5"; // 50 (numeric multiplication)
Explicit Type Conversion:
You can explicitly convert values between different data types using
built-in functions or operators.
Examples:-
CODE:-
var str = String(123); // "123" (converts to a string)
var num = Number("3.14"); // 3.14 (converts to a number)
var bool = Boolean(0); // false (converts to a boolean)
var x = 10;
var strX = x.toString(); // "10" (converts to a string using the
toString() method)
Parsing Functions:
Department of Cyber Security
JavaScript provides parsing functions to convert strings to specific
data types.
Examples:
CODE:-
var num = parseInt("10"); // 10 (parses a string to an integer)
var floatNum = parseFloat("3.14"); // 3.14 (parses a string to a
floating-point number)
It's important to note that type conversion can have unexpected
results or introduce potential errors. Understanding and controlling
type conversion is crucial to ensure proper data handling and
consistent behavior in your JavaScript code.
Remember to use appropriate type conversion techniques based
on the specific requirements of your code and validate user inputs
to avoid unexpected behavior or security vulnerabilities.
Department of Cyber Security
7)Math and String Manipulation
JavaScript provides built-in functions and methods for performing
mathematical calculations and manipulating strings. Here's an
overview of math operations and string manipulation in JavaScript:
Math Operations:
Basic Math:
Addition: var sum = 2 + 3;
Subtraction: var difference = 5 - 2;
Multiplication: var product = 4 * 2;
Division: var quotient = 10 / 2;
Modulo (Remainder): var remainder = 10 % 3;
Increment: var count = 5; count++;
Decrement: var count = 5; count--;
Math Object:
JavaScript's Math object provides a range of built-in math-related
functions and constants.
Example functions:
Math.sqrt(x): Returns the square root of x.
Math.pow(base, exponent): Returns base raised to the power of
exponent.
Math.random(): Returns a random number between 0 (inclusive)
and 1 (exclusive).
Department of Cyber Security
Math.floor(x): Returns the largest integer less than or equal to x.
Math.ceil(x): Returns the smallest integer greater than or equal to
x.
Math.round(x): Returns the rounded integer closest to x.
String Manipulation:
Concatenation:
Combine two or more strings using the concatenation operator (+).
Example: var fullName = firstName + " " + lastName;
String Length:
Access the length of a string using the length property.
Example: var message = "Hello, World!"; var length =
message.length;
Accessing Characters:
Access individual characters in a string using square brackets ([])
and the character's index.
Example: var message = "Hello"; var firstChar = message[0];
String Methods:
JavaScript provides various built-in methods to manipulate strings.
Example methods:
str.toUpperCase(): Converts the string to uppercase.
str.toLowerCase(): Converts the string to lowercase.
Department of Cyber Security
str.trim(): Removes leading and trailing whitespace from the string.
str.split(separator): Splits the string into an array of substrings based
on the separator.
str.indexOf(substring): Returns the index of the first occurrence of
the substring in the string.
str.substring(startIndex, endIndex): Returns a new string that is a
subset of the original string.
str.replace(oldValue, newValue): Replaces occurrences of oldValue
with newValue.
These are just a few examples of math operations and string
manipulation techniques in JavaScript. JavaScript provides a wide
range of built-in functions and methods for handling numbers and
strings. Exploring the JavaScript documentation or references will
provide more details on specific functions and their usage.
Department of Cyber Security
8)Objects and Arrays
In JavaScript, objects and arrays are powerful data structures used
to store and manipulate collections of values. They have different
characteristics and are suited for different purposes:
Objects:
Objects are collections of key-value pairs, where the keys are
strings (or symbols) that act as identifiers for accessing the
corresponding values.
They are versatile and can store different types of values, including
primitive data types, other objects, and functions.
Objects are created using object literals {}, the new keyword, or
constructors like Object().
Example:
CODE:-
var person = {
name: "John",
age: 25,
address: {
street: "123 Main St",
city: "New York"
},
sayHello: function() {
Department of Cyber Security
console.log("Hello, " + this.name + "!");
};
Accessing object properties:
code:-
console.log(person.name); // "John"
console.log(person.address.city); // "New York"
person.sayHello(); // "Hello, John!"
Arrays:
Arrays are ordered collections of values, accessed by numeric
indices starting from 0.
They are useful for storing and manipulating lists or sequences of
values.
Arrays can contain any type of values, including primitive types,
objects, or even other arrays.
Arrays are created using array literals [] or the new keyword.
Example:
var fruits = ["apple", "banana", "orange"];
var numbers = new Array(1, 2, 3, 4, 5);
Accessing array elements:
console.log(fruits[0]); // "apple"
Department of Cyber Security
console.log(numbers[2]); // 3
Modifying array elements:
fruits[1] = "grape";
numbers.push(6);
Both objects and arrays are mutable and can be modified by
adding, updating, or removing elements. They offer various built-in
methods for manipulating and iterating over their elements, such
as push(), pop(), splice(), forEach(), and more.
It's important to note that objects and arrays can be nested within
each other to create complex data structures. They are widely used
in JavaScript for organizing and managing data in a structured way,
enabling developers to create dynamic and flexible applications.
Department of Cyber Security
9)Date and Time
In JavaScript, the Date object is used to work with dates and times.
It provides functionality to create, manipulate, and format dates and
times. Here's an overview of working with dates and times in
JavaScript:
Creating a Date object:
You can create a Date object using one of the following methods:
Without any arguments:
var currentDate = new Date();
With a specific date and time:
With individual date and time components:
var componentsDate = new Date(2023, 5, 22, 9, 30, 0);
Accessing Date and Time Components:
You can retrieve various components (year, month, day, hour,
minute, second, etc.) from a Date object using the following
methods:
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth(); // Month is zero-based (0-11)
var day = date.getDate();
var hour = date.getHours();
var minute = date.getMinutes();
Department of Cyber Security
var second = date.getSeconds();
var milliseconds = date.getMilliseconds();
Formatting Dates and Times:
JavaScript provides methods to format dates and times into strings:
var date = new Date();
var dateString = date.toDateString(); // "Wed Jun 22 2023"
var timeString = date.toTimeString(); // "09:30:00 GMT+0300
(Eastern European Summer Time)"
var dateTimeString = date.toLocaleString(); // "6/22/2023, 9:30:00
AM"
Working with Date and Time Operations:
JavaScript's Date object provides methods to perform various
operations on dates and times:
var date = new Date();
date.setFullYear(2024); // Change the year
date.setMonth(3); // Change the month (0-11)
date.setDate(15); // Change the day
date.setHours(12); // Change the hour
date.setMinutes(30); // Change the minute
date.setSeconds(0); // Change the second
var futureDate = new Date();
Department of Cyber Security
futureDate.setDate(futureDate.getDate() + 7); // Add 7 days
var timeDiff = futureDate - date; // Calculate the time
difference in milliseconds
Working with UTC:
JavaScript provides both UTC-based methods and local time-based
methods for working with dates and times. UTC methods use
Coordinated Universal Time (UTC) as the reference point:
var utcDate = new Date();
var utcYear = utcDate.getUTCFullYear();
var utcMonth = utcDate.getUTCMonth();
var utcDay = utcDate.getUTCDate();
// and so on...
By using UTC-based methods, you can perform date and time
operations without considering local time zones.
The Date object in JavaScript offers extensive functionality for
working with dates and times. Understanding its methods and
properties allows you to perform operations such as creating,
manipulating, formatting, and comparing dates and times in your
JavaScript applications.
Department of Cyber Security
10)Conditional Statements
Conditional statements in JavaScript allow you to control the
flow of your code based on different conditions. They help
you execute specific blocks of code when certain conditions
are met. Here are the main conditional statements in
JavaScript:
if statement:
The if statement is used to execute a block of code if a
specified condition is true.
if (condition)
{
// code to be executed if the condition is true
}
if-else statement:
The if-else statement allows you to execute different blocks
of code depending on whether a condition is true or false.
if (condition)
{
// code to be executed if the condition is true
}
else
{
// code to be executed if the condition is false
}
if-else if-else statement:
Department of Cyber Security
The if-else if-else statement allows you to test multiple
conditions and execute different blocks of code accordingly.
if (condition1)
{
// code to be executed if condition1 is true
}
else if (condition2)
{
// code to be executed if condition2 is true
}
else
{
// code to be executed if none of the conditions are true
}
switch statement:
The switch statement evaluates an expression and executes
different blocks of code based on different cases.
switch (expression)
{
case value1:
// code to be executed if expression matches value1
break;
case value2:
// code to be executed if expression matches value2
break;
default:
Department of Cyber Security
// code to be executed if expression doesn't match any
case
}
The condition in conditional statements can be any expression
that evaluates to a boolean value (true or false). This can
include comparisons (>, <, ==, !=, etc.), logical operators (&&,
||, !), or any other valid boolean expression.
It's important to note that the code block executed within a
conditional statement is defined by using curly braces {}. If
the block contains only a single statement, the curly braces
can be omitted, although it's generally considered good
practice to always include them.
Conditional statements are essential for making decisions and
controlling the flow of your program based on different
conditions. They enable you to create dynamic and flexible
code that responds to various scenarios.
Department of Cyber Security
11)Switch Case
The switch statement in JavaScript provides a way to execute
different blocks of code based on the value of an expression. It is
often used as an alternative to multiple if-else if-else statements
when there are many possible conditions to check against. Here's
the syntax of the switch statement:
switch (expression)
case value1:
// code to be executed if expression matches value1
break;
case value2:
// code to be executed if expression matches value2
break;
case value3:
// code to be executed if expression matches value3
break;
// add more cases as needed
default:
// code to be executed if expression doesn't match any case
Here's how the switch statement works:
Department of Cyber Security
The expression is evaluated once.
The value of the expression is compared to the values in the case
clauses.
If a match is found, the corresponding block of code is executed.
The break statement is used to exit the switch statement and
prevent fall-through to the next case. If break is not used, execution
will continue to the next case until a break statement is encountered
or until the end of the switch statement.
If no match is found, the code block associated with the default
case (optional) is executed. It serves as a fallback when none of
the cases match the expression.
Here's an example to illustrate the usage of switch statement:
code:-
var day = new Date().getDay();
var dayName;
switch (day) {
case 0:
dayName = "Sunday";
break;
case 1:
dayName = "Monday";
break;
Department of Cyber Security
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
default:
dayName = "Unknown";
console.log("Today is " + dayName);
In this example, the switch statement is used to determine the day
of the week based on the value of day. The corresponding case
Department of Cyber Security
block is executed depending on the value, and the dayName
variable is assigned accordingly. If day doesn't match any of the
cases, the default case is executed, and dayName is set to
"Unknown".
The switch statement provides a concise way to handle multiple
possible cases based on the value of an expression. It improves
code readability and can be more efficient than multiple if-else if-
else statements when dealing with a large number of conditions.
Department of Cyber Security
12)Looping in JS
Looping in JavaScript allows you to repeat a block of code multiple
times. JavaScript provides several loop structures to cater to
different looping scenarios. Here are the main types of loops in
JavaScript:
for loop:
The for loop is used when you know the number of iterations in
advance.
for (initialization; condition; increment/decrement)
// code to be executed in each iteration
code:-
for (var i = 0; i < 5; i++)
console.log(i);
while loop:
The while loop is used when you want to repeat a block of code
as long as a specified condition is true.
while (condition)
Department of Cyber Security
// code to be executed as long as the condition is true
code:-
var i = 0;
while (i < 5)
console.log(i);
i++;
do-while loop:
The do-while loop is similar to the while loop, but it executes the
code block at least once before checking the condition.
do
// code to be executed
while (condition);
code:-
var i = 0;
do
Department of Cyber Security
console.log(i);
i++;
while (i < 5);
for...in loop:
The for...in loop is used to iterate over the properties of an object.
for (variable in object)
// code to be executed for each property
code:-
var person =
name: "John",
age: 25,
city: "New York"
};
for (var key in person)
console.log(key + ": " + person[key]);
}
Department of Cyber Security
for...of loop:
The for...of loop is used to iterate over iterable objects like arrays,
strings, and other collections
for (variable of iterable)
// code to be executed for each iteration
code:-
var fruits = ["apple", "banana", "orange"];
for (var fruit of fruits)
console.log(fruit);
Loop control statements:
JavaScript provides loop control statements to control the flow of
loops:
break: Terminates the loop and moves the control to the next
statement after the loop.
continue: Skips the rest of the current iteration and moves to the
next iteration.
code:-
Department of Cyber Security
for (var i = 0; i < 5; i++)
if (i === 2)
continue; // Skip iteration when i is 2
if (i === 4)
break; // Terminate the loop when i is 4
console.log(i);
Loops are fundamental for repetitive tasks and iterating over
collections of data in JavaScript. They offer great flexibility and
control in implementing complex logic and data processing within
your programs.
Department of Cyber Security
13)Functions
Functions in JavaScript are reusable blocks of code that can be
invoked to perform a specific task. They allow you to organize your
code, improve code reusability, and make it more modular. Here's
an overview of working with functions in JavaScript:
Defining a Function:
You can define a function using the function keyword, followed by
the function name, a set of parentheses for parameters (optional),
and curly braces {} to enclose the function body.
function functionName(parameter1, parameter2)
// code to be executed
code:-
function greet(name)
console.log("Hello, " + name + "!");
Invoking a Function:
To execute the code inside a function, you need to invoke or call
the function by its name, followed by a set of parentheses. If the
Department of Cyber Security
function has parameters, you pass the values inside the
parentheses.
functionName(argument1, argument2);
code:-
greet("John");
Return Statement:
Functions can return a value using the return statement. The
returned value can be assigned to a variable or used in
expressions.
function functionName()
// code to be executed
return value;
code:-
function multiply(a, b)
return a * b;
var result = multiply(5, 3);
console.log(result); // Output: 15
Department of Cyber Security
Function Parameters:
You can define parameters in a function declaration to receive
values from the function caller. These parameters act as local
variables inside the function.
function functionName(parameter1, parameter2)
// code that uses the parameters
code:-
function add(a, b)
var sum = a + b;
console.log(sum);
add(2, 3); // Output: 5
Default Parameters:
You can assign default values to function parameters. If no
argument is passed for a parameter, the default value is used.
function functionName(parameter1 = defaultValue1, parameter2 =
defaultValue2)
// code that uses the parameters
Department of Cyber Security
}
code:-
function greet(name = "Guest")
console.log("Hello, " + name + "!");
greet(); // Output: Hello, Guest!
greet("John"); // Output: Hello, John!
Arrow Functions:
Arrow functions are a concise syntax for defining functions in
JavaScript.
const functionName = (parameter1, parameter2) => {
// code to be executed
};
code:-
const multiply = (a, b) => a * b;
console.log(multiply(5, 3)); // Output: 15
Functions are a fundamental building block in JavaScript, allowing
you to encapsulate reusable code and perform specific tasks. They
offer flexibility, code organization, and reusability, making your code
more modular and maintainable.
Department of Cyber Security