JavaScript is a programming language used to create dynamic content on web pages. It enables interactivity, animations, form validation, and much more. JavaScript runs in the browser and interacts with HTML and CSS to modify webpage behavior.
🌟 JavaScript works by:
1. Being embedded into an HTML file using the `<script>` tag.
2. Executing inside the web browser's JavaScript engine.
3. Interacting with HTML elements and responding to user events.
JavaScript can be written inside an HTML file in three ways:
🌟 **Inline JavaScript:** (Inside an HTML tag)
<button onclick="alert('Hello, JavaScript!')">Click
Me</button>
🌟 **Internal JavaScript:** (Inside `<script>` tag in HTML)
<!DOCTYPE html>
<html>
<head>
<script>
function greet() {
alert('Welcome
to JavaScript!');
}
</script>
</head>
<body>
<button onclick="greet()">Click
Me</button>
</body>
</html>
🌟 **External JavaScript:** (Linking a `.js` file)
// script.js
function greet() {
alert('Welcome to
JavaScript!');
}
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<button onclick="greet()">Click
Me</button>
</body>
</html>
🌟 **alert()** - Displays a message to the user.
alert('Hello! This is an alert box.');
🌟 **prompt()** - Asks the user for input.
let name = prompt('What is your name?');
alert('Hello, ' +
name + '!');
🌟 **confirm()** - Asks the user to confirm an action.
let result = confirm('Are you sure you want to proceed?');
if
(result) {
alert('You clicked OK');
} else {
alert('You clicked Cancel');
}
Functions in JavaScript allow code to be reused and executed whenever needed.
🌟 **Defining a Function**
function greet() {
alert('Hello, World!');
}
🌟 **Calling a Function**
greet(); // Calls the greet function
🌟 **Function with Parameters**
function add(a, b) {
return a + b;
}
let sum =
add(5, 10);
alert('Sum: ' + sum);
🌟 **Arrow Function (ES6)**
const multiply = (x, y) => x * y;
alert(multiply(4,
5));
Variables in JavaScript are used to store data. JavaScript provides three ways to declare variables: `var`, `let`, and `const`.
🌟 **Declaring Variables**
// Using var (old way, function-scoped)
var name =
"John";
// Using let (modern, block-scoped)
let
age = 25;
// Using const (constant, cannot be
reassigned)
const PI = 3.14;
🌟 **Using Variables**
let message = "Hello, JavaScript!";
alert(message);
// Displays "Hello, JavaScript!"
The Document Object Model (DOM) allows JavaScript to interact with HTML elements.
🌟 **Getting Data from an HTML Element**
// Get element by ID
let title =
document.getElementById("main-title").innerText;
alert(title);
🌟 **Modifying HTML Content**
// Change text of an
element
document.getElementById("main-title").innerText
= "New Title";
🌟 **Getting Input Value**
function getInputValue() {
let input =
document.getElementById("user-input").value;
alert("User entered: " + input);
}
String concatenation in JavaScript combines two or more strings.
🌟 **Using `+` Operator**
let firstName = "John";
let lastName =
"Doe";
let fullName = firstName + " " +
lastName;
alert(fullName); // "John Doe"
🌟 **Using Template Literals (ES6)**
let firstName = "John";
let lastName =
"Doe";
let fullName = `${firstName}
${lastName}`;
alert(fullName); // "John Doe"
JavaScript has different data types used to store values.
🌟 **Primitive Data Types**
// String
let name = "Alice";
//
Number
let age = 30;
// Boolean
let isStudent =
false;
// Undefined
let value;
// Null
let
emptyValue = null;
// Symbol (unique identifier)
let
uniqueID = Symbol("id");
🌟 **Reference Data Types (Objects, Arrays, Functions)**
// Object
let person = { name: "Alice", age: 30
};
// Array
let numbers = [10, 20, 30];
//
Function
function greet() {
return "Hello,
World!";
}
Operators in JavaScript are used to perform operations on variables and values. JavaScript provides different types of operators:
🌟 **Types of Operators in JavaScript:**
1. Arithmetic Operators
2. Comparison Operators
3.
Logical Operators
4. Ternary Operators
5. Assignment
Operators
6. Bitwise Operators
7. String Operators
8.
Type Operators
Arithmetic operators perform mathematical calculations on numbers.
🌟 **Common Arithmetic Operators**
// Addition
let sum = 10 + 5; // 15
//
Subtraction
let difference = 10 - 5; // 5
//
Multiplication
let product = 10 * 5; // 50
//
Division
let quotient = 10 / 5; // 2
// Modulus
(Remainder)
let remainder = 10 % 3; // 1
//
Exponentiation
let power = 2 ** 3; // 8
//
Increment
let x = 5;
x++; // 6
// Decrement
let
y = 5;
y--; // 4
Comparison operators compare values and return `true` or `false`.
🌟 **Common Comparison Operators**
// Equal to (loose comparison)
console.log(10 == "10");
// true
// Equal to (strict comparison)
console.log(10
=== "10"); // false
// Not equal
to
console.log(10 != 5); // true
// Greater
than
console.log(10 > 5); // true
// Less
than
console.log(10 < 5); // false
// Greater than
or equal to
console.log(10 >= 10); // true
// Less
than or equal to
console.log(10 <= 5); // false
🌟 **Logical Operators** - Used to combine multiple conditions.
// AND (&&) - Returns true if both conditions are
true
console.log(true && false); // false
//
OR (||) - Returns true if at least one condition is
true
console.log(true || false); // true
// NOT (!) -
Reverses the boolean value
console.log(!true); // false
🌟 **Ternary Operator** - A shorthand for `if-else` statements.
// Syntax: condition ? expression_if_true :
expression_if_false;
let age = 20;
let status = (age >=
18) ? "Adult" : "Minor";
console.log(status);
// "Adult"
Assignment operators assign values to variables.
🌟 **Common Assignment Operators**
// Assign value
let x = 10;
// Add and assign
x
+= 5; // x = x + 5
// Subtract and assign
x -= 5; //
x = x - 5
// Multiply and assign
x *= 5; // x = x *
5
// Divide and assign
x /= 5; // x = x / 5
//
Modulus and assign
x %= 5; // x = x % 5
//
Exponentiation and assign
x **= 2; // x = x ** 2
Functions in JavaScript allow you to reuse code by defining blocks of code that execute when called.
🌟 **Types of Functions in JavaScript:**
// 1. Function Declaration
function greet() {
console.log("Hello, World!");
}
// 2.
Function Expression
const sayHello = function() {
console.log("Hello, JavaScript!");
};
// 3.
Arrow Function (ES6+)
const add = (a, b) => a + b;
//
4. Anonymous Function (without a name, used in
callbacks)
setTimeout(function() {
console.log("This
runs after 2 seconds");
}, 2000);
// 5.
Immediately Invoked Function Expression (IIFE)
(function() {
console.log("IIFE executed immediately");
})();
OnClick
Event
The `onclick` event allows a function to execute when an element (e.g., button) is clicked.
🌟 **Example: Button Click Event**
<!DOCTYPE html>
<html>
<head>
<script>
function showMessage() {
alert("Button Clicked!");
}
</script>
</head>
<body>
<button
onclick="showMessage()">Click
Me</button>
</body>
</html>
Mouse events in JavaScript allow developers to handle user interactions such as clicks, hovering, and dragging. These events can be used to make webpages more interactive.
**Common Mouse Events
in JavaScript:**
1.
`onclick` - Triggered when the user clicks an element.
2.
`ondblclick` - Triggered when the user double-clicks an element.
3.
`onmouseover` - Triggered when the mouse hovers over an element.
4.
`onmouseout` - Triggered when the mouse moves away from an
element.
5. `onmousedown` - Triggered when the mouse button is
pressed.
6. `onmouseup` - Triggered when the mouse button is
released.
7. `onmousemove` - Triggered when the mouse moves over
an element.
The `onclick` event is used to execute a function when the user clicks an element.
🌟 **Example: Change Text on Click**
<!DOCTYPE html>
<html>
<head>
<script>
function changeText() {
document.getElementById("message").innerText = "Button
Clicked!";
}
</script>
</head>
<body>
<button onclick="changeText()">Click Me</button>
<p id="message">Click the button
above.</p>
</body>
</html>
The `ondblclick` event triggers when an element is double-clicked.
🌟 **Example: Change Background Color on Double Click**
<!DOCTYPE html>
<html>
<head>
<script>
function changeColor() {
document.body.style.backgroundColor = "lightblue";
}
</script>
</head>
<body
ondblclick="changeColor()">
<p>Double-click
anywhere to change background color.</p>
</body>
</html>
The `onmouseover` event triggers when the mouse enters an element, and `onmouseout` triggers when it leaves.
🌟 **Example: Change Text Color on Hover**
<!DOCTYPE html>
<html>
<head>
<script>
function highlightText() {
document.getElementById("hoverText").style.color =
"red";
}
function
resetText() {
document.getElementById("hoverText").style.color =
"black";
}
</script>
</head>
<body>
<p id="hoverText" onmouseover="highlightText()"
onmouseout="resetText()">Hover over this
text.</p>
</body>
</html>
The `onmousedown` event triggers when the mouse button is pressed, and `onmouseup` triggers when it is released.
🌟 **Example: Change Text on Mouse Down & Up**
<!DOCTYPE html>
<html>
<head>
<script>
function mouseDown() {
document.getElementById("text").innerText = "Mouse
Button Pressed";
}
function
mouseUp() {
document.getElementById("text").innerText = "Mouse
Button Released";
}
</script>
</head>
<body>
<p
id="text" onmousedown="mouseDown()"
onmouseup="mouseUp()">Press and release the mouse button
here.</p>
</body>
</html>
We can create a simple calculator using JavaScript, HTML, and the `onclick` event.
🌟 **Example: Simple Calculator**
<!DOCTYPE html>
<html>
<head>
<script>
function calculate() {
let num1 = parseFloat(document.getElementById("num1").value);
let num2 =
parseFloat(document.getElementById("num2").value);
let result = num1 + num2;
document.getElementById("output").innerText = "Result:
" + result;
}
</script>
</head>
<body>
<input type="number" id="num1"
placeholder="Enter first number">
<input
type="number" id="num2" placeholder="Enter
second number">
<button
onclick="calculate()">Add</button>
<p
id="output"></p>
</body>
</html>
The `prompt()` method allows JavaScript to ask for user input.
🌟 **Example: Get User Input with Prompt**
let name = prompt("What is your name?");
alert("Hello,
" + name + "!");
🌟 **Example: Ask User for a Number**
let age = prompt("Enter your age:");
if (age >=
18) {
alert("You are an adult.");
} else {
alert("You are a minor.");
}
Conditional statements allow JavaScript to make decisions and execute different blocks of code based on conditions.
🌟 **If-Else Statement**
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
🌟 **Else If Statement**
let marks = 85;
if (marks >= 90) {
console.log("Grade: A");
} else if (marks >= 75) {
console.log("Grade: B");
} else {
console.log("Grade: C");
}
🌟 **Example: Check if a number is even or odd**
let num = prompt("Enter a number:");
if (num % 2
== 0) {
alert(num + " is even.");
} else {
alert(num + " is odd.");
}
An array in JavaScript is a collection of values stored in a single variable.
🌟 **Declaring an Array**
// Using array literal
let fruits = ["Apple",
"Banana", "Cherry"];
// Using new
Array()
let numbers = new Array(1, 2, 3, 4, 5);
🌟 **Accessing Array Elements**
console.log(fruits[0]); // Apple
console.log(fruits[1]);
// Banana
🌟 **Array Methods**
// Add item to the end
fruits.push("Mango");
//
Remove last item
fruits.pop();
// Remove first
item
fruits.shift();
// Add item to the
beginning
fruits.unshift("Pineapple");
Loops in JavaScript are used to execute a block of code multiple times.
🌟 **For Loop** - Used to iterate over a block of code for a specific number of times.
for (let i = 1; i <= 5; i++) {
console.log("Number:
" + i);
}
🌟 **While Loop** - Repeats a block of code as long as the condition is true.
let i = 1;
while (i <= 5) {
console.log("Number: " + i);
i++;
}
🌟 **ForEach Loop** - Used to iterate over an array.
let fruits = ["Apple", "Banana",
"Cherry"];
fruits.forEach(function(fruit) {
console.log(fruit);
});
The `continue` statement in JavaScript is used inside loops to skip the current iteration and continue with the next iteration.
🌟 **Example: Using `continue` to Skip Even Numbers**
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
continue; // Skips even numbers
}
console.log(i);
}
// Output: 1, 3, 5, 7, 9
🌟 **Example: Skip Specific Condition in a Loop**
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // Skips when i is 3
}
console.log("Iteration: " + i);
}
The `break` statement is used to exit a loop prematurely when a certain condition is met.
🌟 **Example: Using `break` to Stop the Loop**
for (let i = 1; i <= 10; i++) {
if (i === 5) {
break; // Stops the loop when i is 5
}
console.log(i);
}
// Output: 1, 2, 3, 4
🌟 **Example: Searching for a Value and Breaking the Loop**
let numbers = [10, 20, 30, 40, 50];
let search = 30;
for
(let i = 0; i < numbers.length; i++) {
if (numbers[i] ===
search) {
console.log("Number found: " +
numbers[i]);
break; // Stops searching once the number
is found
}
}
Form events in JavaScript allow interaction with form elements when users enter, modify, or submit data. These events help validate user input, process form submissions, and provide real-time feedback.
🌟 **Common Form Events in JavaScript:**
1. `onsubmit` - Triggered when the form is submitted.
2.
`onreset` - Triggered when the form is reset.
3. `onfocus` -
Triggered when an input field gains focus.
4. `onblur` -
Triggered when an input field loses focus.
5. `onchange` -
Triggered when an input field value changes.
6. `oninput` -
Triggered when the user enters data in a field.
The `onsubmit` event is triggered when a user submits a form. It is often used for validation.
🌟 **Example: Prevent Form Submission Without Input**
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm(event) {
let name = document.getElementById("name").value;
if (name === "") {
alert("Name cannot be empty!");
event.preventDefault(); // Prevents form submission
}
}
</script>
</head>
<body>
<form onsubmit="validateForm(event)">
<input type="text" id="name"
placeholder="Enter your name">
<button
type="submit">Submit</button>
</form>
</body>
</html>
The `onfocus` event occurs when an input field is selected, and `onblur` occurs when the field loses focus.
🌟 **Example: Highlight Input Field on Focus**
<!DOCTYPE html>
<html>
<head>
<script>
function highlightField(element) {
element.style.backgroundColor = "yellow";
}
function resetField(element) {
element.style.backgroundColor = "white";
}
</script>
</head>
<body>
<input type="text" onfocus="highlightField(this)"
onblur="resetField(this)" placeholder="Focus on
me">
</body>
</html>
Form validation ensures that users enter correct and complete data before submitting the form. JavaScript provides both client-side and real-time validation.
🌟 **Example: Validate Email Format**
<!DOCTYPE html>
<html>
<head>
<script>
function validateEmail() {
let email = document.getElementById("email").value;
let pattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
if (!email.match(pattern)) {
alert("Please
enter a valid email address.");
return
false;
}
return true;
}
</script>
</head>
<body>
<form onsubmit="return validateEmail()">
<input type="text" id="email"
placeholder="Enter your email">
<button
type="submit">Submit</button>
</form>
</body>
</html>