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

Unit 2 JavaScript[1]

JavaScript is a high-level programming language essential for creating dynamic web pages, functioning on both client-side and server-side development. It features lightweight execution, dynamic typing, and allows for interactive web elements through event handling and DOM manipulation. The document covers basic syntax, data types, functions, and array methods, providing a comprehensive introduction to JavaScript programming.

Uploaded by

rydhamgupta84
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)
3 views

Unit 2 JavaScript[1]

JavaScript is a high-level programming language essential for creating dynamic web pages, functioning on both client-side and server-side development. It features lightweight execution, dynamic typing, and allows for interactive web elements through event handling and DOM manipulation. The document covers basic syntax, data types, functions, and array methods, providing a comprehensive introduction to JavaScript programming.

Uploaded by

rydhamgupta84
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/ 41

UNIT-2

Java Script
Introduction to JavaScript
• JavaScript (JS) is a high-level, interpreted programming language that is
essential for creating dynamic and interactive web pages. It is one of the
core technologies of the web, along with HTML (HyperText Markup
Language) and CSS (Cascading Style Sheets).
Why Learn JavaScript?
• Client-Side Scripting: Runs directly in web browsers.
• Interactive Websites: Enables animations, form validations, pop-ups,
and real-time updates.
• Full-Stack Development: Works on both front-end (with frameworks like
React, Vue) and back-end (using Node.js).
• Wide Adoption: Supported by all modern browsers and widely used in
web development.
Basic Features of JavaScript
• Lightweight & Fast: Executes in the browser without needing
compilation.
• Event-Driven: Reacts to user interactions like clicks and
keypresses.
• Object-Oriented: Uses objects and prototypes instead of classes
(ES6 introduced class).
• Dynamic Typing: Variables don’t have fixed types (var, let, const).
• Interpreted Language: No need for compilation; browsers read
and execute JS code.
Getting Started with JavaScript
1. Adding JavaScript to HTML
• JavaScript can be written inside an HTML file using the <script> tag:
<script>
alert("Hello, World!");
</script>

• <script src="script.js"></script>
Basic JavaScript Syntax
1. Variables (var, let, const)
• var name = "John"; // Older way (can be redefined)
• let age = 25; // Block-scoped (preferred)
• const PI = 3.14; // Constant (cannot be changed)
2. Data Types
• JavaScript has several data types:
• Primitive: Number, String, Boolean, Undefined, Null, Symbol,
BigInt
• Reference: Objects, Arrays, Functions
• let number = 10; // Number
• let text = "JavaScript"; // String
• let isCool = true; // Boolean
• let arr = [1, 2, 3]; // Array
• let obj = { name: "Alice", age: 30 }; // Object
3. Functions
• Functions are reusable blocks of code:
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Alice"));
4. Conditional Statements
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}

5. Loops
Used for iteration:
for (let i = 0; i < 5; i++) {
console.log("Iteration " + i);
}
6. Events (User Interactions)
JavaScript allows handling user interactions:
document.getElementById("btn").addEventListener("click", function () {
alert("Button Clicked!");
});
Next Step
• Learn DOM Manipulation to change web page content
dynamically.
DOM Manipulation in JavaScript
• What is the DOM?
• The Document Object Model (DOM) is a programming interface
that represents an HTML document as a tree structure. It allows
JavaScript to interact with and modify the content, structure, and
styles of a webpage dynamically.
Selecting Elements in the DOM
Before manipulating elements, you must first select them.
JavaScript provides several methods to do this:
1. Selecting by ID (getElementById)
let heading = document.getElementById("title");
console.log(heading); // Logs the element with ID "title"
DOM
1️⃣ getElementById()
2️⃣ getElementsByClassName()
3️⃣ getElementsByTagName()
4️⃣ querySelector()
5️⃣ querySelectorAll()
Java Script Document functions

1. createElement()
let newParagraph = document.createElement("p");
// Add text content
newParagraph.textContent = "Hello, this is a dynamically created paragraph!";
// Append it to the body
document.body.appendChild(newParagraph);

2. querySelector()
• let heading = document.querySelector("h1"); // Selects the first <h1>
• console.log(heading.textContent);

