SlideShare a Scribd company logo
JavaScript
Functions
• Functions are the building block for modular code in JavaScript
• They are defined by using the reserved word function and then the function name and
(optional) parameters.
• Since JavaScript is dynamically typed, functions do not require a return type, nor do the
parameters require type.
Module 2 Javascript. Advanced concepts of javascript
Scope in JavaScript
Scope determines the accessibility (visibility) of variables, functions, and objects in some
particular part of your code during runtime.
1. Global Scope
• Variables declared outside of any function or block have global scope.
• They can be accessed from any part of the code, including inside functions.
• In a browser environment, global variables become properties of the window object.
2. Local Scope (Function Scope and Block Scope)
Variables declared inside a function or a block have local scope.
They are only accessible within that specific function or block.
a. Function Scope (Variables declared with var)
• Variables declared with var inside a function are function-scoped.
• They are accessible throughout that function, but not outside it.
b. Block Scope (Variables declared with let and const)
• Introduced in ES6 (ECMAScript 2015), let and const keywords introduce block scope.
• A block is any code enclosed within curly braces {} (e.g., if statements, for loops, while
loops, functions).
• Variables declared with let or const are only accessible within the block they are
defined in.
Arrays
Arrays are one of the most used data structures, and they have been included in
JavaScript as well.
An array is a special type of variable that can store multiple values, or "elements," in a
single variable. Arrays are ordered collections, meaning each element has a specific
position (index).
Array Creation
There are several ways to create arrays in JavaScript:
• Array Literal (Most Common)
• Array() Constructor
Array Literal (Most Common)
This is the simplest and most preferred way to create an array. You enclose a comma-separated
list of values in square brackets []
// An array of numbers
let numbers = [1, 2, 3, 4, 5];
// An array of strings
let fruits = ["apple", "banana", "cherry"];
// An array with mixed data types (JavaScript allows this)
let mixedArray = [10, "hello", true, null, { key: "value" }];
// An empty array
let emptyArray = [];
Array() Constructor
You can also use the Array() constructor.
With arguments: If you pass arguments, they become elements of the array.
let colors = new Array("red", "green", "blue");
console.log(colors); // Output: ["red", "green", "blue"]
With a single number argument: If you pass a single number, it creates an
empty array with that specified length (but no actual elements).
let zeroedArray = new Array(5); // Creates an array of 5 empty slots
console.log(zeroedArray); // Output: [empty × 5]
console.log(zeroedArray.length); // Output: 5
Indexing (Accessing Elements)
Array elements are accessed using a zero-based index. This means the first element is at index
0, the second at 1, and so on.
Array Methods
JavaScript provides a rich set of built-in methods for manipulating arrays. Here,
we'll focus on push, pop, splice, and sort.
a. push()
• Purpose: Adds one or more elements to the end of an array.
• Return Value: The new length of the array.
• Modifies Original Array: Yes.
let fruits = ["apple", "banana"];
console.log("Original fruits:", fruits); // Output: ["apple", "banana"]
let newLength1 = fruits.push("cherry");
console.log("After push 'cherry':", fruits); // Output: ["apple", "banana", "cherry"]
console.log("New length:", newLength1); // Output: 3
let newLength2 = fruits.push("grape", "kiwi");
console.log("After push 'grape', 'kiwi':", fruits); // Output: ["apple", "banana", "cherry",
"grape", "kiwi"]
console.log("New length:", newLength2); // Output: 5
pop()
• Purpose: Removes the last element from an array.
• Return Value: The removed element.
• Modifies Original Array: Yes.
let vegetables = ["carrot", "broccoli", "spinach", "potato"];
console.log("Original vegetables:", vegetables); // Output: ["carrot", "broccoli", "spinach", "potato"]
let removedVeg1 = vegetables.pop();
console.log("After pop 1:", vegetables); // Output: ["carrot", "broccoli", "spinach"]
console.log("Removed element:", removedVeg1); // Output: "potato"
Splice()
• The splice() method adds and/or removes array elements.
• The splice() method overwrites the original array.
Syntax
array.splice(index, count, item1, ....., it
emX)
Parameter Description
index Required.
The index (position) to add or remove items.
A negative value counts from the end of the array.
count Optional.
Number of items to be removed.
item1, ..., Optional.
The new elements(s) to be added.
Type Description
Array An array containing the removed
items (if any).
Return Value
// Create an Array
const fruits =
["Banana", "Orange", "Apple", "Mango"];
// At position 2, remove 2 items
fruits.splice(2, 2);
// Create an Array
const fruits =
["Banana", "Orange", "Apple", "Mango"];
// At position 2, remove 1 item, add
"Lemon" and "Kiwi"
fruits.splice(2, 1, "Lemon", "Kiwi");
sort()
• Purpose: Sorts the elements of an array in place.
• Return Value: The sorted array (the original array is modified).
• Modifies Original Array: Yes.
Default Behavior (String Sort):
By default, sort() converts elements to strings and sorts them alphabetically (lexicographically). This can lead to unexpected
results for numbers.
Syntax
array.sort(compareFunction)
Parameter Description
compareFunction •Optional.
A function that defines a sort order. The function should return a negative, zero, or
positive value, depending on the arguments:
function(a, b){
return a-b
}
When sort() compares two values, it sends the values to the compare function, and
sorts the values according to the returned (negative, zero, positive) value.
compareFunction(a, b) rules:
• If compareFunction(a, b) returns < 0, a comes before b.
• If compareFunction(a, b) returns 0, a and b maintain their relative order.
• If compareFunction(a, b) returns > 0, b comes before a.For ascending numerical sort: return a - b;For
descending numerical sort: return b - a;
// Create an Array
const fruits =
["Banana", "Orange", "Apple", "Mango"];
// Sort the Array
fruits.sort();
Sort numbers in ascending order:
// Create an Array
const points = [40, 100, 1, 5, 25, 10];
// Sort the Array
points.sort(function(a, b){return a-b});
Sort numbers in descending order:
// Create an Array
const points = [40, 100, 1, 5, 25, 10];
// Sort the Array
points.sort(function(a, b){return b-a});
Pattern Matching
• A regular expression is a sequence of characters that forms a search pattern.
• When you search for data in a text, you can use this search pattern to describe what you are searching for.
• A regular expression can be a single character, or a more complicated pattern.
• Regular expressions can be used to perform all types of text search and text replace operations.
Creating Regular Expressions
There are two main ways to create a regular expression
RegExp Literal (Most Common):
You enclose the pattern in forward slashes /. This is generally preferred when the pattern is static and known
at development time.
const pattern1 = /hello/; // Matches the literal string "hello“
const pattern2 = /[0-9]+/; // Matches one or more digits
RegExp Constructor:
You use the RegExp constructor, passing the pattern as a string and flags as a second-string argument. This is
useful when the pattern is dynamic (e.g., comes from user input or a variable).
const searchTerm = "world";
const dynamicPattern = new RegExp(searchTerm); // Matches "world“
const dynamicCaseInsensitiveGlobal = new RegExp("banana", "gi");
Basic RegExp Usage
Once you have a regular expression, you can use it with various methods to perform pattern matching.
We'll focus on test() and match().
1. RegExp.prototype.test()
• Purpose: Tests for a match in a string.
• Return Value: Returns true if there is at least one match, otherwise false.
• Modifies Original String: No.
• Called On: The RegExp object.
String.prototype.match()
Purpose: Retrieves the result of matching a string against a regular expression.
Return Value:
• If the regex has the g (global) flag: Returns an Array containing all matches as strings, or null if no matches are
found.
• If the regex does not have the g flag: Returns an Array similar to the RegExp.prototype.exec() method. This
array will contain the full match as the first element, followed by any captured groups, along with properties
like index (start position of the match) and input (the original string). Returns null if no match is found.
Modifies Original String: No.
Called On: The String object.
Simple pattern validation: email, phone numbers
Email validation aims to check if a string broadly resembles an email address.
Common Requirements for a Simple Email Pattern:
• Presence of @ symbol: An email address must contain an "@" symbol.
• Something before @: There should be at least one character (or more) before the "@"
symbol (local part).
• Something after @: There should be at least one character (or more) after the "@" symbol
(domain part).
• Presence of . in domain: The domain part typically contains at least one dot (.).
• Top-Level Domain (TLD): The part after the last dot in the domain should be at least two
characters long (e.g., .com, .org, .in).
/^[a-zA-Z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,}$/;
function validateEmail(email) {
let emailPattern = /^[a-zA-Z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,}$/;
return emailPattern.test(email);
}
^
Start of the string
[a-zA-Z0-9._%+-]+
Matches the local part (before the @)
Allowed characters:
• a-z, A-Z: letters
• 0-9: digits
• . _ % + -: common special characters
+: one or more of these characters
@
Matches the @ symbol literally
[a-z0-9.-]+
Matches the domain name (after the @, before the final .)
Allowed characters:
• a-z: lowercase letters
• 0-9: digits
• . and -: dots and hyphens (e.g., gmail.com, abc-xyz.in)
+: one or more characters
.
Matches the dot (.) before the domain extension like .com, .in
[a-z]{2,}
• Matches the domain extension
• Only lowercase letters allowed (a-z)
• {2,}: at least 2 letters, e.g., com, in, org
$
End of the string
let phonePattern = /^[6-9]d{9}$/;
Starts with 6–9
Followed by 9 digits
function validatePhone(phone) {
let phonePattern = /^[6-9]d{9}$/;
return phonePattern.test(phone);
}
DOM
The Document Object Model (DOM) is a fundamental concept in web development. It's the
programming interface for web documents (like HTML or XML). Think of it as a structured,
object-oriented representation of the web page, allowing programs (like JavaScript) to access
and manipulate its content, structure, and style.
Accessing elements: getElementById, getElementsByClassName, querySelector
These methods are essential for selecting specific elements on a web page so you can
manipulate their content, style, or behavior.
document.getElementById(id)
Purpose: This is the most direct and efficient way to access a single HTML element.
Selection Criteria: It selects an element by its unique id attribute.
Return Value:
If an element with the specified id is found, it returns that single element object.
If no element with the specified id is found, it returns null.
<p id="demo">Hello</p>
<script>
let para = document.getElementById("demo");
console.log(para.textContent); // Output: Hello
</script>
getElementsByClassName
Use : To get multiple elements that share the same class
<p class="info">Paragraph 1</p>
<p class="info">Paragraph 2</p>
<script>
let items = document.getElementsByClassName("info");
console.log(items[0].textContent); // Output: Paragraph 1
</script>
querySelector
Purpose: A more modern and flexible method to select the first element that matches a
specified CSS selector.
Selection Criteria: It takes a CSS selector string as an argument. This means you can select
by ID, class, tag name, attribute, or any complex combination of these, just like you would
in a CSS stylesheet.
Return Value:
If one or more elements match the selector, it returns the first matching element
object.
If no element matches, it returns null.
<p class="msg">Hello</p>
<p class="msg">Hi</p>
<script>
let firstMsg = document.querySelector(".msg");
console.log(firstMsg.textContent); // Output: Hello
</script>
document.querySelectorAll(selector)
Purpose: Similar to querySelector, but it selects all elements that match the specified CSS selector.
What is Event Handling?
Event handling is how you make your webpage respond to user interactions like clicks, mouse movements, or form
input changes.
button onclick="alert('Button clicked!')">Click Me</button>
<button onclick="myFunction()">Execute Function</button>
<script> function myFunction()
{
console.log("My function was called!“);
}
</script>
button id="myButton">Click Me</button>
<script>
const button = document.getElementById('myButton’);
button.onclick = function()
{ console.log("Button clicked via JS property!"); }; // You can also assign a named function
function handleButtonClick()
{ console.log("Another way to handle click!"); } //
button.onclick = handleButtonClick; // This would replace the previous handler </script>
Onmouseover
Purpose: Fires when the mouse pointer enters the element's
area.
Usage: Similar to onclick.
In HTML
<div
onmouseover="this.style.backgroundColor='lightblue'">Hover
Over Me</div>
element.addEventListener(event, handler, [options]);
• element: The DOM element to which you want to attach the listener.
• event: A string representing the event type (e.g., 'click', 'mouseover',
'change', 'submit', 'keydown'). Do not include "on" prefix.
• handler: The function that will be executed when the event occurs.
This function automatically receives an Event object as its first
argument, containing details about the event.
• [options] (optional): An object that can specify capture (boolean),
once (boolean), passive (boolean).
<button id="clickBtn">Click</button>
<script>
document.getElementById("clickBtn").addEventListener("cl
ick", function() {
alert("Clicked with addEventListener!");
});
</script>

More Related Content

Similar to Module 2 Javascript. Advanced concepts of javascript (20)

PDF
React Native Evening
Troy Miles
 
PPTX
Java script advance-auroskills (2)
BoneyGawande
 
PDF
JavaScript Array Interview Questions PDF By ScholarHat
Scholarhat
 
PPS
CS101- Introduction to Computing- Lecture 29
Bilal Ahmed
 
PPT
Java Script Introduction
jason hu 金良胡
 
PDF
Angular Weekend
Troy Miles
 
PDF
React Native One Day
Troy Miles
 
PPSX
javascript-Array.ppsx
VedantSaraf9
 
PPTX
The JavaScript Programming Language
Mohammed Irfan Shaikh
 
PDF
Handout - Introduction to Programming
Cindy Royal
 
PDF
Fewd week5 slides
William Myers
 
PDF
javascript objects
Vijay Kalyan
 
PPTX
JavaScript.pptx
KennyPratheepKumar
 
PPTX
ES6 and BEYOND
Brian Patterson
 
PDF
Node Boot Camp
Troy Miles
 
PPS
CS101- Introduction to Computing- Lecture 26
Bilal Ahmed
 
PPT
POLITEKNIK MALAYSIA
Aiman Hud
 
PPT
javascript arrays in details for udergaduate studenets .ppt
debasisdas225831
 
PPTX
Javascript
Prashant Kumar
 
PPTX
Java script
Adrian Caetano
 
React Native Evening
Troy Miles
 
Java script advance-auroskills (2)
BoneyGawande
 
JavaScript Array Interview Questions PDF By ScholarHat
Scholarhat
 
CS101- Introduction to Computing- Lecture 29
Bilal Ahmed
 
Java Script Introduction
jason hu 金良胡
 
Angular Weekend
Troy Miles
 
React Native One Day
Troy Miles
 
javascript-Array.ppsx
VedantSaraf9
 
The JavaScript Programming Language
Mohammed Irfan Shaikh
 
Handout - Introduction to Programming
Cindy Royal
 
Fewd week5 slides
William Myers
 
javascript objects
Vijay Kalyan
 
JavaScript.pptx
KennyPratheepKumar
 
ES6 and BEYOND
Brian Patterson
 
Node Boot Camp
Troy Miles
 
CS101- Introduction to Computing- Lecture 26
Bilal Ahmed
 
POLITEKNIK MALAYSIA
Aiman Hud
 
javascript arrays in details for udergaduate studenets .ppt
debasisdas225831
 
Javascript
Prashant Kumar
 
Java script
Adrian Caetano
 

Recently uploaded (20)

PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PDF
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
PDF
People & Earth's Ecosystem -Lesson 2: People & Population
marvinnbustamante1
 
PPTX
Quarter1-English3-W4-Identifying Elements of the Story
FLORRACHELSANTOS
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PPSX
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
PDF
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PDF
community health nursing question paper 2.pdf
Prince kumar
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PPTX
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PPSX
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
People & Earth's Ecosystem -Lesson 2: People & Population
marvinnbustamante1
 
Quarter1-English3-W4-Identifying Elements of the Story
FLORRACHELSANTOS
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
community health nursing question paper 2.pdf
Prince kumar
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
Ad

Module 2 Javascript. Advanced concepts of javascript

  • 2. Functions • Functions are the building block for modular code in JavaScript • They are defined by using the reserved word function and then the function name and (optional) parameters. • Since JavaScript is dynamically typed, functions do not require a return type, nor do the parameters require type.
  • 4. Scope in JavaScript Scope determines the accessibility (visibility) of variables, functions, and objects in some particular part of your code during runtime. 1. Global Scope • Variables declared outside of any function or block have global scope. • They can be accessed from any part of the code, including inside functions. • In a browser environment, global variables become properties of the window object.
  • 5. 2. Local Scope (Function Scope and Block Scope) Variables declared inside a function or a block have local scope. They are only accessible within that specific function or block. a. Function Scope (Variables declared with var) • Variables declared with var inside a function are function-scoped. • They are accessible throughout that function, but not outside it.
  • 6. b. Block Scope (Variables declared with let and const) • Introduced in ES6 (ECMAScript 2015), let and const keywords introduce block scope. • A block is any code enclosed within curly braces {} (e.g., if statements, for loops, while loops, functions). • Variables declared with let or const are only accessible within the block they are defined in.
  • 7. Arrays Arrays are one of the most used data structures, and they have been included in JavaScript as well. An array is a special type of variable that can store multiple values, or "elements," in a single variable. Arrays are ordered collections, meaning each element has a specific position (index). Array Creation There are several ways to create arrays in JavaScript: • Array Literal (Most Common) • Array() Constructor
  • 8. Array Literal (Most Common) This is the simplest and most preferred way to create an array. You enclose a comma-separated list of values in square brackets [] // An array of numbers let numbers = [1, 2, 3, 4, 5]; // An array of strings let fruits = ["apple", "banana", "cherry"]; // An array with mixed data types (JavaScript allows this) let mixedArray = [10, "hello", true, null, { key: "value" }]; // An empty array let emptyArray = [];
  • 9. Array() Constructor You can also use the Array() constructor. With arguments: If you pass arguments, they become elements of the array. let colors = new Array("red", "green", "blue"); console.log(colors); // Output: ["red", "green", "blue"] With a single number argument: If you pass a single number, it creates an empty array with that specified length (but no actual elements). let zeroedArray = new Array(5); // Creates an array of 5 empty slots console.log(zeroedArray); // Output: [empty × 5] console.log(zeroedArray.length); // Output: 5
  • 10. Indexing (Accessing Elements) Array elements are accessed using a zero-based index. This means the first element is at index 0, the second at 1, and so on.
  • 11. Array Methods JavaScript provides a rich set of built-in methods for manipulating arrays. Here, we'll focus on push, pop, splice, and sort. a. push() • Purpose: Adds one or more elements to the end of an array. • Return Value: The new length of the array. • Modifies Original Array: Yes.
  • 12. let fruits = ["apple", "banana"]; console.log("Original fruits:", fruits); // Output: ["apple", "banana"] let newLength1 = fruits.push("cherry"); console.log("After push 'cherry':", fruits); // Output: ["apple", "banana", "cherry"] console.log("New length:", newLength1); // Output: 3 let newLength2 = fruits.push("grape", "kiwi"); console.log("After push 'grape', 'kiwi':", fruits); // Output: ["apple", "banana", "cherry", "grape", "kiwi"] console.log("New length:", newLength2); // Output: 5
  • 13. pop() • Purpose: Removes the last element from an array. • Return Value: The removed element. • Modifies Original Array: Yes. let vegetables = ["carrot", "broccoli", "spinach", "potato"]; console.log("Original vegetables:", vegetables); // Output: ["carrot", "broccoli", "spinach", "potato"] let removedVeg1 = vegetables.pop(); console.log("After pop 1:", vegetables); // Output: ["carrot", "broccoli", "spinach"] console.log("Removed element:", removedVeg1); // Output: "potato"
  • 14. Splice() • The splice() method adds and/or removes array elements. • The splice() method overwrites the original array. Syntax array.splice(index, count, item1, ....., it emX) Parameter Description index Required. The index (position) to add or remove items. A negative value counts from the end of the array. count Optional. Number of items to be removed. item1, ..., Optional. The new elements(s) to be added.
  • 15. Type Description Array An array containing the removed items (if any). Return Value // Create an Array const fruits = ["Banana", "Orange", "Apple", "Mango"]; // At position 2, remove 2 items fruits.splice(2, 2); // Create an Array const fruits = ["Banana", "Orange", "Apple", "Mango"]; // At position 2, remove 1 item, add "Lemon" and "Kiwi" fruits.splice(2, 1, "Lemon", "Kiwi");
  • 16. sort() • Purpose: Sorts the elements of an array in place. • Return Value: The sorted array (the original array is modified). • Modifies Original Array: Yes. Default Behavior (String Sort): By default, sort() converts elements to strings and sorts them alphabetically (lexicographically). This can lead to unexpected results for numbers. Syntax array.sort(compareFunction)
  • 17. Parameter Description compareFunction •Optional. A function that defines a sort order. The function should return a negative, zero, or positive value, depending on the arguments: function(a, b){ return a-b } When sort() compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value. compareFunction(a, b) rules: • If compareFunction(a, b) returns < 0, a comes before b. • If compareFunction(a, b) returns 0, a and b maintain their relative order. • If compareFunction(a, b) returns > 0, b comes before a.For ascending numerical sort: return a - b;For descending numerical sort: return b - a;
  • 18. // Create an Array const fruits = ["Banana", "Orange", "Apple", "Mango"]; // Sort the Array fruits.sort(); Sort numbers in ascending order: // Create an Array const points = [40, 100, 1, 5, 25, 10]; // Sort the Array points.sort(function(a, b){return a-b}); Sort numbers in descending order: // Create an Array const points = [40, 100, 1, 5, 25, 10]; // Sort the Array points.sort(function(a, b){return b-a});
  • 19. Pattern Matching • A regular expression is a sequence of characters that forms a search pattern. • When you search for data in a text, you can use this search pattern to describe what you are searching for. • A regular expression can be a single character, or a more complicated pattern. • Regular expressions can be used to perform all types of text search and text replace operations. Creating Regular Expressions There are two main ways to create a regular expression RegExp Literal (Most Common): You enclose the pattern in forward slashes /. This is generally preferred when the pattern is static and known at development time.
  • 20. const pattern1 = /hello/; // Matches the literal string "hello“ const pattern2 = /[0-9]+/; // Matches one or more digits RegExp Constructor: You use the RegExp constructor, passing the pattern as a string and flags as a second-string argument. This is useful when the pattern is dynamic (e.g., comes from user input or a variable). const searchTerm = "world"; const dynamicPattern = new RegExp(searchTerm); // Matches "world“ const dynamicCaseInsensitiveGlobal = new RegExp("banana", "gi");
  • 21. Basic RegExp Usage Once you have a regular expression, you can use it with various methods to perform pattern matching. We'll focus on test() and match(). 1. RegExp.prototype.test() • Purpose: Tests for a match in a string. • Return Value: Returns true if there is at least one match, otherwise false. • Modifies Original String: No. • Called On: The RegExp object.
  • 22. String.prototype.match() Purpose: Retrieves the result of matching a string against a regular expression. Return Value: • If the regex has the g (global) flag: Returns an Array containing all matches as strings, or null if no matches are found. • If the regex does not have the g flag: Returns an Array similar to the RegExp.prototype.exec() method. This array will contain the full match as the first element, followed by any captured groups, along with properties like index (start position of the match) and input (the original string). Returns null if no match is found. Modifies Original String: No. Called On: The String object.
  • 23. Simple pattern validation: email, phone numbers Email validation aims to check if a string broadly resembles an email address. Common Requirements for a Simple Email Pattern: • Presence of @ symbol: An email address must contain an "@" symbol. • Something before @: There should be at least one character (or more) before the "@" symbol (local part). • Something after @: There should be at least one character (or more) after the "@" symbol (domain part). • Presence of . in domain: The domain part typically contains at least one dot (.). • Top-Level Domain (TLD): The part after the last dot in the domain should be at least two characters long (e.g., .com, .org, .in).
  • 24. /^[a-zA-Z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,}$/; function validateEmail(email) { let emailPattern = /^[a-zA-Z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,}$/; return emailPattern.test(email); }
  • 25. ^ Start of the string [a-zA-Z0-9._%+-]+ Matches the local part (before the @) Allowed characters: • a-z, A-Z: letters • 0-9: digits • . _ % + -: common special characters +: one or more of these characters @ Matches the @ symbol literally
  • 26. [a-z0-9.-]+ Matches the domain name (after the @, before the final .) Allowed characters: • a-z: lowercase letters • 0-9: digits • . and -: dots and hyphens (e.g., gmail.com, abc-xyz.in) +: one or more characters . Matches the dot (.) before the domain extension like .com, .in
  • 27. [a-z]{2,} • Matches the domain extension • Only lowercase letters allowed (a-z) • {2,}: at least 2 letters, e.g., com, in, org $ End of the string
  • 28. let phonePattern = /^[6-9]d{9}$/; Starts with 6–9 Followed by 9 digits function validatePhone(phone) { let phonePattern = /^[6-9]d{9}$/; return phonePattern.test(phone); }
  • 29. DOM The Document Object Model (DOM) is a fundamental concept in web development. It's the programming interface for web documents (like HTML or XML). Think of it as a structured, object-oriented representation of the web page, allowing programs (like JavaScript) to access and manipulate its content, structure, and style.
  • 30. Accessing elements: getElementById, getElementsByClassName, querySelector These methods are essential for selecting specific elements on a web page so you can manipulate their content, style, or behavior. document.getElementById(id) Purpose: This is the most direct and efficient way to access a single HTML element. Selection Criteria: It selects an element by its unique id attribute. Return Value: If an element with the specified id is found, it returns that single element object. If no element with the specified id is found, it returns null.
  • 31. <p id="demo">Hello</p> <script> let para = document.getElementById("demo"); console.log(para.textContent); // Output: Hello </script> getElementsByClassName Use : To get multiple elements that share the same class <p class="info">Paragraph 1</p> <p class="info">Paragraph 2</p> <script> let items = document.getElementsByClassName("info"); console.log(items[0].textContent); // Output: Paragraph 1 </script>
  • 32. querySelector Purpose: A more modern and flexible method to select the first element that matches a specified CSS selector. Selection Criteria: It takes a CSS selector string as an argument. This means you can select by ID, class, tag name, attribute, or any complex combination of these, just like you would in a CSS stylesheet. Return Value: If one or more elements match the selector, it returns the first matching element object. If no element matches, it returns null.
  • 33. <p class="msg">Hello</p> <p class="msg">Hi</p> <script> let firstMsg = document.querySelector(".msg"); console.log(firstMsg.textContent); // Output: Hello </script> document.querySelectorAll(selector) Purpose: Similar to querySelector, but it selects all elements that match the specified CSS selector.
  • 34. What is Event Handling? Event handling is how you make your webpage respond to user interactions like clicks, mouse movements, or form input changes. button onclick="alert('Button clicked!')">Click Me</button> <button onclick="myFunction()">Execute Function</button> <script> function myFunction() { console.log("My function was called!“); } </script> button id="myButton">Click Me</button> <script> const button = document.getElementById('myButton’); button.onclick = function() { console.log("Button clicked via JS property!"); }; // You can also assign a named function function handleButtonClick() { console.log("Another way to handle click!"); } // button.onclick = handleButtonClick; // This would replace the previous handler </script>
  • 35. Onmouseover Purpose: Fires when the mouse pointer enters the element's area. Usage: Similar to onclick. In HTML <div onmouseover="this.style.backgroundColor='lightblue'">Hover Over Me</div>
  • 36. element.addEventListener(event, handler, [options]); • element: The DOM element to which you want to attach the listener. • event: A string representing the event type (e.g., 'click', 'mouseover', 'change', 'submit', 'keydown'). Do not include "on" prefix. • handler: The function that will be executed when the event occurs. This function automatically receives an Event object as its first argument, containing details about the event. • [options] (optional): An object that can specify capture (boolean), once (boolean), passive (boolean).