Introduction
JavaScript is the programming language of the web. It runs in every browser and increasingly on servers via Node.js. JavaScript brings interactivity to web pages: form validation, animations, fetching data, and whole applications.
Including JavaScript
<script src="app.js"></script>
<script>console.log('Hi');</script>Place scripts at the end of the body or use defer so they run after HTML is parsed.
Variables
let x = 5; // block-scoped
const PI = 3.14; // block-scoped, cannot reassign
var y = 10; // function-scoped, legacyPrefer const, use let only when reassignment is needed, avoid var.
Data Types
- Primitives: number, string, boolean, null, undefined, symbol, bigint.
- Objects: arrays, plain objects, dates, functions.
Operators
Arithmetic: + - * / % **. Comparison: == === != !== < <= > >= (prefer strict ===). Logical: && || ! ?? ?.. Ternary: cond ? a : b.
Control Flow
if (x > 0) { ... } else { ... }
switch (day) {
case 'Mon': ...; break;
default: ...;
}
for (let i = 0; i < 10; i++) { ... }
for (const item of arr) { ... }
for (const key in obj) { ... }
while (cond) { ... }Functions
function add(a, b) { return a + b; }
const mul = (a, b) => a * b; // arrow
const greet = name => 'Hi ' + name; // one param, one exprFunctions are first-class: stored in variables, passed as arguments, returned. Default parameters, rest parameters (...args), and spread operator are all common.
Arrays
const a = [1, 2, 3];
a.push(4);
a.pop();
a.map(x => x * 2);
a.filter(x => x > 1);
a.reduce((sum, x) => sum + x, 0);
a.forEach(x => console.log(x));Objects
const user = {
name: 'Alice',
age: 30,
greet() { return 'Hi ' + this.name; }
};
user.name; // dot
user['name']; // bracket
Object.keys(user);ES6 features: destructuring, shorthand, computed keys, spread {...u}.
The DOM
The Document Object Model is the tree of nodes that the browser builds from HTML. JavaScript reads and changes the DOM.
const h = document.getElementById('title');
h.textContent = 'New title';
h.style.color = 'red';
const items = document.querySelectorAll('.item');
items.forEach(i => i.classList.add('active'));Events
const btn = document.querySelector('button');
btn.addEventListener('click', (e) => {
e.preventDefault();
alert('Clicked');
});Common events: click, submit, input, change, load, DOMContentLoaded, keydown, mouseover.
Form Validation
form.addEventListener('submit', (e) => {
if (!email.value.includes('@')) {
e.preventDefault();
alert('Invalid email');
}
});Asynchronous JavaScript
JavaScript is single-threaded but non-blocking. Async code uses:
- Callbacks — traditional, risk of nesting (callback hell).
- Promises —
.then().catch()chain. - async/await — syntactic sugar on top of promises.
async function load() {
const res = await fetch('/api/data');
const data = await res.json();
console.log(data);
}JSON
JavaScript Object Notation is the standard data format. JSON.stringify(obj) serializes, JSON.parse(text) deserializes.
Summary
JavaScript is the universal language of the web. Master data types, control flow, functions, arrays, objects, and DOM manipulation, then layer on async and modern ES features to build real applications.
Important Questions
- Explain
varvsletvsconst. - List JavaScript primitive types.
- Differentiate
==and===. - Write a function using arrow syntax.
- List five array methods with examples.
- What is the DOM?
- Write JavaScript to change the text of a heading.
- Explain Promises and async/await.