KEMBAR78
JS Control Statements and Functions.pptx
JavaScript Control statements
Control statements in JavaScript are used to alter the normal flow of execution of a program.
They allow you to make decisions, repeat code blocks, and jump to different parts of your code.
They are TWO Types
Conditional Statements: Based on an expression passed, a conditional statement makes a decision, which
results in either YES or NO(True or False).
Iterative Statements (Loop): These statements continue to repeat until the expression or condition is
satisfied.
 Conditional Statements
 Conditional statements in a program decide the next step based on the result.
 They result in either True or False.
 The program moves to the next step if a condition is passed and true.
 However, if the condition is false, the program moves to another step. These statements are
executed only once, unlike loop statements.
If,else and else if
IF
 When you want to check for a specific condition with the IF condition, the inner code block
executes if the provided condition is satisfied.
if (condition)
{
 //code block to be executed if condition is satisfied
}
Example:
let age = 18;
if (age >= 18)
{
console.log("You are an adult.");
}
if-else Statement:
The If-Else Statement is an extended version of the If statement. We use this one when we want to
check a condition we want and another one if the evaluation turns out otherwise.
if (condition)
{
// code to be executed if the condition is true
}
Else
{ // code to be executed if the condition is false
}
let age = 18;
if (age >= 18)
{
console.log("You are an adult.");
}
else
{
console.log("You are Child.");
}###################
let isRaining = false;
if (isRaining)
{
console.log("Take an umbrella.");
}
Else
{
console.log("Enjoy the sunshine!");
}
else if statement
Adds more conditions to the if statement, allowing for multiple alternative conditions to be tested.
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition1 is false and condition2 is true
} else if (condition3) {
// code to be executed if condition1 and condition2 are false and condition3 is true
} else {
// code to be executed if none of the conditions are true
}
Example:
let grade = 85;
if (grade >= 90) {
console.log(“MCA Student!");
} else if (grade >= 80) {
console.log(“MBA Students!");
} else if (grade >= 70) {
console.log(“Degree Student");
} else {
console.log(“Student");
}
 Looping Statements:
Different Kinds of Loops
JavaScript supports different kinds of loops:
for - loops through a block of code a number of times
for/in - loops through the properties of an object
for/of - loops through the values of an iterable object
while - loops through a block of code while a specified condition is true
do/while - also loops through a block of code while a specified condition is true
 The For Loop
 The for statement creates a loop with 3 optional expressions:
 for (expression 1; expression 2; expression 3) {
 // code block to be executed
 }
 Expression 1 is executed (one time) before the execution of the code block.
 Expression 2 defines the condition for executing the code block.
 Expression 3 is executed (every time) after the code block has been executed.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For Loop</h2>
<p id="demo"></p>
<script>
let text = "";
for (let i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
for (let i = 0; i < 5; i++) { console.log(i); }
FOR IN
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For In Loop</h2>
<p>The for in statement loops through the properties of an object:</p>
<p id="demo"></p>
<script>
const person = {fname:“RK", lname:“Reddy", age:31};
let txt = "";
for (let x in person) {
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>
</body>
</html>
The for in loop iterates over a person object
Each iteration returns a key (x)
The key is used to access the value of the key
The value of the key is person[x]
The For Of Loop
The JavaScript for of statement loops through the values of an iterable object.
It lets you loop over iterable data structures such as Arrays, Strings, Maps, NodeLists, and more:
 for (variable of iterable) {
// code block to be executed
}
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For Of Loop</h2>
<p>The for of statement loops through the values of an iterable object.</p>
<p id="demo"></p>
<script>
let language = "JavaScript";
let text = "";
for (let x of language) {
text += x + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
While Loop
Loops can execute a block of code as long as a specified condition is true.
The while loop loops through a block of code as long as a specified condition is true.
Syntax:
while (condition) {
// code block to be executed
}
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript While Loop</h2>
<p id="demo"></p>
<script>
let text = "";
let i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
The Do While Loop
The do while loop is a variant of the while loop. This loop will execute the code block once, before
checking if the condition is true, then it will repeat the loop as long as the condition is true.
Syntax
do {
// code block to be executed
}
while (condition);
Example
The example below uses a do while loop. The loop will always be executed at least once, even if
the condition is false, because the code block is executed before the condition is tested:
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Do While Loop</h2>
<p id="demo"></p>
<script>
let text = ""
let i = 0;
do {
text += "<br>The number is " + i;
i++;
}
while (i < 10);
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
Jump Statements
break Statement: Exits the current loop or switch statement.
continue Statement: Skips the current iteration of the loop and moves to the next.
By understanding and effectively using these control statements, you can create more complex and
dynamic JavaScript programs.
The break statement "jumps out" of a loop.
The continue statement "jumps over" one iteration in the loop.
It was used to "jump out" of a switch() statement.
The break statement can also be used to jump out of a loop:
switch (expression) {
case value1:
// code block 1;
break;
case value2:
// code block 2;
break;
...
default:
// default code block;
}
let day = 3;
let dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
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;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}
console.log(dayName);
let grade = 'B';
let result;
switch (grade) {
case 'A':
result = "A (Excellent)";
break;
case 'B':
result = "B (Average)";
break;
case 'C':
result = "C (Below than average)";
break;
default:
result = "No Grade";
}
console.log(result);
JavaScript Continue Statement
 The continue statement in Javascript is used to break the iteration of the loop and follow with
the next iteration. The break in the iteration is possible only when the specified condition going
to occur.
 The major difference between the continue and break statement is that the break statement
breaks out of the loop completely while continue is used to break one statement and iterate to
the next statement.
 How does the continue statement work for different loops?
 In a For loop, iteration goes to an updated expression which means the increment expression is
first updated.
 In a While loop, it again executes the condition.
 Syntax:
Continue;
for (let i = 0; i < 11; i++)
{
if (i % 2 == 0)
continue;
console.log(i);
}
//
let i = 0;
while (i < 11)
{
i++;
if (i % 2 == 0)
continue;
console.log(i);
}
JavaScript Programming Modules
JavaScript Modules enables you to divide your code into multiple files which makes it easier to maintain a
code-base.
Modules are imported using the import statement from the external files.
Exporting a Module
There are two types of exports:
Named Exports
Named exports allow you to export multiple values from a module by their names, enabling selective imports.
Default Exports
Default exports allow you to export a single value or entity from a module. This can be imported without using
curly braces.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Modules</h1>
<p id="demo"></p>
<script type="module">
import message from "./message.js";
document.getElementById("demo").innerHTML = message();
</script>
</body>
</html>
Named Exports
Let us create a file named person.js, and fill it with the things we want to export.
You can create named exports two ways. In-line individually, or all at once at the bottom.
person.js
export const name = “RK";
export const age = 31;
 const name = ”RK";
const age = 31;
export {name, age};
 Import
You can import modules into a file in two ways, based on if they are named exports or default exports.
Named exports are constructed using curly braces. Default exports are not.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Modules</h1>
<p id="demo"></p>
<script type="module">
import { name, age } from "./person.js";
let text = "My name is " + name + ", I am " + age + ".";
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Example(INDEX.HTML)
<html>
<head>
<meta charset=“UTF-8”>
<title>….</title>
</head>
<body>
<h1>JS Modules are</h1>
<script src=“func.js” type=“module”></script>
</body>
</html>
Index.js
export function add(a,b)
{
return a+b;
}/*export function subtract(a,b)
{
Return a-b;
}*/
FUNC.js
import {add} from ‘./index.js’//{add,subtract}
console.log(add(4,5));
 Func.js
 Import * as calculate from ‘./index.js’
 Console.log(calculate.add());
 Console.log(calculate.subtract());
 index.js
 Export default function add(a,b)
 {
 Return a+b;
 }
 Fun
 Import add from .
JavaScript Recursion
Recursion is a programming technique where a function calls itself repeatedly to solve a problem
Every time you write a recursive function, three elements must be present. They are:
The function definition.
The base condition.
The recursive call.
In the function, it makes a call to itself until the base condition is met and it stops executing.
The second recursion function that occurs outside of the function code takes arguments and only
calls the recursive function once.
 Base Condition
 The base case is the most critical component of each recursive function. When the problem is
divided into smaller jobs, it is the smallest component of the problem to be solved. It can also
be seen as the command that, if the set condition is true, it can end the recursion process.
function recursion() { // The Function Declaration
if (true) { // here is the base case command
return;
}
// Function and recursive step codes
}
 The Recursive Call
 The Recursive Call command in recursion is only responsible for triggering a new recursive call.
The Recursive Call command is the actual command that addresses the main problem that you
want to solve.
function recursion() { // The Function Declaration
if (true) { // The base case
return;
}
// Function code
// and recursive step codes
return ... ;
}
//Here is The Recursive Call command
recursion()
function factorial(n) {
// Base case: if n is 0 or 1, return 1
if (n === 0 || n === 1) {
return 1;
} else {
// Recursive case: call the factorial function with n-1 until the base case is reached
return n * factorial(n - 1);
}
}
function counter(count) {
// display count
console.log(count);
// condition for stopping
if(count > 1) {
// decrease count
count = count - 1;
// call counter with new value of count
counter(count);
} else {
// terminate execution
return;
};
};
// access function
counter(5);
let decrementCounter = (number) => {
// Base case condition....
if(number === 0) return ;
console.log(number);
decrementCounter(number - 1);
}
decrementCounter(5);
 we have a function counter() that accepts the argument count, which is the starting point for our
countdown till 1.
 The counter() function first displays count then checks if the value of count is greater than 1 with
count > 1.
 If count > 1 evaluates to true, the program decreases the value of count and calls counter() with
the new value of count (recursion).
 Otherwise, if count > 1 evaluates to false, the program executes the return statement, stopping
the recursion.
 Here,
 The counter() function is a recursive function, a function that calls itself recursively.
 The count > 1 condition is called a base case, a condition that specifies when the recursion must
stop.
 Find Factorial of a Number
// recursive function
function factorial(num) {
// base case
// recurse only if num is greater than 0
if (num > 1) {
return num * factorial(num - 1);
}
else {
return 1;
};
};
let x = 3;
// store result of factorial() in variable
let y = factorial(x);
console.log(`The factorial of ${x} is ${y}`);
Recursion vs Iteration
Basic
Recursion is the process of calling a
function itself within its own code.
In iteration, there is a repeated
execution of the set of instructions.
In Iteration, loops are used to
execute the set of instructions
repetitively until the condition is
false.
Syntax
There is a termination condition is
specified.
The format of iteration includes
initialization, condition, and
increment/decrement of a variable.
Termination
The termination condition is defined
within the recursive function.
Here, the termination condition is
defined in the definition of the loop.
Code size
The code size in recursion is smaller
than the code size in iteration.
The code size in iteration is larger
than the code size in recursion.
Applied
It is always applied to
functions.
It is applied to loops.
Speed It is slower than iteration. It is faster than recursion.
Usage
Recursion is generally used
where there is no issue of time
complexity, and code size
requires being small.
It is used when we have to
balance the time complexity
against a large code size.
Time complexity It has high time complexity.
The time complexity in
iteration is relatively lower. We
can calculate its time
complexity by finding the no.
of cycles being repeated in a
loop.
Stack
It has to update and maintain
the stack.
There is no utilization of stack.
Memory
It uses more memory as
compared to iteration.
It uses less memory as
compared to recursion.
Recursion
function factorialRecursion(n) {
if (n === 0 || n === 1) {
return 1; // Base case
}
return n * factorialRecursion(n - 1); // Recursive case
}
console.log(factorialRecursion(5));
Iteration
function factorialIteration(n) {
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
console.log(factorialIteration(5));
Global Function in JS
 Global functions in JavaScript are functions that are available globally and can be used without needing to define or import them.
1. eval()
Description: Executes a string of JavaScript code.
Example:
eval("console.log('Hello, World!')");
2. isFinite()
Description: Determines if a value is a finite number.
Example:
console.log(isFinite(10)); // true
console.log(isFinite(Infinity)); // false
3. isNaN()
Description: Determines if a value is NaN (Not-a-Number).
EX:
console.log(isNaN('abc')); // true
console.log(isNaN(123)); // false
4. parseFloat()
Description: Parses a string and returns a floating-point number.
Example:
console.log(parseFloat("3.14")); // 3.14
5. parseInt()
Description: Parses a string and returns an integer.
Example:
console.log(parseInt("42")); // 42
console.log(parseInt("101", 2)); // 5 (binary conversion)
6. encodeURIComponent()
Description: Encodes a URI component.
Example:
console.log(encodeURIComponent("name=John Doe"));
7. decodeURIComponent()
Description: Decodes an encoded URI
Example:
console.log(decodeURIComponent("name%3DJohn%20Doe"));
8. unescape() (Deprecated)
Description: Decodes an encoded string.
Example:
console.log(unescape('%20')); // " "
9. escape() (Deprecated)
Description: Encodes a string.
Example:
console.log(escape("Hello World")); // "Hello%20World"
Date Methods
The new Date() Constructor
In JavaScript, date objects are created with new Date().
new Date() returns a date object with the current date and time.
Date Get Methods
Method Description
getFullYear() Get year as a four digit number (yyyy)
getMonth() Get month as a number (0-11)
getDate() Get day as a number (1-31)
getDay() Get weekday as a number (0-6)
getHours() Get hour (0-23)
getMinutes() Get minute (0-59)
getSeconds() Get second (0-59)
getMilliseconds() Get millisecond (0-999)
getTime() Get time (milliseconds since January 1, 1970)
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Dates</h1>
<h2>Using new Date()</h2>
<p>Create a new date object with the current date and time:</p>
<p id="demo"></p>
<script>
const d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
Get Full Year(Mentioned Year and current)
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Dates</h1>
<h2>The getFullYear() Method</h2>
<p>Return the full year of a date object:</p>
<p id="demo"></p>
<script>
const d = new Date("2021-03-25")
document.getElementById("demo").innerHTML = d.getFullYear();
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Dates</h1>
<h2>The getFullYear() Method</h2>
<p>Return the full year of a date object:</p>
<p id="demo"></p>
<script>
const d = new Date();
document.getElementById("demo").innerHTML = d.getFullYear();
</script>
</body>
</html>
The getMonth() Method
The getMonth() method returns the month of a date as a number (0-11).
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Dates</h1>
<h2>The getMonth() Method</h2>
<p>Return the month of a date as a number from 0 to 11.</p>
<p>To get the correct month number, you must add 1:</p>
<p id="demo"></p>
<script>
const d = new Date();
document.getElementById("demo").innerHTML = d.getMonth() + 1;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Dates</h1>
<h2>JavaScript getMonth()</h2>
<p>Return the month as a number.</p>
<p>You can use an array of names to return the month as a name:</p>
<p id="demo"></p>
<script>
const months =
["January","February","March","April","May","June","July","August","September","October","November","Decembe
r"];
const d = new Date("2021-03-25");
let month = months[d.getMonth()];
document.getElementById("demo").innerHTML = month;
</script>
</body>
</html>
CURRENT Month
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Dates</h1>
<h2>JavaScript getMonth()</h2>
<p>Return the month as a number.</p>
<p>You can use an array of names to return the month as a name:</p>
<p id="demo"></p>
<script>
const months =
["January","February","March","April","May","June","July","August","September","October","November","December"];
const d = new Date();
let month = months[d.getMonth()];
document.getElementById("demo").innerHTML = month;
</script>
</body>
</html>
HOURS:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Dates</h1>
<h2>The getHours() Method</h2>
<p>Return the hours of a date as a number (0-23):</p>
<p id="demo"></p>
<script>
const d = new Date();
document.getElementById("demo").innerHTML = d.getHours();
</script>
</body>
</html>
 Minutes:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Dates</h1>
<h2>The getMinutes() Method</h2>
<p>Returns the minutes of a date as a number (0-59):</p>
<p id="demo"></p>
<script>
const d = new Date();
document.getElementById("demo").innerHTML = d.getMinutes();
</script>
</body>
</html>
SECONDS:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Dates</h1>
<h2>The getSeconds() Method</h2>
<p>Return the seconds of a date as a number (0-59):</p>
<p id="demo"></p>
<script>
const d = new Date();
document.getElementById("demo").innerHTML = d.getSeconds();
</script>
</body>
</html>
Milliseconds:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Dates</h1>
<h2>The getMilliseconds() Method</h2>
<p>Return the milliseconds of a date as a number (0-999):</p>
<p id="demo"></p>
<script>
const d = new Date();
document.getElementById("demo").innerHTML = d.getMilliseconds();
</script>
</body>
</html>
GET DAY:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Dates</h1>
<h2>The getDay() Method</h2>
<p>Return the weekday as a number:</p>
<p id="demo"></p>
<script>
const d = new Date();
document.getElementById("demo").innerHTML = d.getDay();
</script>
</body>
</html>
Arrays in JS
 An array in JavaScript is a data structure used to store multiple values in a single variable.
 It can hold various data types and allows for dynamic resizing.
 Elements are accessed by their index, starting from 0.
1. Create using Literal
 Creating an array using array literal involves using square brackets [] to define and initialize the array.
// Creating an Empty Array
let a = [];
console.log(a);
// Creating an Array and Initializing with Values
let b = [10, 20, 30];
console.log(b);
2. Create using new Keyword (Constructor)
The “Array Constructor” refers to a method of creating arrays by invoking the Array constructor function.
// Creating and Initializing an array with values
let a = new Array(10, 20, 30);
console.log(a);
Basic Operations on JavaScript Arrays
1. Accessing Elements of an Array
Any element in the array can be accessed using the index number. The index in the arrays starts with 0.
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
// Accessing Array Elements
console.log(a[0]);
console.log(a[1]);
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<p id="demo"></p>
<script>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
</body>
</html>
2. Accessing the First Element of an Array
The array indexing starts from 0, so we can access first element of array using the index number.
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
// Accessing First Array Elements
let fst = a[0];
console.log("First Item: ", fst);
//<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>Bracket Indexing</h2>
<p>JavaScript array elements are accesses using numeric indexes (starting from 0).</p>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits[0];
</script>
</body>
</html>
 3. Accessing the Last Element of an Array
 We can access the last array element using [array.length – 1] index number.
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
// Accessing Last Array Elements
let lst = a[a.length - 1];
console.log("First Item: ", lst);
 Modifying the Array Elements
Elements in an array can be modified by assigning a new value to their corresponding index.
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
console.log(a);
a[1]= "Bootstrap";
console.log(a);
5. Adding Elements to the Array
Elements can be added to the array using methods like push() and unshift().
The push() method add the element to the end of the array.
The unshift() method add the element to the starting of the array.
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
// Add Element to the end of Array
a.push("Node.js");
// Add Element to the beginning
a.unshift("Web Development");
console.log(a);
6. Removing Elements from an Array
To remove the elements from an array we have different methods like pop(), shift(), or splice().
The pop() method removes an element from the last index of the array.
The shift() method removes the element from the first index of the array.
The splice() method removes or replaces the element from the array.
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
console.log("Original Array: " + a);
// Removes and returns the last element
let lst = a.pop();
console.log("After Removing the last: " + a);
// Removes and returns the first element
let fst = a.shift();
console.log("After Removing the First: " + a);
// Removes 2 elements starting from index 1
a.splice(1, 2);
console.log("After Removing 2 elements starting from index 1: " + a);
7. Array Length
 We can get the length of the array using the array length property.
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
let len = a.length;
console.log("Array Length: " + len);
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The length Property</h2>
<p>The length property returns the length of an array:</p>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let size = fruits.length;
document.getElementById("demo").innerHTML = size;
</script>
</body>
</html>
8. Increase and Decrease the Array Length
 We can increase and decrease the array length using the JavaScript length property.
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"]
// Increase the array length to 7
a.length = 7;
console.log("After Increasing Length: ", a);
// Decrease the array length to 2
a.length = 2;
console.log("After Decreasing Length: ", a)
9. Iterating Through Array Elements
We can iterate array and access array elements using for loop and forEach loop.
Example: It is an example of for loop.
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
// Iterating through for loop
for (let i = 0; i < a.length; i++) {
console.log(a[i])
}
//// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
// Iterating through forEach loop
a.forEach(function myfunc(x) {
console.log(x);
});//
10. Array Concatenation
 Combine two or more arrays using the concat() method. It returns new array containing joined arrays
elements.
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS", "React"];
let b = ["Node.js", "Expess.js"];
// Concatenate both arrays
let concateArray = a.concat(b);
console.log("Concatenated Array: ", concateArray);
11. Conversion of an Array to String
 We have a builtin method toString() to converts an array to a string.
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
// Convert array ot String
console.log(a.toString());
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The toString() Method</h2>
<p>The toString() method returns an array as a comma separated string:</p>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
</script>
</body>
</html>
12. Check the Type of an Arrays
The JavaScript typeof operator is used at check the type of an array. It returns “object” for arrays.
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
// Check type of array
console.log(typeof a);

JS Control Statements and Functions.pptx

  • 1.
    JavaScript Control statements Controlstatements in JavaScript are used to alter the normal flow of execution of a program. They allow you to make decisions, repeat code blocks, and jump to different parts of your code. They are TWO Types Conditional Statements: Based on an expression passed, a conditional statement makes a decision, which results in either YES or NO(True or False). Iterative Statements (Loop): These statements continue to repeat until the expression or condition is satisfied.
  • 2.
     Conditional Statements Conditional statements in a program decide the next step based on the result.  They result in either True or False.  The program moves to the next step if a condition is passed and true.  However, if the condition is false, the program moves to another step. These statements are executed only once, unlike loop statements. If,else and else if
  • 3.
    IF  When youwant to check for a specific condition with the IF condition, the inner code block executes if the provided condition is satisfied. if (condition) {  //code block to be executed if condition is satisfied } Example: let age = 18; if (age >= 18) { console.log("You are an adult."); }
  • 4.
    if-else Statement: The If-ElseStatement is an extended version of the If statement. We use this one when we want to check a condition we want and another one if the evaluation turns out otherwise. if (condition) { // code to be executed if the condition is true } Else { // code to be executed if the condition is false }
  • 5.
    let age =18; if (age >= 18) { console.log("You are an adult."); } else { console.log("You are Child."); }################### let isRaining = false; if (isRaining) { console.log("Take an umbrella."); } Else { console.log("Enjoy the sunshine!"); }
  • 6.
    else if statement Addsmore conditions to the if statement, allowing for multiple alternative conditions to be tested. if (condition1) { // code to be executed if condition1 is true } else if (condition2) { // code to be executed if condition1 is false and condition2 is true } else if (condition3) { // code to be executed if condition1 and condition2 are false and condition3 is true } else { // code to be executed if none of the conditions are true }
  • 7.
    Example: let grade =85; if (grade >= 90) { console.log(“MCA Student!"); } else if (grade >= 80) { console.log(“MBA Students!"); } else if (grade >= 70) { console.log(“Degree Student"); } else { console.log(“Student"); }
  • 8.
     Looping Statements: DifferentKinds of Loops JavaScript supports different kinds of loops: for - loops through a block of code a number of times for/in - loops through the properties of an object for/of - loops through the values of an iterable object while - loops through a block of code while a specified condition is true do/while - also loops through a block of code while a specified condition is true
  • 9.
     The ForLoop  The for statement creates a loop with 3 optional expressions:  for (expression 1; expression 2; expression 3) {  // code block to be executed  }  Expression 1 is executed (one time) before the execution of the code block.  Expression 2 defines the condition for executing the code block.  Expression 3 is executed (every time) after the code block has been executed.
  • 10.
    <!DOCTYPE html> <html> <body> <h2>JavaScript ForLoop</h2> <p id="demo"></p> <script> let text = ""; for (let i = 0; i < 5; i++) { text += "The number is " + i + "<br>"; }document.getElementById("demo").innerHTML = text; </script> </body> </html> for (let i = 0; i < 5; i++) { console.log(i); }
  • 11.
    FOR IN <!DOCTYPE html> <html> <body> <h2>JavaScriptFor In Loop</h2> <p>The for in statement loops through the properties of an object:</p> <p id="demo"></p> <script> const person = {fname:“RK", lname:“Reddy", age:31}; let txt = ""; for (let x in person) { txt += person[x] + " "; } document.getElementById("demo").innerHTML = txt; </script> </body> </html>
  • 12.
    The for inloop iterates over a person object Each iteration returns a key (x) The key is used to access the value of the key The value of the key is person[x] The For Of Loop The JavaScript for of statement loops through the values of an iterable object. It lets you loop over iterable data structures such as Arrays, Strings, Maps, NodeLists, and more:  for (variable of iterable) { // code block to be executed }
  • 13.
    <!DOCTYPE html> <html> <body> <h2>JavaScript ForOf Loop</h2> <p>The for of statement loops through the values of an iterable object.</p> <p id="demo"></p> <script> let language = "JavaScript"; let text = ""; for (let x of language) { text += x + "<br>"; } document.getElementById("demo").innerHTML = text; </script> </body> </html>
  • 14.
    While Loop Loops canexecute a block of code as long as a specified condition is true. The while loop loops through a block of code as long as a specified condition is true. Syntax: while (condition) { // code block to be executed }
  • 15.
    <!DOCTYPE html> <html> <body> <h2>JavaScript WhileLoop</h2> <p id="demo"></p> <script> let text = ""; let i = 0; while (i < 10) { text += "<br>The number is " + i; i++; } document.getElementById("demo").innerHTML = text; </script> </body> </html>
  • 16.
    The Do WhileLoop The do while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true. Syntax do { // code block to be executed } while (condition); Example The example below uses a do while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:
  • 17.
    let i =0; while (i < 5) { console.log(i); i++; }
  • 18.
    <!DOCTYPE html> <html> <body> <h2>JavaScript DoWhile Loop</h2> <p id="demo"></p> <script> let text = "" let i = 0; do { text += "<br>The number is " + i; i++; } while (i < 10); document.getElementById("demo").innerHTML = text; </script> </body> </html>
  • 19.
    let i =0; do { console.log(i); i++; } while (i < 5);
  • 20.
    Jump Statements break Statement:Exits the current loop or switch statement. continue Statement: Skips the current iteration of the loop and moves to the next. By understanding and effectively using these control statements, you can create more complex and dynamic JavaScript programs. The break statement "jumps out" of a loop. The continue statement "jumps over" one iteration in the loop. It was used to "jump out" of a switch() statement. The break statement can also be used to jump out of a loop:
  • 21.
    switch (expression) { casevalue1: // code block 1; break; case value2: // code block 2; break; ... default: // default code block; }
  • 23.
    let day =3; let dayName; switch (day) { case 1: dayName = "Monday"; break; 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; case 7: dayName = "Sunday"; break; default: dayName = "Invalid day"; } console.log(dayName);
  • 24.
    let grade ='B'; let result; switch (grade) { case 'A': result = "A (Excellent)"; break; case 'B': result = "B (Average)"; break; case 'C': result = "C (Below than average)"; break; default: result = "No Grade"; } console.log(result);
  • 25.
    JavaScript Continue Statement The continue statement in Javascript is used to break the iteration of the loop and follow with the next iteration. The break in the iteration is possible only when the specified condition going to occur.  The major difference between the continue and break statement is that the break statement breaks out of the loop completely while continue is used to break one statement and iterate to the next statement.  How does the continue statement work for different loops?  In a For loop, iteration goes to an updated expression which means the increment expression is first updated.  In a While loop, it again executes the condition.  Syntax: Continue;
  • 26.
    for (let i= 0; i < 11; i++) { if (i % 2 == 0) continue; console.log(i); } // let i = 0; while (i < 11) { i++; if (i % 2 == 0) continue; console.log(i); }
  • 27.
    JavaScript Programming Modules JavaScriptModules enables you to divide your code into multiple files which makes it easier to maintain a code-base. Modules are imported using the import statement from the external files. Exporting a Module There are two types of exports: Named Exports Named exports allow you to export multiple values from a module by their names, enabling selective imports. Default Exports Default exports allow you to export a single value or entity from a module. This can be imported without using curly braces.
  • 28.
    <!DOCTYPE html> <html> <body> <h1>JavaScript Modules</h1> <pid="demo"></p> <script type="module"> import message from "./message.js"; document.getElementById("demo").innerHTML = message(); </script> </body> </html>
  • 29.
    Named Exports Let uscreate a file named person.js, and fill it with the things we want to export. You can create named exports two ways. In-line individually, or all at once at the bottom. person.js export const name = “RK"; export const age = 31;
  • 30.
     const name= ”RK"; const age = 31; export {name, age};
  • 31.
     Import You canimport modules into a file in two ways, based on if they are named exports or default exports. Named exports are constructed using curly braces. Default exports are not. <!DOCTYPE html> <html> <body> <h1>JavaScript Modules</h1> <p id="demo"></p> <script type="module"> import { name, age } from "./person.js"; let text = "My name is " + name + ", I am " + age + "."; document.getElementById("demo").innerHTML = text; </script> </body> </html>
  • 32.
    Example(INDEX.HTML) <html> <head> <meta charset=“UTF-8”> <title>….</title> </head> <body> <h1>JS Modulesare</h1> <script src=“func.js” type=“module”></script> </body> </html>
  • 33.
    Index.js export function add(a,b) { returna+b; }/*export function subtract(a,b) { Return a-b; }*/ FUNC.js import {add} from ‘./index.js’//{add,subtract} console.log(add(4,5));
  • 34.
     Func.js  Import* as calculate from ‘./index.js’  Console.log(calculate.add());  Console.log(calculate.subtract());  index.js  Export default function add(a,b)  {  Return a+b;  }  Fun  Import add from .
  • 35.
    JavaScript Recursion Recursion isa programming technique where a function calls itself repeatedly to solve a problem Every time you write a recursive function, three elements must be present. They are: The function definition. The base condition. The recursive call. In the function, it makes a call to itself until the base condition is met and it stops executing. The second recursion function that occurs outside of the function code takes arguments and only calls the recursive function once.
  • 36.
     Base Condition The base case is the most critical component of each recursive function. When the problem is divided into smaller jobs, it is the smallest component of the problem to be solved. It can also be seen as the command that, if the set condition is true, it can end the recursion process. function recursion() { // The Function Declaration if (true) { // here is the base case command return; } // Function and recursive step codes }
  • 37.
     The RecursiveCall  The Recursive Call command in recursion is only responsible for triggering a new recursive call. The Recursive Call command is the actual command that addresses the main problem that you want to solve. function recursion() { // The Function Declaration if (true) { // The base case return; } // Function code // and recursive step codes return ... ; } //Here is The Recursive Call command recursion()
  • 38.
    function factorial(n) { //Base case: if n is 0 or 1, return 1 if (n === 0 || n === 1) { return 1; } else { // Recursive case: call the factorial function with n-1 until the base case is reached return n * factorial(n - 1); } }
  • 39.
    function counter(count) { //display count console.log(count); // condition for stopping if(count > 1) { // decrease count count = count - 1; // call counter with new value of count counter(count); } else { // terminate execution return; }; }; // access function counter(5);
  • 40.
    let decrementCounter =(number) => { // Base case condition.... if(number === 0) return ; console.log(number); decrementCounter(number - 1); } decrementCounter(5);
  • 41.
     we havea function counter() that accepts the argument count, which is the starting point for our countdown till 1.  The counter() function first displays count then checks if the value of count is greater than 1 with count > 1.  If count > 1 evaluates to true, the program decreases the value of count and calls counter() with the new value of count (recursion).  Otherwise, if count > 1 evaluates to false, the program executes the return statement, stopping the recursion.  Here,  The counter() function is a recursive function, a function that calls itself recursively.  The count > 1 condition is called a base case, a condition that specifies when the recursion must stop.
  • 42.
     Find Factorialof a Number // recursive function function factorial(num) { // base case // recurse only if num is greater than 0 if (num > 1) { return num * factorial(num - 1); } else { return 1; }; }; let x = 3; // store result of factorial() in variable let y = factorial(x); console.log(`The factorial of ${x} is ${y}`);
  • 43.
    Recursion vs Iteration Basic Recursionis the process of calling a function itself within its own code. In iteration, there is a repeated execution of the set of instructions. In Iteration, loops are used to execute the set of instructions repetitively until the condition is false. Syntax There is a termination condition is specified. The format of iteration includes initialization, condition, and increment/decrement of a variable. Termination The termination condition is defined within the recursive function. Here, the termination condition is defined in the definition of the loop. Code size The code size in recursion is smaller than the code size in iteration. The code size in iteration is larger than the code size in recursion.
  • 44.
    Applied It is alwaysapplied to functions. It is applied to loops. Speed It is slower than iteration. It is faster than recursion. Usage Recursion is generally used where there is no issue of time complexity, and code size requires being small. It is used when we have to balance the time complexity against a large code size. Time complexity It has high time complexity. The time complexity in iteration is relatively lower. We can calculate its time complexity by finding the no. of cycles being repeated in a loop. Stack It has to update and maintain the stack. There is no utilization of stack. Memory It uses more memory as compared to iteration. It uses less memory as compared to recursion.
  • 45.
    Recursion function factorialRecursion(n) { if(n === 0 || n === 1) { return 1; // Base case } return n * factorialRecursion(n - 1); // Recursive case } console.log(factorialRecursion(5));
  • 46.
    Iteration function factorialIteration(n) { letresult = 1; for (let i = 2; i <= n; i++) { result *= i; } return result; } console.log(factorialIteration(5));
  • 47.
    Global Function inJS  Global functions in JavaScript are functions that are available globally and can be used without needing to define or import them. 1. eval() Description: Executes a string of JavaScript code. Example: eval("console.log('Hello, World!')"); 2. isFinite() Description: Determines if a value is a finite number. Example: console.log(isFinite(10)); // true console.log(isFinite(Infinity)); // false 3. isNaN() Description: Determines if a value is NaN (Not-a-Number). EX: console.log(isNaN('abc')); // true console.log(isNaN(123)); // false
  • 48.
    4. parseFloat() Description: Parsesa string and returns a floating-point number. Example: console.log(parseFloat("3.14")); // 3.14 5. parseInt() Description: Parses a string and returns an integer. Example: console.log(parseInt("42")); // 42 console.log(parseInt("101", 2)); // 5 (binary conversion) 6. encodeURIComponent() Description: Encodes a URI component. Example: console.log(encodeURIComponent("name=John Doe"));
  • 49.
    7. decodeURIComponent() Description: Decodesan encoded URI Example: console.log(decodeURIComponent("name%3DJohn%20Doe")); 8. unescape() (Deprecated) Description: Decodes an encoded string. Example: console.log(unescape('%20')); // " " 9. escape() (Deprecated) Description: Encodes a string. Example: console.log(escape("Hello World")); // "Hello%20World"
  • 50.
    Date Methods The newDate() Constructor In JavaScript, date objects are created with new Date(). new Date() returns a date object with the current date and time. Date Get Methods Method Description getFullYear() Get year as a four digit number (yyyy) getMonth() Get month as a number (0-11) getDate() Get day as a number (1-31) getDay() Get weekday as a number (0-6) getHours() Get hour (0-23) getMinutes() Get minute (0-59) getSeconds() Get second (0-59) getMilliseconds() Get millisecond (0-999) getTime() Get time (milliseconds since January 1, 1970)
  • 51.
    <!DOCTYPE html> <html> <body> <h1>JavaScript Dates</h1> <h2>Usingnew Date()</h2> <p>Create a new date object with the current date and time:</p> <p id="demo"></p> <script> const d = new Date(); document.getElementById("demo").innerHTML = d; </script> </body> </html>
  • 52.
    Get Full Year(MentionedYear and current) <!DOCTYPE html> <html> <body> <h1>JavaScript Dates</h1> <h2>The getFullYear() Method</h2> <p>Return the full year of a date object:</p> <p id="demo"></p> <script> const d = new Date("2021-03-25") document.getElementById("demo").innerHTML = d.getFullYear(); </script> </body> </html>
  • 53.
    <!DOCTYPE html> <html> <body> <h1>JavaScript Dates</h1> <h2>ThegetFullYear() Method</h2> <p>Return the full year of a date object:</p> <p id="demo"></p> <script> const d = new Date(); document.getElementById("demo").innerHTML = d.getFullYear(); </script> </body> </html>
  • 54.
    The getMonth() Method ThegetMonth() method returns the month of a date as a number (0-11). <!DOCTYPE html> <html> <body> <h1>JavaScript Dates</h1> <h2>The getMonth() Method</h2> <p>Return the month of a date as a number from 0 to 11.</p> <p>To get the correct month number, you must add 1:</p> <p id="demo"></p> <script> const d = new Date(); document.getElementById("demo").innerHTML = d.getMonth() + 1; </script> </body> </html>
  • 55.
    <!DOCTYPE html> <html> <body> <h1>JavaScript Dates</h1> <h2>JavaScriptgetMonth()</h2> <p>Return the month as a number.</p> <p>You can use an array of names to return the month as a name:</p> <p id="demo"></p> <script> const months = ["January","February","March","April","May","June","July","August","September","October","November","Decembe r"]; const d = new Date("2021-03-25"); let month = months[d.getMonth()]; document.getElementById("demo").innerHTML = month; </script> </body> </html>
  • 56.
    CURRENT Month <!DOCTYPE html> <html> <body> <h1>JavaScriptDates</h1> <h2>JavaScript getMonth()</h2> <p>Return the month as a number.</p> <p>You can use an array of names to return the month as a name:</p> <p id="demo"></p> <script> const months = ["January","February","March","April","May","June","July","August","September","October","November","December"]; const d = new Date(); let month = months[d.getMonth()]; document.getElementById("demo").innerHTML = month; </script> </body> </html>
  • 57.
    HOURS: <!DOCTYPE html> <html> <body> <h1>JavaScript Dates</h1> <h2>ThegetHours() Method</h2> <p>Return the hours of a date as a number (0-23):</p> <p id="demo"></p> <script> const d = new Date(); document.getElementById("demo").innerHTML = d.getHours(); </script> </body> </html>
  • 58.
     Minutes: <!DOCTYPE html> <html> <body> <h1>JavaScriptDates</h1> <h2>The getMinutes() Method</h2> <p>Returns the minutes of a date as a number (0-59):</p> <p id="demo"></p> <script> const d = new Date(); document.getElementById("demo").innerHTML = d.getMinutes(); </script> </body> </html>
  • 59.
    SECONDS: <!DOCTYPE html> <html> <body> <h1>JavaScript Dates</h1> <h2>ThegetSeconds() Method</h2> <p>Return the seconds of a date as a number (0-59):</p> <p id="demo"></p> <script> const d = new Date(); document.getElementById("demo").innerHTML = d.getSeconds(); </script> </body> </html>
  • 60.
    Milliseconds: <!DOCTYPE html> <html> <body> <h1>JavaScript Dates</h1> <h2>ThegetMilliseconds() Method</h2> <p>Return the milliseconds of a date as a number (0-999):</p> <p id="demo"></p> <script> const d = new Date(); document.getElementById("demo").innerHTML = d.getMilliseconds(); </script> </body> </html>
  • 61.
    GET DAY: <!DOCTYPE html> <html> <body> <h1>JavaScriptDates</h1> <h2>The getDay() Method</h2> <p>Return the weekday as a number:</p> <p id="demo"></p> <script> const d = new Date(); document.getElementById("demo").innerHTML = d.getDay(); </script> </body> </html>
  • 62.
    Arrays in JS An array in JavaScript is a data structure used to store multiple values in a single variable.  It can hold various data types and allows for dynamic resizing.  Elements are accessed by their index, starting from 0. 1. Create using Literal  Creating an array using array literal involves using square brackets [] to define and initialize the array. // Creating an Empty Array let a = []; console.log(a); // Creating an Array and Initializing with Values let b = [10, 20, 30]; console.log(b);
  • 63.
    2. Create usingnew Keyword (Constructor) The “Array Constructor” refers to a method of creating arrays by invoking the Array constructor function. // Creating and Initializing an array with values let a = new Array(10, 20, 30); console.log(a);
  • 64.
    Basic Operations onJavaScript Arrays 1. Accessing Elements of an Array Any element in the array can be accessed using the index number. The index in the arrays starts with 0. // Creating an Array and Initializing with Values let a = ["HTML", "CSS", "JS"]; // Accessing Array Elements console.log(a[0]); console.log(a[1]); <!DOCTYPE html> <html> <body> <h1>JavaScript Arrays</h1> <p id="demo"></p> <script> const cars = ["Saab", "Volvo", "BMW"]; document.getElementById("demo").innerHTML = cars; </script> </body> </html>
  • 65.
    2. Accessing theFirst Element of an Array The array indexing starts from 0, so we can access first element of array using the index number. // Creating an Array and Initializing with Values let a = ["HTML", "CSS", "JS"]; // Accessing First Array Elements let fst = a[0]; console.log("First Item: ", fst); //<!DOCTYPE html> <html> <body> <h1>JavaScript Arrays</h1> <h2>Bracket Indexing</h2> <p>JavaScript array elements are accesses using numeric indexes (starting from 0).</p> <p id="demo"></p> <script> const fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits[0]; </script> </body> </html>
  • 66.
     3. Accessingthe Last Element of an Array  We can access the last array element using [array.length – 1] index number. // Creating an Array and Initializing with Values let a = ["HTML", "CSS", "JS"]; // Accessing Last Array Elements let lst = a[a.length - 1]; console.log("First Item: ", lst);
  • 67.
     Modifying theArray Elements Elements in an array can be modified by assigning a new value to their corresponding index. // Creating an Array and Initializing with Values let a = ["HTML", "CSS", "JS"]; console.log(a); a[1]= "Bootstrap"; console.log(a);
  • 68.
    5. Adding Elementsto the Array Elements can be added to the array using methods like push() and unshift(). The push() method add the element to the end of the array. The unshift() method add the element to the starting of the array. // Creating an Array and Initializing with Values let a = ["HTML", "CSS", "JS"]; // Add Element to the end of Array a.push("Node.js"); // Add Element to the beginning a.unshift("Web Development"); console.log(a);
  • 69.
    6. Removing Elementsfrom an Array To remove the elements from an array we have different methods like pop(), shift(), or splice(). The pop() method removes an element from the last index of the array. The shift() method removes the element from the first index of the array. The splice() method removes or replaces the element from the array. // Creating an Array and Initializing with Values let a = ["HTML", "CSS", "JS"]; console.log("Original Array: " + a); // Removes and returns the last element let lst = a.pop(); console.log("After Removing the last: " + a); // Removes and returns the first element let fst = a.shift(); console.log("After Removing the First: " + a); // Removes 2 elements starting from index 1 a.splice(1, 2); console.log("After Removing 2 elements starting from index 1: " + a);
  • 70.
    7. Array Length We can get the length of the array using the array length property. // Creating an Array and Initializing with Values let a = ["HTML", "CSS", "JS"]; let len = a.length; console.log("Array Length: " + len); <!DOCTYPE html> <html> <body> <h1>JavaScript Arrays</h1> <h2>The length Property</h2> <p>The length property returns the length of an array:</p> <p id="demo"></p> <script> const fruits = ["Banana", "Orange", "Apple", "Mango"]; let size = fruits.length; document.getElementById("demo").innerHTML = size; </script> </body> </html>
  • 71.
    8. Increase andDecrease the Array Length  We can increase and decrease the array length using the JavaScript length property. // Creating an Array and Initializing with Values let a = ["HTML", "CSS", "JS"] // Increase the array length to 7 a.length = 7; console.log("After Increasing Length: ", a); // Decrease the array length to 2 a.length = 2; console.log("After Decreasing Length: ", a)
  • 72.
    9. Iterating ThroughArray Elements We can iterate array and access array elements using for loop and forEach loop. Example: It is an example of for loop. // Creating an Array and Initializing with Values let a = ["HTML", "CSS", "JS"]; // Iterating through for loop for (let i = 0; i < a.length; i++) { console.log(a[i]) } //// Creating an Array and Initializing with Values let a = ["HTML", "CSS", "JS"]; // Iterating through forEach loop a.forEach(function myfunc(x) { console.log(x); });//
  • 73.
    10. Array Concatenation Combine two or more arrays using the concat() method. It returns new array containing joined arrays elements. // Creating an Array and Initializing with Values let a = ["HTML", "CSS", "JS", "React"]; let b = ["Node.js", "Expess.js"]; // Concatenate both arrays let concateArray = a.concat(b); console.log("Concatenated Array: ", concateArray);
  • 74.
    11. Conversion ofan Array to String  We have a builtin method toString() to converts an array to a string. // Creating an Array and Initializing with Values let a = ["HTML", "CSS", "JS"]; // Convert array ot String console.log(a.toString());
  • 75.
    <!DOCTYPE html> <html> <body> <h1>JavaScript Arrays</h1> <h2>ThetoString() Method</h2> <p>The toString() method returns an array as a comma separated string:</p> <p id="demo"></p> <script> const fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.toString(); </script> </body> </html>
  • 76.
    12. Check theType of an Arrays The JavaScript typeof operator is used at check the type of an array. It returns “object” for arrays. // Creating an Array and Initializing with Values let a = ["HTML", "CSS", "JS"]; // Check type of array console.log(typeof a);