3. addEventListener()
• document.getElementById("myButton").addEventListener("click", function () {
• alert("Button Clicked!");
• });
Adding & Removing Elements
4. Remove an Element and Create & Append Elements
let newPara = document.createElement("p");
newPara.innerText = "This is a new paragraph!";
document.body.appendChild(newPara);
let element = document.getElementById("oldElement");
element.remove();

5. Event Listeners
document.getElementById("myButton").addEventListener("click", function() {
alert("Button Clicked!");
});
1. Changing Inline Styles
• var element = document.getElementById("myDiv");
• element.style.color = "red"; // Changes text color
• element.style.backgroundColor = "yellow"; // Changes background
• element.style.fontSize = "20px"; // Changes font size
2. Generate a Random RGB Color
function getRandomRGBColor() {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
return `rgb(${r}, ${g}, ${b})`;
}
console.log(getRandomRGBColor());
String Method in JS
1. String Length
• let str = "Hello World!";
• console.log(str.length); // Output: 12
2. Changing Case
• console.log(str.toUpperCase()); // "HELLO WORLD!"
• console.log(str.toLowerCase()); // "hello world!"
3. Extracting Parts of a String
• console.log(str.slice(0, 5)); // "Hello” slice(start, end)
• let str = "JavaScript";
• console.log(str.slice(0, 4)); // "Java" (Extracts from index 0 to 3)
• console.log(str.slice(4)); // "Script" (Extracts from index 4 to end)
• console.log(str.slice(-6, -1)); // "Scrip" (Negative indices)
• console.log(str.substring(6, 11)); // "World” substring(start, end)
• console.log(str.substr(6, 5)); // "World” substr(start, length) (Deprecated)
String Method in JS
4. Replacing Text
• console.log(str.replace("World", "JavaScript")); // "Hello JavaScript!"
• console.log(str.replace(/world/i, "JS")); // Case-insensitive replacement
• var str = "hello world";

