Unit 2 JavaScript[1]
Unit 2 JavaScript[1]
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";
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();
.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);
<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
}
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
• 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