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

CSS UNIT 2

This document covers key concepts in JavaScript, focusing on arrays, functions, and strings. It explains how to construct and manipulate arrays, the types and definitions of functions, and how to declare and modify strings, along with examples of common methods. Additionally, it includes practical exercises and code snippets to demonstrate these concepts.

Uploaded by

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

CSS UNIT 2

This document covers key concepts in JavaScript, focusing on arrays, functions, and strings. It explains how to construct and manipulate arrays, the types and definitions of functions, and how to declare and modify strings, along with examples of common methods. Additionally, it includes practical exercises and code snippets to demonstrate these concepts.

Uploaded by

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

Contents

UNIT 2. ARRAYS, FUNCTION AND STRING................................................................... 2

Arrays.................................................................................................................................... 2

Ways to construct an array in JS ................................................................................... 2

Common array methods in Javascript ........................................................................... 2

Looping through an array: ............................................................................................. 3

Associative Array: ............................................................................................................ 5

Function ................................................................................................................................ 5

Types of Functions ........................................................................................................... 5

Defining a function ........................................................................................................... 7

Scope of the variable & parameters ............................................................................... 7

Calling a Function ............................................................................................................ 7

Strings ................................................................................................................................... 9

Declaring a string ............................................................................................................. 9

Common String Methods .............................................................................................. 10


UNIT 2. ARRAYS, FUNCTION AND STRING

Arrays
An array is a data structure that allows to store multiple values in a single variable it stores a
fixed – size sequential collection of elements of the same or different type.
The main advantage of an array is that is allows us to handle individual elements with the help
of an index.
Ways to construct an array in JS
1) JS array literal
Syntax: var array-name = [val1, val2…valn];
2) Creating instance of array directly
Syntax: var array_name =new Array ( ); // declaration
array_name[0] = val1;
array_name[1] = val2; //initialization
3) JS array constructor
Syntax: var array_name = new Array (val1, val2…, valn);
Common array methods in Javascript
1) Array Creation and Initialization Methods
Function Explanation Syntax Example
Array Creates a new array object. let array = new Array(size); let array = new Array(5); //
Creates an array of length 5
from Creates a new array from an array-like or Array.from(iterable); let array = Array.from('hello'); //
iterable object. ['h', 'e', 'l', 'l', 'o']
Of Creates a new array with a variable Array.of(element1, element2, let array = Array.of(1, 2, 3); // [1,
number of arguments, regardless of ...); 2, 3]
number or type.
2) Accessing and Modifying Elements
Function Explanation Syntax Example
Concat Merges two or more arrays. array1.concat(array2, ...); let newArray = array1.concat
(array2);
Push Adds one or more elements to the array.push(element1,..., array.push(4, 5); // Adds 4 and 5 to
end of an array. elementN); the end
Pop Removes the last element of an array.pop(); array.pop(); // Removes the last
array. element
Shift Removes the first element of an array.shift(); array.shift(); // Removes the first
array. element
Unshift Adds one or more elements to the array.unshift(element1, array.unshift(0); // Adds 0 to the
front of an array. ..., elementN); beginning
Slice Extracts a section of an array. array.slice(begin, end); array.slice(1, 3); // Extracts
elements from index 1 to 2
Splice Adds/Removes elements from an array.splice(start, array.splice(1, 0, 'a'); // Inserts 'a' at
array. deleteCount, item1, index 1
item2, ...);
3) Searching and Sorting
Function Explanation Syntax Example
indexOf Returns the first index at which a array.indexOf(element); array.indexOf(3); // Returns
given element can be found. index of the first 3
lastIndexOf Returns the last index at which a array.lastIndexOf(element); array.lastIndexOf(3); // Returns
given element can be found. index of the last 3
Find Returns the first element that array.find(callback); array.find(element => element >
satisfies a testing function. 2); // Returns first element > 2
findIndex Returns the index of the first array.findIndex(callback); array.findIndex(element =>
element that satisfies a testing element > 2); // Returns index of
function. first element > 2
Sort Sorts the elements of an array in array.sort([compareFunction]); array.sort(); // Sorts array
place. elements in ascending order
Reverse Reverses the order of the elements array.reverse(); array.reverse(); // Reverses the
of an array. order of elements
4) Iteration Methods
Function Explanation Syntax Example
forEach Executes a provided function once for array.forEach(callback); array.forEach(element =>
each array element. console.log(element));

