JavaScript Full Detailed Notes
Introduction to JavaScript:
- JavaScript is a dynamic programming language used for web development.
- It is commonly used to create interactive effects in web browsers.
- JavaScript allows you to update content, control multimedia, animate images, etc.
1. Variables in JavaScript
- JavaScript variables are containers for storing data values.
- You declare variables using var, let, or const.
Example:
var x = 5;
let y = 10;
const z = 15;
2. Data Types
- JavaScript variables can hold many data types such as numbers, strings, objects, and more.
- Common data types include:
Numbers: var num = 100;
Strings: var name = "John";
Booleans: var isActive = true;
Arrays: var arr = [1, 2, 3, 4];
Objects: var person = {firstName: "John", lastName: "Doe", age: 25};
3. Functions
- Functions in JavaScript allow you to write reusable code.
- A JavaScript function is defined with the function keyword, followed by a name.
Example:
function add(a, b) {
return a + b;
let sum = add(5, 10); // Output: 15
4. Conditional Statements
- JavaScript supports if-else conditions to execute code based on specific conditions.
Example:
if (x > 10) {
console.log("x is greater than 10");
} else {
console.log("x is less than or equal to 10");
5. Loops
- Loops are used to repeatedly run a block of code until a condition is met.
- JavaScript supports several types of loops: for, while, do-while.
Example:
for (let i = 0; i < 5; i++) {
console.log(i);
while (i < 5) {
console.log(i);
i++;
6. DOM Manipulation
- JavaScript can interact with the Document Object Model (DOM) to manipulate web pages.
- You can access and modify HTML elements using methods like getElementById(), querySelector(),
etc.
Example:
document.getElementById("myElement").innerHTML = "Hello World!";
document.querySelector(".myClass").style.backgroundColor = "yellow";
7. JavaScript Events
- JavaScript can respond to user actions via events, such as clicking a button or hovering over an
element.
Example:
document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!");
});
8. JavaScript Objects
- Objects are collections of key-value pairs.
Example:
var car = {
make: "Toyota",
model: "Corolla",
year: 2020,
start: function() {
console.log("Car started");
};
car.start(); // Output: "Car started"
9. JavaScript Arrays
- Arrays are used to store multiple values in a single variable.
Example:
var fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]); // Output: Apple
- You can manipulate arrays using methods like push(), pop(), and shift().