• var str1 = str.replace(/[aeiouAEIOU]/g,” ") // Replace All vowels removed.


• console.log(str)
• console.log(str1)

5. Splitting a String
• let sentence = "Apple, Banana, Cherry";
• console.log(sentence.split(", ")); // ["Apple", "Banana", "Cherry"]
6. Trimming Spaces
• let text = " Hello World! ";
• console.log(text.trim()); // "Hello World!"
• console.log(text.trimStart()); // "Hello World! "
• console.log(text.trimEnd()); // " Hello World!"
7. Searching in a String
• console.log(str.indexOf("World")); // 6
• console.log(str.lastIndexOf("o")); // 7
• console.log(str.includes("Hello")); // true
• console.log(str.startsWith("Hello")); // true
• console.log(str.endsWith("!")); // true
8. Repeating a String
• console.log("Hi ".repeat(3)); // "Hi Hi Hi "
9. Extracting Characters
• console.log(str.charAt(0)); // "H"
• console.log(str.charCodeAt(0)); // Unicode of 'H' (72)
• console.log(str[0]); // "H"
10. Concatenation
• let first = "Hello";
• let second = "World";
• console.log(first.concat(" ", second)); // "Hello World"
11. Padding Strings
• let num = "5";
• console.log(num.padStart(4, "0")); // "0005"
• console.log(num.padEnd(4, "0")); // "5000"
Array
• let fruits = ["apple", "banana", "mango"];
• let cars = new Array("BMW", "Audi", "Tesla");
• let emptyArray = [];
• Accessing Array Elements
• let colors = ["red", "green", "blue"];
• console.log(colors[0]); // Output: red
• console.log(colors[1]); // Output: green

Array Methods
Method Description Example
.push() Adds an element at the end. fruits.push("orange");
.pop() Removes the last element. fruits.pop();

.unshift() Adds an element at the beginning. fruits.unshift("grapes");

.shift() Removes the first element. fruits.shift();

.concat() Combines two or more arrays. let allFruits = fruits.concat(["kiwi", "pear"]);

.splice() Adds/Removes elements from a specific index. fruits.splice(1, 1, "pineapple");

.slice() Extracts a portion of an array. let sliced = fruits.slice(1, 3);


.indexOf() Finds the index of an element. fruits.indexOf("banana");

.includes() Checks if an element exists in the array. fruits.includes("apple");

.map() Creates a new array by transforming each element. let doubled = [1, 2, 3].map(x => x * 2);

.filter() Filters elements based on a condition. let even = [1, 2, 3, 4].filter(x => x % 2 === 0);

.reduce() Reduces array to a single value. let sum = [1, 2, 3].reduce((a, b) => a + b, 0);

.forEach() Iterates over each element. fruits.forEach(fruit => console.log(fruit));


splice() for Insertion, Deletion, and Replacement
• let numbers = [10, 20, 30, 40, 50];

// Inserting elements
• numbers.splice(2, 0, 25); // Insert 25 at index 2
• console.log(numbers); // Output: [10, 20, 25, 30, 40, 50]

// Deleting elements
• numbers.splice(3, 1); // Removes 1 element at index 3
• console.log(numbers); // Output: [10, 20, 25, 40, 50]

// Replacing elements
• numbers.splice(1, 2, 15, 35); // Replaces two elements starting at index 1
• console.log(numbers); // Output: [10, 15, 35, 40, 50]

Array Iteration Methods
• let cars = ["BMW", "Audi", "Tesla"];
• cars.forEach(car => console.log(`Car: ${car}`));
map() Example (Transformation)
• let prices = [100, 200, 300];
• let discountedPrices = prices.map(price => price * 0.9);
• console.log(discountedPrices); // Output: [90, 180, 270]
filter() Example (Condition Filtering)
• et ages = [12, 18, 25, 30, 14];
• let adults = ages.filter(age => age >= 18);
• console.log(adults); // Output: [18, 25, 30]
reduce() Example (Summing Values)
• let marks = [50, 60, 70];
• let totalMarks = marks.reduce((acc, mark) => acc + mark, 0);
• let totalMarks = marks.reduce((acc, mark) => acc + mark,"a");
console.log(totalMarks); // Output: 180
Sorting and Reversing
Sorting Strings
• let fruits = ["banana", "apple", "orange", "grape"];
• fruits.sort();

console.log(fruits); // Output: ["apple", "banana", "grape", "orange"]
Sorting Numbers
• let numbers = [25, 100, 5, 42];
• numbers.sort();
• console.log(numbers); // Output: [100, 25, 42, 5] (Incorrect for numbers)
Correct Example (Ascending Order):
• numbers.sort((a, b) => a - b);
• console.log(numbers); // Output: [5, 25, 42, 100]
Descending Order:
• numbers.sort((a, b) => b - a);
• console.log(numbers);// Output: [100, 42, 25, 5]
reversing an array after sorting:
• let cities = ["Delhi", "Mumbai", "Pune", "Kolkata"];
• cities.sort().reverse();

console.log(cities);
• // Output: ["Pune", "Mumbai", "Kolkata", "Delhi"]
• Practical Example: Sorting Student Scores
• let scores = [85, 70, 95, 60, 100];

let sortedScores = [...scores].sort((a, b) => b - a); // Highest to Lowest
• let top3 = sortedScores.slice(0, 3);

console.log(`Top 3 Scores: ${top3}`);
• // Output: Top 3 Scores: 100, 95, 85
Combining Arrays
.concat()
• let a = [1, 2];
• let b = [3, 4];
• let combined = a.concat(b);
• console.log(combined); // Output: [1, 2, 3, 4]
Spread Operator (...)
• let combined = [...a, ...b];
• console.log(combined); // Output: [1, 2, 3, 4]
Restructuring Arrays
• let scores = [80, 90, 100];
• let [math, science, english] = scores;
• console.log(math); // Output: 80
• console.log(english); // Output: 100
Multidimensional Arrays
• let matrix = [
• [1, 2, 3],
• [4, 5, 6],
• [7, 8, 9]
• ];
• console.log(matrix[1][2]); // Output: 6
Practical Example - Finding Maximum Number
• let values = [45, 23, 89, 12, 67];
• let maxValue = Math.max(...values);
• console.log(`Maximum Value: ${maxValue}`); // Output: 89
Array Methods in JavaScript
1. Adding/Removing Elements
• push(value): Adds an element to the end of the array.
• pop(): Removes and returns the last element.
• unshift(value): Adds an element to the beginning of the array.
• shift(): Removes and returns the first element.
• splice(start, deleteCount, item1, item2, ...): Adds/removes
elements at a specific index.
Array Methods in JavaScript
2. Accessing and Searching
• indexOf(value): Returns the first index of the given value, or -1 if
not found.
• lastIndexOf(value): Returns the last index of the given value.
• includes(value): Returns true if the value exists in the array.
• find(callback): Returns the first element that satisfies the
condition.
• findIndex(callback): Returns the index of the first element that
satisfies the condition.
Array Methods in JavaScript
3. Sorting and Reversing
• sort(compareFunction): Sorts elements (default is lexicographic order).
• reverse(): Reverses the order of elements.
4. Joining and Splitting
• join(separator): Joins elements into a string with the given separator.
• split(separator): Converts a string into an array (used on strings, not
arrays).
5. Slicing and Concatenating
• slice(start, end): Returns a new array with selected elements.
• concat(array2): Merges two or more arrays.
JS Math Functions
Basic Operations
• Math.abs(x): Returns the absolute value of x.
• Math.round(x): Rounds x to the nearest integer.
• Math.floor(x): Rounds x down to the nearest integer.
• Math.ceil(x): Rounds x up to the nearest integer.
• Math.trunc(x): Removes the decimal part and returns only the integer part.
Power and Roots
• Math.pow(base, exponent): Returns base raised to the power of exponent.
• Math.sqrt(x): Returns the square root of x.
• Math.cbrt(x): Returns the cube root of x.
JS Math Functions
Minimum and Maximum
• Math.min(a, b, c, ...): Returns the smallest value.
• Math.max(a, b, c, ...): Returns the largest value.
• Random Numbers
• Math.random(): Returns a random number between 0 and 1 (exclusive).
Trigonometric Functions
• Math.sin(x): Sine of x (in radians).
• Math.cos(x): Cosine of x (in radians).
• Math.tan(x): Tangent of x (in radians).
• Convert degrees to radians: radians = degrees * (Math.PI / 180)
JS Math Functions
Logarithms and Exponentials
• Math.log(x): Natural logarithm (base e).
• Math.log10(x): Base-10 logarithm.
• Math.exp(x): Returns e^x.
Math Constants
• Math.PI (≈ 3.14159)
• Math.E (Euler’s number ≈ 2.718)
• Math.SQRT2 (Square root of 2 ≈ 1.414)
• Math.LN2 (Natural log of 2 ≈ 0.693)
Form Validation using JS
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
</head>
<body>
<h2>Form Validation using addEventListener()</h2>
<form id="myForm">
Name: <input type="text" id="name"><br><br>
Email: <input type="text" id="email"><br><br>
Password: <input type="password" id="password"><br><br>
<input type="submit" value="Submit">
</form>

<script>
document.getElementById("myForm").addEventListener("submit", function(event) {
let name = document.getElementById("name").value;
let email = document.getElementById("email").value;
let password = document.getElementById("password").value;

if (!name) {
alert("Name is required");
event.preventDefault(); // Prevents form submission
}

let emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;


if (!emailPattern.test(email)) {
alert("Invalid email format");
event.preventDefault();
}

if (password.length < 6) {
alert("Password must be at least 6 characters");
event.preventDefault();
• In JavaScript, getter and setter methods are special functions
that provide controlled access to an object's properties. They
allow you to define logic when retrieving (getter) or updating
(setter) a property.
getter and setter methods of the JavaScript

1. get Method (Getter)


• Used to access a property.
• Acts like a function but is called without parentheses.
• get propertyName() {
• // Code to return the value
• }
2. set Method (Setter)
• Used to modify a property.
• Allows data validation or transformation before assigning values.
• set propertyName(value) {
• // Code to set the value
• }
3. Example with get and set Methods

• Class Person {
• constructor(firstName, lastName) {
• this._firstName = firstName; // Convention: Use "_" for internal properties
• this._lastName = lastName;
• }

// Getter for full name
• get fullName() {
• return `${this._firstName} ${this._lastName}`;
• }

// Setter for full name
• set fullName(name) {
• const parts = name.split(" ");
• if (parts.length === 2) {
• this._firstName = parts[0];
• this._lastName = parts[1];
• } else {
• console.error("Please provide both first and last name.");
• }
• }
• }

// Creating an object
• const person1 = new Person("John", "Doe");

console.log(person1.fullName); // Output: John Doe

You might also like