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

Client Side Scripting Chapter 2

Css

Uploaded by

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

Client Side Scripting Chapter 2

Css

Uploaded by

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

Client Side Scripting

Notes

Chapter 2 -: Array, Function & String

Define Array -:

In JavaScript, an array is a special type of object used to store multiple values in a single
variable. JavaScript arrays can hold elements of different types and can dynamically resize,
meaning you can add or remove elements after the array is created.

Array Declaration -:

Array declaration is the process of defining an array in a programming language. When you
declare an array, you specify its name, and in some languages, its size and data type. The
array declaration sets aside memory to hold the array's elements.

General Steps in Array Declaration:

1. Specify the Data Type (if applicable): Determine what type of elements the array
will store, such as integers, strings, or objects. Some languages like JavaScript don't
require you to specify the data type explicitly.

JOIN OUR CLASS TO SCORE 95+ CLICK HERE YOUTUBE CHANNEL


2. Provide the Array Name: Choose a name that identifies the array, similar to how
you would name any other variable.
3. Determine the Size (if applicable): In some languages, you need to specify how
many elements the array will hold. This size is fixed once the array is created (e.g., in
C++ or Java). In dynamic languages like JavaScript, the size can change.
4. Initialize the Array (Optional): You can initialize the array with values at the time
of declaration.

In JavaScript, arrays are dynamic, so you don't need to specify the size or data type. The
declaration is straightforward:

let fruits = ["Apple", "Banana", "Cherry"]; // Array with 3 string elements


let numbers = []; // Empty array

Array Initialization

Defining array elements refers to the process of assigning values to the individual positions
(or slots) in an array. Each position in an array is identified by an index, allowing you to store
and access elements in a structured way.

Key Concepts:

1. Indexing:
o Arrays are indexed collections, meaning each element is identified by an index
number.
o Indexes usually start from 0, meaning the first element is at index 0, the
second at index 1, and so on.
2. Element Assignment:
o You define or assign values to specific positions in the array using the index.
o The syntax typically involves the array name, followed by the index in square
brackets, and then the assignment operator (=).
3. Element Types:

JOIN OUR CLASS TO SCORE 95+ CLICK HERE YOUTUBE CHANNEL


o Depending on the language, array elements can be of a single type (e.g.,
integers, strings) or mixed types (as in JavaScript).

let numbers = []; // Declare an empty array


numbers[0] = 10; // Assign 10 to the first element
numbers[1] = 20; // Assign 20 to the second element

// Alternatively, you can define elements during declaration:


let fruits = ["Apple", "Banana", "Cherry"];

Looping an Array -:

Looping through an array is a common operation in programming that involves iterating over
each element of the array, typically to access, modify, or perform some operation on each
element. Most programming languages provide various types of loops to facilitate this.

Common Types of Loops for Iterating Arrays:

1. For Loop:
o A traditional way to loop through an array, especially when you know the
array's length.
o You typically use an index variable to access each element.
2. For-Each Loop:
o A loop designed to iterate over all elements in a collection (like an array)
without using an explicit index.
o Easier to read and write when you don't need the index.
3. While Loop:
o A loop that continues as long as a specified condition is true.
o Less commonly used for simple array iteration but can be useful in certain
cases.

let fruits = ["Apple", "Banana", "Cherry"];

JOIN OUR CLASS TO SCORE 95+ CLICK HERE YOUTUBE CHANNEL


for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]); // Access each element by index
}

Adding an Element in an Array

In JavaScript, you can add elements to an array in several ways, depending on where you
want to place the new element.

Here are the most common methods:

1. Appending an Element to the End of the Array: push()

The push() method adds one or more elements to the end of an array.

let fruits = ["Apple", "Banana"];


fruits.push("Cherry"); // Adds "Cherry" to the end of the array
console.log(fruits); // Outputs: ["Apple", "Banana", "Cherry"]

You can also add multiple elements at once:

fruits.push("Orange", "Mango");
console.log(fruits); // Outputs: ["Apple", "Banana", "Cherry", "Orange", "Mango"]

2. Inserting an Element at the Beginning of the Array: unshift()

The unshift() method adds one or more elements to the beginning of an array.

let fruits = ["Banana", "Cherry"];


fruits.unshift("Apple"); // Adds "Apple" to the beginning of the array
console.log(fruits); // Outputs: ["Apple", "Banana", "Cherry"]

JOIN OUR CLASS TO SCORE 95+ CLICK HERE YOUTUBE CHANNEL


3. Inserting an Element at a Specific Index: splice()

The splice() method can be used to add elements at a specific position in the array.

let fruits = ["Apple", "Banana", "Cherry"];


fruits.splice(1, 0, "Orange"); // Inserts "Orange" at index 1
console.log(fruits); // Outputs: ["Apple", "Orange", "Banana", "Cherry"]

