Introduction to JavaScript
JavaScript is a versatile, lightweight programming language that powers interactive web applications. Originally designed for web browsers, it's now used across the entire development stack.
Why Learn JavaScript?
- It runs in all web browsers without installation
- Essential for front-end web development
- Can be used for back-end development with Node.js
- High demand in the job market
Variables & Data Types
Variables store data values. JavaScript supports multiple data types including strings, numbers, booleans, and more.
Declaring Variables
let name = "Alice"; const age = 20; var isStudent = true;
Data Types
String: Text data ("Hello")
Number: Integers and decimals (42, 3.14)
Boolean: True or false
Array: List of values [1, 2, 3]
Object: Key-value pairs {name: "John"}
Operators
Arithmetic Operators
let sum = 10 + 5; // 15 let difference = 10 - 5; // 5 let product = 10 * 5; // 50 let quotient = 10 / 5; // 2
Comparison Operators
5 == "5" // true (loose equality) 5 === "5" // false (strict equality) 10 > 5 // true 10 <= 5 // false
Logical Operators
true && false // false (AND) true || false // true (OR) !true // false (NOT)
Control Flow
If-Else Statement
let score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else {
console.log("Grade: C");
}
Switch Statement
let day = 3;
switch(day) {
case 1: console.log("Monday"); break;
case 2: console.log("Tuesday"); break;
default: console.log("Other day");
}
Loops
for (let i = 0; i < 5; i++) {
console.log(i);
}
let count = 0;
while (count < 5) {
console.log(count);
count++;
}
Functions
Functions are reusable blocks of code that perform specific tasks.
Function Declaration
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Alice"));
Arrow Functions
const add = (a, b) => a + b; console.log(add(5, 3)); // 8
Function Parameters
function calculate(x, y, operation) {
if (operation === "add") return x + y;
if (operation === "subtract") return x - y;
return 0;
}
Arrays & Objects
Working with Arrays
let fruits = ["apple", "banana", "orange"];
console.log(fruits[0]); // "apple"
fruits.push("grape"); // Add element
fruits.pop(); // Remove last element
fruits.map(f => f.toUpperCase()); // Transform
Working with Objects
let student = {
name: "John",
age: 20,
major: "Computer Science",
greet: function() {
return "Hi, I'm " + this.name;
}
};
console.log(student.name); // "John"
console.log(student.greet()); // "Hi, I'm John"
DOM Manipulation
The Document Object Model (DOM) allows you to interact with HTML elements.
Selecting Elements
let element = document.getElementById("myId");
let elements = document.querySelectorAll(".myClass");
let button = document.querySelector("button");
Modifying Content
element.textContent = "New Text";
element.innerHTML = "<strong>Bold Text</strong>";
element.style.color = "blue";
element.classList.add("active");
Event Handling
Events allow you to respond to user interactions like clicks and key presses.
Adding Event Listeners
let btn = document.getElementById("myButton");
btn.addEventListener("click", function() {
console.log("Button clicked!");
});
// Using arrow function
btn.addEventListener("mouseover", () => {
btn.style.backgroundColor = "lightblue";
});
Common Events
click: Mouse click
mouseover: Mouse enters element
keydown: Keyboard key pressed
submit: Form submission
Asynchronous Programming & Promises
Handle operations that take time, like fetching data from servers.
Promises
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log("Error:", error));
Async/Await
async function getData() {
try {
let response = await fetch("https://api.example.com/data");
let data = await response.json();
console.log(data);
} catch(error) {
console.log("Error:", error);
}
}
Best Practices & Tips
Code Quality
✓ Use meaningful variable names
✓ Write comments for complex logic
✓ Use const and let instead of var
✓ Keep functions small and focused
✓ Follow consistent naming conventions
Debugging
Use console.log() for debugging
Utilize browser DevTools (F12)
Use try-catch blocks for error handling
Performance
Minimize DOM manipulations
Use efficient algorithms
Optimize loops and conditionals