Basics
JavaScript is the programming language of the web it makes pages interactive and dynamic.
Variables & Data Types
const name = 'Aditya'; // constant
let age = 17; // reassignable
// var is legacy avoid it
// Data Types
'string' // String
42 // Number
true // Boolean
null // Null
undefined // Undefined
{} // Object
[] // Array
Functions
Function Declarations & Arrow Functions
// Traditional
function greet(name) {
return `Hello, ${name}!`;
}
// Arrow function
const greet = (name) => `Hello, ${name}!`;
// Default parameters
const add = (a, b = 0) => a + b;
Array Methods
Essential Array Methods
const nums = [1, 2, 3, 4, 5];
nums.map(n => n * 2); // [2, 4, 6, 8, 10]
nums.filter(n => n > 3); // [4, 5]
nums.reduce((sum, n) => sum + n, 0); // 15
nums.find(n => n === 3); // 3
nums.forEach(n => console.log(n));
nums.includes(3); // true
nums.some(n => n > 4); // true
nums.every(n => n > 0); // true
// Spread & destructuring
const copy = [...nums];
const [first, ...rest] = nums;
DOM Manipulation
Selecting & Modifying Elements
// Select elements
const el = document.querySelector('.my-class');
const all = document.querySelectorAll('.items');
// Modify
el.textContent = 'New text';
el.innerHTML = '<strong>Bold</strong>';
el.classList.add('active');
el.classList.toggle('hidden');
el.style.color = 'red';
// Events
el.addEventListener('click', (e) => {
console.log('Clicked!', e.target);
});
Async / Await & Fetch
Fetching Data
// Async / Await
async function getUser() {
const response = await fetch('https://api.example.com/user');
const data = await response.json();
return data;
}
// With error handling
async function fetchData(url) {
try {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (err) {
console.error('Fetch failed:', err);
}
}
Best Practices
- Use
constby default,letwhen needed, nevervar - Prefer arrow functions for callbacks
- Use template literals instead of string concatenation
- Destructure objects and arrays for clean code
- Use optional chaining (
?.) and nullish coalescing (??) - Handle errors with try/catch in async code
- Use
addEventListenerinstead of inline event handlers - Keep functions small and focused
