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

PPTX
Taxonomy of Scala
shinolajla
 
PPTX
Java script advance-auroskills (2)
BoneyGawande
 
PPTX
JavaScript.pptx
Govardhan Bhavani
 
PPTX
Introduction to Client-Side Javascript
Julie Iskander
 
PPTX
17-Arrays-And-Files-kkkkkkkkkkkkkkk.pptx
kamalsmail1
 
PPTX
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Maulik Borsaniya
 
PPT
Introduction to Boost regex
Yongqiang Li
 
PDF
JavaScript(Es5) Interview Questions & Answers
Ratnala Charan kumar
 
Taxonomy of Scala
shinolajla
 
Java script advance-auroskills (2)
BoneyGawande
 
JavaScript.pptx
Govardhan Bhavani
 
Introduction to Client-Side Javascript
Julie Iskander
 
17-Arrays-And-Files-kkkkkkkkkkkkkkk.pptx
kamalsmail1
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Maulik Borsaniya
 
Introduction to Boost regex
Yongqiang Li
 
JavaScript(Es5) Interview Questions & Answers
Ratnala Charan kumar
 

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

PPTX
Aggregate.pptx
Ramakrishna Reddy Bijjam
 
PPTX
Python basics
Hoang Nguyen
 
PPTX
Python basics
Young Alista
 
PPTX
Python basics
Harry Potter
 
PPTX
Python basics
Fraboni Ec
 
PPTX
Python basics
Tony Nguyen
 
PPTX
Python basics
James Wong
 
PPTX
Python basics
Luis Goldster
 
PPSX
Javascript variables and datatypes
Varun C M
 
PPTX
CAP615-Unit1.pptx
SatyajeetGaur3
 
PPTX
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Dhivyaa C.R
 
PPTX
UNIT IV (4).pptx
DrDhivyaaCRAssistant
 
PPTX
Variables
Jesus Obenita Jr.
 
PPT
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
PPTX
The ES Library for JavaScript Developers
Ganesh Bhosale
 
PPTX
Array and functions
Sun Technlogies
 
PPTX
Matlab Functions
Umer Azeem
 
PDF
Stata Programming Cheat Sheet
Laura Hughes
 
PDF
Scala in Places API
Łukasz Bałamut
 
PPT
Introduction to Intermediate Java
Philip Johnson
 
Aggregate.pptx
Ramakrishna Reddy Bijjam
 
Python basics
Hoang Nguyen
 
Python basics
Young Alista
 
Python basics
Harry Potter
 
Python basics
Fraboni Ec
 
Python basics
Tony Nguyen
 
Python basics
James Wong
 
Python basics
Luis Goldster
 
Javascript variables and datatypes
Varun C M
 
CAP615-Unit1.pptx
SatyajeetGaur3
 
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Dhivyaa C.R
 
UNIT IV (4).pptx
DrDhivyaaCRAssistant
 
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
The ES Library for JavaScript Developers
Ganesh Bhosale
 
Array and functions
Sun Technlogies
 
Matlab Functions
Umer Azeem
 
Stata Programming Cheat Sheet
Laura Hughes
 
Scala in Places API
Łukasz Bałamut
 
Introduction to Intermediate Java
Philip Johnson
 
Ad

Recently uploaded (20)

PDF
Arihant Class 10 All in One Maths full pdf
sajal kumar
 
PDF
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
PDF
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
PPTX
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
PPTX
Strengthening open access through collaboration: building connections with OP...
Jisc
 
DOCX
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
PPTX
Congenital Hypothyroidism pptx
AneetaSharma15
 
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
mansk2
 
PPTX
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
PDF
Sunset Boulevard Student Revision Booklet
jpinnuck
 
PPTX
Cardiovascular Pharmacology for pharmacy students.pptx
TumwineRobert
 
PPTX
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
PPTX
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
PPTX
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
PPTX
Understanding operators in c language.pptx
auteharshil95
 
PDF
Introducing Procurement and Supply L2M1.pdf
labyankof
 
PDF
5.Universal-Franchise-and-Indias-Electoral-System.pdfppt/pdf/8th class social...
Sandeep Swamy
 
PPTX
Open Quiz Monsoon Mind Game Final Set.pptx
Sourav Kr Podder
 
PDF
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
PPTX
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
Arihant Class 10 All in One Maths full pdf
sajal kumar
 
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
Strengthening open access through collaboration: building connections with OP...
Jisc
 
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
Congenital Hypothyroidism pptx
AneetaSharma15
 
Week 4 Term 3 Study Techniques revisited.pptx
mansk2
 
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
Sunset Boulevard Student Revision Booklet
jpinnuck
 
Cardiovascular Pharmacology for pharmacy students.pptx
TumwineRobert
 
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
Understanding operators in c language.pptx
auteharshil95
 
Introducing Procurement and Supply L2M1.pdf
labyankof
 
5.Universal-Franchise-and-Indias-Electoral-System.pdfppt/pdf/8th class social...
Sandeep Swamy
 
Open Quiz Monsoon Mind Game Final Set.pptx
Sourav Kr Podder
 
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
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).