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.
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).
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).