Every Tests whether all elements pass the array.every(callback); array.every(element =>
provided function. element > 0); // Checks if all
elements > 0
Some Tests whether at least one element array.some(callback); array.some(element =>
passes the provided function. element > 0); // Checks if
any element > 0

5) Other Useful Methods


Function Explanation Syntax Example
join Joins all elements of an array into array.join([separator]); array.join(', '); // Joins elements
a string. with a comma and space
includes Determines whether an array array.includes(searchElement); array.includes(2); // Checks if 2 is
includes a certain element. in the array
Looping through an array:
We can loop through an array is JS in the following ways;
1) Using the ‘forEach()’ method:
‘forEach()’ is used to execute a provided function once for each elements in an array it is a
convenient way to iterate through all the items in an array without having to manually setup a
loop.
Syntax: array.forEach (function (elements, index, array) {// code});
element – current item in the array.
index (optional) – Index of the current item.
array (optional)- Array that forEach is being called on.
Arrow function syntax:
array.forEach (element) => {//code};
Example:
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function (number)
{ console.log (number); };
numbers.forEach((number) => console.log(number));
2) Using the ‘for..of’ statement
The ‘for..of’ statement provides a way to iterate over iterable objects , such as arrays, and
access their values directly. It simplifies the process of looping through an array by focusing
on values rather than the indices.
Syntax: for (const item of array)
{ //code }
array - The iterable object (eg. array).
item – Current value in the iteration.
Example – const fruits = [‘apple’, ‘banana’, ‘cherry’];
for (const fruit of fruits)
console.log(fruit);
3) Using the basic for loop
4) Using while loop

WAP to implement array methods for adding and removing methods from an array. Display the array after every
method.
let array=[1, 2, 3, 4, 5];
console.log (“Current array: ”, array);
array.push(6); //Add to End
console.log(array);
array.unshift(0); // Add to Beginning
console.log(array);
array.pop(); //Remove from End
console.log(array);
array.shift(); //Remove from Beginning
console.log(array);
WAP to combine 3 different arrays into one & display result with ‘-’ between the elements.
let arr1 = [1, 2, 3];
let arr2 = [3.7, 4.2, 5.9];
let arr3 = [“a”, “b”, “c”];
let result = arr1.concat (arr2, arr3);
document.write (result.join (“-”));

Associative Array:
An associative array is essentially an object in JS. They store a collection of key–value pairs.
Each key is unique & used to access the corresponding value. Unlike a regular array that uses
numeric indices, associative arrays use keys that are usually strings or other data types.
Object as an associative array:
In JS, there isn’t a native data type called an ‘associative array’, but objects serve similar
purposes. The properties of an object act as the key & the corresponding values can be any
valid JD data type. They do not have a ‘length’ property like a normal array & cannot be
traversed using normal for.

WAP to set the index of array as CSS, AJP, OSY, STE, EST. values for these indices as 22519, 22517, 22516, 22518,
22447 respectively. Display array elements with index.
const values = { CSS: 22519
AJP: 22517
OSY: 22516
STE: 22518
EST: 22447 };
for (let key in values)
document.write (key+ “:”+ values[key] + “<br>”);

Function
Functions are building blocks of any programming language that are executed when called or
invoked. It is a block of statements that perform a certain task.
Types of Functions
1. Built-in functions
They are provided by JS to perform common tasks. These are predefined functions that can be
used directly in the code.
Examples: alert(): Displays a message to the user in a dialog box.
parseInt(): Converts a string to an integer.
2. User Defined functions
These are the functions that you create to perform specific tasks according to your need.
Syntax: function function–name (parameters)
{
// function body
return value; // optional
}
WAP to create a function to find me perfect number between 1 and 100.
function isPerfect (num)
{
if (num <= 1)
return false; // 1 is not considered a perfect number
let sum =0;
for (let i = 1; i <= num/2; i++) //no num greater than num/2 can be a proper divisor
{
if (num % i === 0)
sum += i;
}
return sum === num; //if the sum of divisors is equal to num, then only it is a perfect number
}
function perfectnum(start, end) //find all the perfect number in the given range
{
let arr = []; // stores any perfect number found
for (let i = start; i <= end; i++)
{
if(isPerfect(i) )
arr.push(i) ;
}
return arr; //6=1+2+3, 28= 1+2+4+7+14
}
let num = perfectnum (1,100);
document.write(“Perfect numbers between 1 & 100: ” ,num);
WAP to create function 2 multiply 2 number 3 numbers & 4 numbers. Write function in external JS & call this
function from the html file.
<script src = “multiply.js”> </script>
function mul(a, b, c, d)
{ let result =a * b;
console.log (“*2 numbers: ” +result);
if (arguments.length > 2)
{ result *= c;
console.log (“*3 numbers: ” +result); }
if (arguments.length > 3)
{ result *= d;
console.log (“*3 numbers: ” +result); }
return result; }

Defining a function
A function must be defined before it can be called in a JS statement. The best place to define a
function is at the beginning of a JS that is inserted in the <head> tag, because then all the
subsequent JS will know the definition of that function.
Naming conventions for a function
 The name must be letter(s), digit(s) or ‘-’.
 Unique to the JS on your webpage; as no two functions can have the same name
 The name cannot
 Begin with a digit.
 Be a keyword.
 Be a reserved word.
Scope of the variable & parameters
The scope of the variable means how the different parts of the program can access that variable.
In JavaScript, there are two types of scope - Local & Global.
Local Variable - A Variable declared within a function is called a local variable. Other parts of
the JS don’t know that the local variable exists because it is not available outside the function.
Global Variable - A variable declared outside a function is called a global variable because it
is available to all parts of the JS, i.e., statements within any function & statements outside the
function can use a global variable.
Calling a Function
 A function can be called any time when the browser is needed to execute statements
contained in the code block of the function.
 A function is called by using the function name followed by parentheses ‘()’. If the
function has parameters, values for each parameter are placed within the ‘()’.
 These values must be placed in the same order that parameters are listed in the function
definition. A common must separate each value.

Calling a function from HTML


A function can be called from the html code on the web page. Typically, a function will be
called in response to an event such as when the web page is loaded by the browser. The function
is called from the html code nearly the same way as the function is called from within a JS,
except in html code the function call is assigned as a value of an HTML tag attribute.
<html>
<script>
function onpageLoad()
{ console.log (“Page has loaded”); }
function onpageUnload( )
{ console.log(“Page has unloaded”); }
</script>
<body onload = “onpageLoad()” onunload = “onpageUnload()”> </body> </html >

Function calling another function


Any application can be divided into multiply function, each of which handles a portion of the
application.

function logon()
{ var l_id password, valid ;
l_id = prompt(“Enter user ID: ”);
password = prompt(“Enter password: ”);
valid = validatelogon(id, password);
if(valid === true)
alert (“Valid Credentials”);
else
alert(“Invalid credentials”); }
function validatelogon(id, pass)
{ if (id === ‘111’ && pass === ‘aaa’)
return true;
else
return false; }
Returning a value from function
A function can be designed to do smoothing & then report back to the statement that calls the
function by returning a value to that statement using the return keywords; followed by a return
value in a statement.

Write a program to print sum of digits of user entered value using recursive function.
function sumOfDigits(num)
{
if (num < 10)
return num;
return (num % 10) + sumOfDigits(Math.floor(num / 10));
}
let number = parseInt(prompt("Enter a positive integer:"));
if (isNaN(number) || number < 0)
alert('Please enter a valid positive integer.');
else
{
const result = sumOfDigits(number);
alert("The sum of the digits is: " +result);
}

Strings
A string is a datatype used to represent a sequence of characters. Strings can include letters
numbers symbols & spaces.
Declaring a string
In JS, a string can be declared using
 single quotes (‘’)
Example: let str = ‘Hello’;
 double quotes (“”)
Example: let str = “John”;
 backticks / template literals (-)
Example: let strl = `hello! ${str}
Welcome to JS`;
Template literal offers following additional features:
1. Multi-line string: Doesn’t require escape characters
2. String interpolation: Expressions can be embedded inside ‘${}’ which are evaluated &
included inside the string.
Common String Methods
1) String Creation & Properties
Function/Property Description
String() Creates a new string object.
.length Returns the length of the string.
String.raw() Returns a raw string representation, often used in template literals.