• The first argument is the index where the new element should be inserted.
• The second argument is 0, indicating that no elements should be removed.
• The third argument (and any following arguments) are the elements to be added.

4. Using the Length Property

You can also add an element to the end of an array by assigning it to the index equal to the
current length of the array.

let fruits = ["Apple", "Banana"];


fruits[fruits.length] = "Cherry"; // Adds "Cherry" at the end of the array
console.log(fruits); // Outputs: ["Apple", "Banana", "Cherry"]

5. Concatenating Arrays: concat()

Although not exactly adding a single element, you can create a new array by concatenating
the existing array with another array or single-element array.

let fruits = ["Apple", "Banana"];


let moreFruits = fruits.concat("Cherry"); // Adds "Cherry" to the end of the array and returns
a new array
console.log(moreFruits); // Outputs: ["Apple", "Banana", "Cherry"]

JOIN OUR CLASS TO SCORE 95+ CLICK HERE YOUTUBE CHANNEL


Sorting array element

In JavaScript, you can sort the elements of an array using the sort() method. By default, the
sort() method sorts the elements of an array as strings in alphabetical and ascending order.
However, you can customize the sorting behavior by providing a comparison function.

Basic Sorting with sort()

When sort() is called without any arguments, it converts the array elements to strings and
sorts them lexicographically (alphabetical order).

let fruits = ["Banana", "Apple", "Cherry", "Mango"];


fruits.sort();
console.log(fruits); // Outputs: ["Apple", "Banana", "Cherry", "Mango"]

Sorting Numbers

Since sort() converts array elements to strings by default, sorting numbers can produce
unexpected results (e.g., 10 will come before 2 because "10" is less than "2"
lexicographically). To sort numbers correctly, you need to provide a comparison function.

Ascending Order:
let numbers = [40, 100, 1, 5, 25, 10];
numbers.sort(function(a, b) {
return a - b;
});
console.log(numbers); // Outputs: [1, 5, 10, 25, 40, 100]

Descending Order:
let numbers = [40, 100, 1, 5, 25, 10];
numbers.sort(function(a, b) {
return b - a;
});
console.log(numbers); // Outputs: [100, 40, 25, 10, 5, 1]

JOIN OUR CLASS TO SCORE 95+ CLICK HERE YOUTUBE CHANNEL


Function in Java Script

In JavaScript, a function is a block of code designed to perform a specific task. Functions are
one of the fundamental building blocks in JavaScript and are used to encapsulate code that
can be reused, executed, and invoked with different inputs.

Key Concepts of Functions in JavaScript:

1. Function Declaration: Defines a named function that can be called later.


2. Function Expression: Defines a function as part of an expression, often anonymous,
and can be assigned to a variable.
3. Arrow Function: A more concise syntax introduced in ES6 for writing functions.
4. Parameters and Arguments: Functions can take inputs (parameters) and use them
within the function.
5. Return Value: Functions can return a value to the caller using the return keyword.

Function Declaration

A function declaration creates a function with a specified name.

function functionName(parameters) {
// Code to be executed
}

Function Calling

In JavaScript, calling a function involves invoking or executing the function to perform the
task it was designed for. Once a function is defined, you can call it to run its code. Here’s
how you can do it:

Basic Function Call

Syntax:

JOIN OUR CLASS TO SCORE 95+ CLICK HERE YOUTUBE CHANNEL


functionName(arguments);

Example:
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Outputs: "Hello, Alice!"

Function Call with Arguments

When calling a function, you pass arguments that correspond to the function's parameters.

Example:
function add(a, b) {
return a + b;
}
let sum = add(5, 10);
console.log(sum); // Outputs: 15

Calling Functions Immediately

Immediately Invoked Function Expression (IIFE):

An IIFE is a function that runs as soon as it is defined. It’s a common pattern used to create a
local scope.

Syntax:
(function() {
// Code here runs immediately
})();

Example:
(function() {
console.log("This runs immediately!");

JOIN OUR CLASS TO SCORE 95+ CLICK HERE YOUTUBE CHANNEL


})();

Function Call with Return Values

When a function has a return value, you can use it directly in expressions or assign it to
variables.

Example:
function multiply(a, b) {
return a * b;
}
let result = multiply(4, 5);
console.log(result); // Outputs: 20

Function Call with Default Parameters

JavaScript functions can have default parameters, which are used if no argument is provided.

Example:
function greet(name = "Guest") {
console.log("Hello, " + name + "!");
}
greet(); // Outputs: "Hello, Guest!"
greet("Bob"); // Outputs: "Hello, Bob!"

Function Call with this Context

When a function is called as a method of an object, the this keyword refers to the object that
owns the method.

Example:

const person = {

name: "John",
greet: function() {

JOIN OUR CLASS TO SCORE 95+ CLICK HERE YOUTUBE CHANNEL


console.log("Hello, " + this.name + "!");
}
};

person.greet(); // Outputs: "Hello, John!"

