Skip to main content

JavaScript Fundamentals

JavaScript is the programming language of the web; it also runs on servers with Node.js.

Variables and types​

const name = "Asha"; // cannot be reassigned
let count = 0; // can be reassigned
count += 1;

// primitives: string, number, boolean, null, undefined, symbol, bigint
// everything else is an object (arrays, functions, dates...)
console.log(typeof name, typeof count); // string number

Prefer const, use let when you must reassign, and avoid var.

Equality and truthiness​

0 == "0"; // true (coerces types)
0 === "0"; // false (strict, prefer this)

// falsy: false, 0, "", null, undefined, NaN. Everything else is truthy
if (!"") console.log("empty string is falsy");

Functions​

function add(a, b) {
return a + b;
}

const multiply = (a, b) => a * b; // arrow function

const greet = (name = "friend") => `Hello, ${name}!`;

Arrays and objects​

const nums = [1, 2, 3, 4];

const doubled = nums.map((n) => n * 2); // [2, 4, 6, 8]
const evens = nums.filter((n) => n % 2 === 0); // [2, 4]
const total = nums.reduce((sum, n) => sum + n, 0); // 10

const user = { name: "Asha", age: 21 };
const { name, age } = user; // destructuring
const copy = { ...user, city: "Pune" }; // spread

Scope and closures​

function makeCounter() {
let count = 0;
return () => ++count; // remembers `count`
}

const next = makeCounter();
next(); // 1
next(); // 2

Modern syntax worth knowing​

Template literals, optional chaining (user?.address?.city), nullish coalescing (value ?? "default"), modules (import / export), classes.