2) String Modification
Function Description
.concat() Combines two or more strings and returns a new string.
.repeat() Repeats the string a specified number of times.
.replace() Replaces a specified value with another value in a string. Supports regular expressions.

.replaceAll() Replaces all occurrences of a specified value in a string with another value.
.slice() Extracts a part of a string and returns it as a new string.
.substring() Returns the part of the string between the start and end indexes.
.substr() Returns a portion of the string, starting at the specified index and extending for a given number of
characters. (Deprecated)
.toLowerCase() Converts the string to lowercase letters.
.toUpperCase() Converts the string to uppercase letters.
.trim() Removes whitespace from both ends of the string.
.trimStart() Removes whitespace from the beginning of the string.
.trimEnd() Removes whitespace from the end of the string.
.padStart() Pads the current string with another string (repeated, if needed) until the resulting string reaches
the given length.
.padEnd() Pads the current string with another string (repeated, if needed) until the resulting string reaches
the given length.
3) String Search & Match
Function Description
.indexOf() Returns the index of the first occurrence of a specified value in the string. Returns -1 if not found.
.lastIndexOf() Returns the index of the last occurrence of a specified value in the string. Returns -1 if not found.
.includes() Checks if a string contains a specified value, returning true or false.
.startsWith() Checks if a string starts with a specified value, returning true or false.
.endsWith() Checks if a string ends with a specified value, returning true or false.
.match() Retrieves the matches when matching a string against a regular expression.
.matchAll() Returns an iterator containing all matches, including capturing groups, when matching a string
against a regular expression.
.search() Searches for a match between a regular expression and this string object.
.localeCompa Compares two strings in the current locale.
re()

