JavaScript
Complete JavaScript Guide with Code
1. JavaScript Introduction
What is JavaScript?
JavaScript is a programming language used to make web pages interactive. It is widely used for creating dynamic content, animations, and web applications.
Example:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
<script>
function showMessage() {
alert(‘Hello, JavaScript!’);
}
</script>
</head>
<body>
<button onclick=”showMessage()”>Click Me</button>
</body>
</html>
2. JavaScript Syntax
JavaScript code follows simple syntax rules. Statements end with a semicolon, and blocks of code are enclosed in {}.
let x = 10; // Variable declaration
if (x > 5) {
console.log(“X is greater than 5”);
}
3. JavaScript Variables
Variables store data values and can be declared using var, let, or const.
let name = “John”; // String variable
const pi = 3.14; // Constant variable
var age = 25; // Old variable declaration
4. JavaScript Data Types
JavaScript has different data types:
- String: “Hello”
- Number: 123
- Boolean: true / false
- Object: { key: “value” }
- Array: [1, 2, 3]
- Null: empty value
- Undefined: variable declared but not assigned
let text = “Hello”; // String
let num = 10; // Number
let isValid = true; // Boolean
let person = { name: “John”, age: 30 }; // Object
let colors = [“red”, “green”, “blue”]; // Array
5. JavaScript Operators
Operators perform operations on variables and values.
let a = 10;
let b = 5;
console.log(a + b); // Addition
console.log(a – b); // Subtraction
console.log(a * b); // Multiplication
console.log(a / b); // Division
console.log(a % b); // Modulus (remainder)
6. JavaScript Functions
Functions are blocks of code designed to perform a specific task.
function greet(name) {
return “Hello, ” + name;
}
console.log(greet(“Alice”));
7. JavaScript Events
Events respond to user actions like clicks or keystrokes.
<button onclick=”alert(‘Button clicked!’)”>Click Me</button>
8. JavaScript Arrays
Arrays store multiple values in a single variable.
let fruits = [“Apple”, “Banana”, “Cherry”];
console.log(fruits[0]); // Access first element
9. JavaScript Objects
Objects store properties and methods.
let car = {
brand: “Toyota”,
model: “Corolla”,
year: 2022,
start: function() {
console.log(“Car started”);
}
};
console.log(car.brand); // Access property
car.start(); // Call method
10. JavaScript Loops
Loops execute a block of code multiple times.
for (let i = 1; i <= 5; i++) {
console.log(“Number: ” + i);
}
11. JavaScript Conditional Statements
Conditions control the flow of code execution.
let age = 18;
if (age >= 18) {
console.log(“You are an adult.”);
} else {
console.log(“You are a minor.”);
}
12. JavaScript DOM Manipulation
The Document Object Model (DOM) allows JavaScript to interact with HTML elements.
document.getElementById(“demo”).innerHTML = “Hello, DOM!”;
<p id=”demo”></p>
<button onclick=”document.getElementById(‘demo’).innerHTML=’Hello, DOM!'”>Change Text</button>
13. JavaScript Events Handling
JavaScript can handle different types of events like clicks, mouseovers, keypresses, etc.
<input type=”text” onkeyup=”console.log(this.value)”>
14. JavaScript AJAX
AJAX allows JavaScript to request data from a server without reloading the page.
fetch(‘https://jsonplaceholder.typicode.com/posts/1’)
.then(response => response.json())
.then(data => console.log(data));
15. JavaScript ES6 Features
ES6 introduced new features like let & const, arrow functions, template literals, destructuring, and modules.
const add = (a, b) => a + b;
console.log(add(2, 3)); // Output: 5
16. JavaScript Promises & Async/Await
Promises handle asynchronous operations in JavaScript.
let myPromise = new Promise((resolve, reject) => {
setTimeout(() => resolve(“Success!”), 2000);
});
myPromise.then(message => console.log(message));
With async/await:
async function fetchData() {
let response = await fetch(‘https://jsonplaceholder.typicode.com/todos/1’);
let data = await response.json();
console.log(data);
}
fetchData();
17. JavaScript LocalStorage
LocalStorage allows saving data in the browser.
localStorage.setItem(“username”, “John”);
console.log(localStorage.getItem(“username”));
18. JavaScript Debugging
Use console.log(), debugger, and browser DevTools for debugging JavaScript code.
console.log(“Debugging message”);
debugger; // Stops execution in DevTools
