Unit 4 JAVASCRIPT
Unit 4 JAVASCRIPT
Introduction to JavaScript:
JavaScript is a versatile and powerful programming language primarily used for creating
dynamic and interactive content on websites. It is a core technology of the web, alongside
HTML and CSS.
JavaScript is supported by all modern web browsers and is an essential skill for web developers.
It works seamlessly with HTML to define the structure of a webpage and CSS to style it.
Beyond the browser, JavaScript is widely used on the server side (e.g., Node.js) and in desktop
or mobile applications.
Variables in JavaScript:
Variables are fundamental to programming, allowing you to store and manipulate data. In
JavaScript, variables can be declared using three keywords:
var: The original way to declare variables. It has function scope and is less commonly used
in modern JavaScript due to certain limitations.
let: Introduced in ES6, it provides block scope, making it safer and more predictable.
const: Used to declare constants, values that cannot be reassigned after their initial
assignment. It also has block scope.
const pi = 3.14159;
Variables can hold different types of data, including strings, numbers, booleans, arrays, objects,
and more. JavaScript is dynamically typed, meaning the type of a variable can change at
runtime.
JavaScript Operators:
JavaScript operators are symbols or keywords that perform operations on data values. They are
categorized as follows:
let x = 10;
x += 5; // Equivalent to x = x + 5;
x *= 2; // Equivalent to x = x * 2;
Conditional Statements:
Conditional statements allow you to perform actions based on conditions. Common statements
include:
if Statement: Executes a block of code if a condition is true.
JavaScript Loops:
Loops are used to execute a block of code repeatedly:
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
do-while Loop: Executes a block of code at least once, then repeats while the condition is
true.
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
for-of Loop: Iterates over the values of an iterable object, such as an array.
Continue Statement: Skips the current iteration and moves to the next iteration of the loop.
Use Cases:
Break is useful when you want to exit a loop early based on a specific condition.
Continue is helpful when you want to skip certain iterations but keep looping through the rest.
Example with Nested Loops
Alert Box (alert): Displays a message to the user and has an OK button.
Confirm Box (confirm): Displays a dialog box with OK and Cancel buttons. It returns true
if the user clicks OK, and false if they click Cancel.
JavaScript Arrays:
Arrays in JavaScript are used to store multiple values in a single variable. They can hold values
of any data type.
Declaring an Array:
Array Methods:
push(): Adds an element to the end of an array.
fruits.push("Orange");
function greet(name) {
return "Hello " + name + "!";
}
Arrow Functions: JavaScript also supports arrow functions, which are a more concise way
to write functions.
console.log(Math.abs(-5)); // 5
console.log(Math.round(4.5)); // 5
console.log(Math.floor(4.9)); // 4
console.log(Math.ceil(4.1)); // 5
console.log(Math.pow(2, 3)); // 8
map(): Creates a new array with the results of calling a provided function on every element.
let arr = [1, 2, 3];
let doubled = arr.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
filter(): Creates a new array with all elements that pass the test.
new Date(): Creates a new Date object with the current date and time.
Events:
Mouse Events:
onclick
Triggered when an element is clicked.
Example:
<button onclick="alert('Button clicked!')">Click Me</button>
ondblclick
Triggered when an element is double-clicked.
Example:
<button ondblclick="alert('Button double-clicked!')">Double Click Me</button>
onmouseover
Triggered when the mouse pointer hovers over an element.
Example:
<p onmouseover="this.style.color='red'">Hover over me!</p>
onmouseout
Triggered when the mouse pointer leaves an element.
Example:
<p onmouseout="this.style.color='black'">Mouse out!</p>
Keyboard Events:
onkeypress
Triggered when a key is pressed (excluding some special keys).
Example:
<input onkeypress="alert('Key pressed!')" />
onkeyup
Triggered when a key is released.
Example:
<input onkeyup="console.log('Key released')" />
onblur
Triggered when an element loses focus.
Example:
<input onblur="this.style.backgroundColor='white'" />
onchange
Triggered when the value of an element (like a text field or dropdown) changes.
Example:
<select onchange="alert('Selection changed!')">
<option>Option 1</option>
<option>Option 2</option>
</select>
onsubmit
Triggered when a form is submitted.
Example:
<form onsubmit="alert('Form submitted!'); return false;">
<input type="text" />
<button type="submit">Submit</button>
</form>
onreset
Triggered when a form is reset.
Example:
<form onreset="alert('Form reset!')">
<input type="text" />
<button type="reset">Reset</button>
</form>
Window Events:
onload
Triggered when the page or an element (e.g., an image) has fully loaded.
Example:
<body onload="alert('Page loaded!')">
Key Features:
Accessing Elements: Use JavaScript to access and manipulate HTML elements.
Creating Elements:
document.getElementById("btn").addEventListener("click", function() {
alert("Button Clicked!");
});
Manipulating Styles:
History Object
The history object allows developers to manipulate the browser's session history. It is part of the
window object.
Key Methods:
history.back(): Navigates to the previous page.
history.back();
history.forward(): Navigates to the next page.
history.forward();
history.pushState(): Adds a new entry to the session history without reloading the page.
Example:
<form id="myForm">
<label for="username">Username:</label>
<input type="text" id="username" required minlength="3">
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("myForm").addEventListener("submit", function(event) {
let username = document.getElementById("username").value;
if (username.length < 3) {
alert("Username must be at least 3 characters long.");
event.preventDefault(); // Prevent form submission
}
});
</script>
Email Validation
Email validation ensures that the entered email address is in a valid format.
document.getElementById("email").addEventListener("input", function() {
const email = this.value;
if (!validateEmail(email)) {
this.style.borderColor = "red";
} else {
this.style.borderColor = "green";
}
});