4) String Splitting & Joining


Function Description
.split() Splits a string into an array of substrings, using a specified separator string.
.join() Joins all elements of an array into a string, separated by the specified separator. Typically used with arrays,
not strings directly.

5) String Extraction
Function Description
.charAt() Returns the character at a specified index in a string.
.charCodeAt() Returns the Unicode of the character at a specified index in a string.
.codePointAt() Returns the Unicode code point value at a specified index in a string.
.fromCharCode() Returns a string created by using the specified sequence of Unicode values.
.fromCodePoint() Returns a string created by using the specified sequence of code points.
.slice() Extracts a part of a string and returns it as a new string.
.substring() Returns the part of the string between the start and end indexes.
.substr() Returns a portion of the string, starting at the specified index and extending for a given number
of characters. (Deprecated)
6) String Conversion
Function Description
.toString() Returns a string representing the specified object.
.valueOf() Returns the primitive value of a String object.
.toLowerCase() Converts the string to lowercase letters.
.toUpperCase() Converts the string to uppercase letters.
.localeCompare() Compares two strings in the current locale.

7) Template Literals
Feature Description
`${expression}` Allows embedding expressions inside string literals, using backticks.
String.raw Used to get the raw string form of template literals.

8) Advanced String Manipulation (Using Regular Expressions)


Function Description
.replace() Replaces a specified value with another value in a string. Supports regular expressions.
.replaceAll() Replaces all occurrences of a specified value in a string with another value.
.match() Retrieves the matches when matching a string against a regular expression.
.matchAll() Returns an iterator containing all matches, including capturing groups, when matching a string against
a regular expression.
.search() Searches for a match between a regular expression and this string object.
.split() Splits a string into an array of substrings, using a specified separator string or regular expression.

Given string = “I like JavaScript programming”


Write a program to display the above string as “I like JAVASCRIPT programming”.

let str = "I like JavaScript Programming";


let a = str.substr(7, 10);
document.write("<br>" + a);
let b = a.toUpperCase();
document.write("<br>" + b);
document.write("<br> <p style = 'background-color : green;'>" + "I like " + "<b><i>" + b + "</i></b>" + "
Programming</p>");
Given string = “I like JavaScript programming”
Write a program to replace “like” by “know” and divide the string on the basis of space from the 7th index.

let str = "I like JavaScript programming";


document.write("String after replacement: ", str.replace("like", "know"));
document.write("<br> Divided parts from the 7th index: ", str.slice(7).split(" "));

Given string = “I like JavaScript programming”


Write a program to retrieve characters from position 3, 15, 8 and retrieve position of character J, p, a, t. Search for
‘like’ and display results.

let str = "I like JavaScript programming";


document.write("Character at position 3: " ,str.charAt(3));
document.write("<br>Character at position 3: " ,str.charAt(15));
document.write("<br>Character at position 3: " ,str.charAt(8));
document.write("<br>Position of J: " ,str.indexOf('J'));
document.write("<br>Position of p: " ,str.indexOf('p'));
document.write("<br>Position of a: " ,str.indexOf('a'));
document.write("<br>Position of t: " ,str.indexOf('t'));
document.write("<br>Is the word 'like' present in the string? " ,str.includes("like"));

You might also like