String in Java Script

In JavaScript, a string is a sequence of characters used to represent text. Strings are a fundamental
data type and are used to store and manipulate textual data. JavaScript strings are immutable,
meaning once a string is created, it cannot be changed, but you can create new strings based on
existing ones.

String methods

JavaScript provides a rich set of methods for working with strings. These methods allow you
to perform various operations such as searching, manipulating, and transforming strings.
Here’s a comprehensive overview of commonly used string methods in JavaScript:

1. charAt(index)

Returns the character at a specified index in a string.

let str = "JavaScript";


console.log(str.charAt(4)); // Outputs: "S"

2. charCodeAt(index)

Returns the Unicode character code at a specified index.

let str = "JavaScript";


console.log(str.charCodeAt(4)); // Outputs: 83 (Unicode value for "S")

JOIN OUR CLASS TO SCORE 95+ CLICK HERE YOUTUBE CHANNEL


3. concat(...strings)

Combines multiple strings into one.

let str1 = "Hello";


let str2 = "World";
let result = str1.concat(", ", str2);
console.log(result); // Outputs: "Hello, World"

4. includes(searchValue, position)

Checks if a string contains a specified value, optionally starting the search from a given
position.

let str = "JavaScript is fun";


console.log(str.includes("fun")); // Outputs: true
console.log(str.includes("fun", 15)); // Outputs: false

5. indexOf(searchValue, fromIndex)

Returns the index of the first occurrence of a specified value, starting the search from a given
index.

let str = "JavaScript is fun";


console.log(str.indexOf("is")); // Outputs: 11
console.log(str.indexOf("is", 12)); // Outputs: -1

6. lastIndexOf(searchValue, fromIndex)

Returns the index of the last occurrence of a specified value, searching backwards from a
given index.

let str = "JavaScript is fun";


console.log(str.lastIndexOf("is")); // Outputs: 11

7. slice(start, end)

Extracts a portion of the string between start and end (not including end).

JOIN OUR CLASS TO SCORE 95+ CLICK HERE YOUTUBE CHANNEL


let str = "JavaScript";
console.log(str.slice(0, 4)); // Outputs: "Java"
console.log(str.slice(-6)); // Outputs: "Script"

8. substring(start, end)

Extracts a portion of the string between start and end (not including end). Unlike slice(), it
does not accept negative indices.

let str = "JavaScript";


console.log(str.substring(0, 4)); // Outputs: "Java"

9. substr(start, length)

Extracts a substring starting at start and extending for length characters.

let str = "JavaScript";


console.log(str.substr(0, 4)); // Outputs: "Java"

10. toLowerCase()

Converts all characters in the string to lowercase.

let str = "JavaScript";


console.log(str.toLowerCase()); // Outputs: "javascript"

11. toUpperCase()

Converts all characters in the string to uppercase.

let str = "JavaScript";


console.log(str.toUpperCase()); // Outputs: "JAVASCRIPT"

12. trim()

Removes whitespace from both ends of the string.

let str = " JavaScript ";


console.log(str.trim()); // Outputs: "JavaScript"

JOIN OUR CLASS TO SCORE 95+ CLICK HERE YOUTUBE CHANNEL


13. replace(searchValue, newValue)

Replaces the first occurrence of a specified value with a new value.

let str = "JavaScript is fun";


console.log(str.replace("fun", "awesome")); // Outputs: "JavaScript is awesome"

14. replaceAll(searchValue, newValue)

Replaces all occurrences of a specified value with a new value (introduced in ES2021).

let str = "JavaScript is fun and JavaScript is great";


console.log(str.replaceAll("JavaScript", "JS")); // Outputs: "JS is fun and JS is great"

15. split(separator, limit)

Splits the string into an array of substrings based on a separator.

let str = "JavaScript,Python,Java";


console.log(str.split(",")); // Outputs: ["JavaScript", "Python", "Java"]
console.log(str.split(",", 2)); // Outputs: ["JavaScript", "Python"]

16. startsWith(searchString, position)

Checks if the string starts with a specified value, optionally starting the search from a given
position.

let str = "JavaScript is fun";


console.log(str.startsWith("Java")); // Outputs: true
console.log(str.startsWith("Script", 4)); // Outputs: true

17. endsWith(searchString, length)

Checks if the string ends with a specified value, optionally considering a specified length.

let str = "JavaScript is fun";


console.log(str.endsWith("fun")); // Outputs: true
console.log(str.endsWith("is", 16)); // Outputs: true

JOIN OUR CLASS TO SCORE 95+ CLICK HERE YOUTUBE CHANNEL


18. repeat(count)

Returns a new string with a specified number of copies of the original string.

let str = "Hello";


console.log(str.repeat(3)); // Outputs: "HelloHelloHello"

JOIN OUR CLASS TO SCORE 95+ CLICK HERE YOUTUBE CHANNEL

You might also like