# Modern JavaScript Cheatsheet

ES2015+ essentials, the DOM, events, and async/await — the core JS we use across the course.

## Variables

```js
const PI = 3.14;        // never reassigned (default)
let count = 0;          // can be reassigned
// avoid `var` — function-scoped, hoisted, foot-guns
```

## Types

`string` `number` `boolean` `null` `undefined` `bigint` `symbol` — and **objects** (incl. arrays, functions).

```js
typeof "abc";      // "string"
Array.isArray([]); // true
```

## Strings

```js
const name = "Asha";
`Hello, ${name}!`              // template literal
"abc".toUpperCase()
"a,b,c".split(",")             // ["a","b","c"]
str.includes("foo")
str.startsWith("https://")
str.trim()
```

## Arrays

```js
const xs = [1, 2, 3];
xs.length
xs.push(4); xs.pop();
xs.unshift(0); xs.shift();
xs.includes(2)
xs.indexOf(3)
xs.slice(1, 3)                 // copy [1..3)
xs.concat([4, 5])

// Functional (return new arrays — don't mutate)
xs.map(x => x * 2)
xs.filter(x => x > 1)
xs.reduce((sum, x) => sum + x, 0)
xs.find(x => x === 2)
xs.some(x => x > 2)
xs.every(x => x > 0)
```

## Objects

```js
const user = { name: "Asha", age: 22 };
user.name
user["name"]
const { name, age } = user;          // destructuring
const copy = { ...user, age: 23 };   // spread
Object.keys(user)
Object.entries(user)
```

## Functions

```js
function add(a, b) { return a + b; }
const add = (a, b) => a + b;
const greet = (name = "world") => `Hi ${name}`;

// Rest & spread
const sum = (...nums) => nums.reduce((a, b) => a + b, 0);
sum(...[1, 2, 3]);
```

## Control flow

```js
if (x > 0) {} else if (x < 0) {} else {}

for (let i = 0; i < 10; i++) {}
for (const x of array) {}
for (const [k, v] of Object.entries(obj)) {}

array.forEach((item, i) => {});

switch (kind) {
  case "a": ...; break;
  default: ...;
}

// Optional chaining + nullish coalescing
user?.address?.city ?? "unknown"
```

## DOM — selecting & modifying

```js
document.getElementById("main")
document.querySelector(".card")
document.querySelectorAll("li")           // NodeList (use forEach / spread)

el.textContent = "Hi";                    // safe — escapes HTML
el.innerHTML = "<b>Hi</b>";               // raw HTML — XSS risk
el.classList.add("active");
el.classList.toggle("open");
el.setAttribute("data-id", "42");
el.dataset.id                             // → "42"
el.style.color = "red";

const div = document.createElement("div");
div.textContent = "Hello";
parent.append(div);
el.remove();
```

## Events

```js
button.addEventListener("click", (event) => {
  event.preventDefault();
  console.log(event.target);
});

// Form
form.addEventListener("submit", (e) => {
  e.preventDefault();
  const data = new FormData(form);
  console.log(Object.fromEntries(data));
});

// Delegation — one listener for many children
list.addEventListener("click", (e) => {
  if (e.target.matches("li.delete")) { ... }
});
```

## Promises & async/await

```js
async function loadUser(id) {
  try {
    const res = await fetch(`/api/users/${id}`);
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    return await res.json();
  } catch (err) {
    console.error(err);
  }
}

// Run in parallel
const [a, b] = await Promise.all([fetchA(), fetchB()]);
```

## JSON

```js
JSON.stringify({ a: 1 })       // '{"a":1}'
JSON.parse('{"a":1}')           // { a: 1 }
```

## localStorage / sessionStorage

```js
localStorage.setItem("theme", "dark");
const theme = localStorage.getItem("theme");
localStorage.removeItem("theme");
// Store objects via JSON
localStorage.setItem("user", JSON.stringify(user));
const u = JSON.parse(localStorage.getItem("user"));
```

## Modules (ES2015)

```js
// utils.js
export const add = (a, b) => a + b;
export default function main() {}

// app.js
import main, { add } from "./utils.js";
```

## Common mistakes

- `===` not `==` (avoid type coercion).
- Don't reassign `const` arrays/objects, but you *can* mutate them.
- Arrow functions don't have their own `this`.
- `forEach` can't `break` — use `for…of` or `some()`.
- `await` only works inside an `async` function (or top-level in modules).

## Tools

- MDN JS reference: <https://developer.mozilla.org/en-US/docs/Web/JavaScript>
- DevTools console: `Cmd/Ctrl + Shift + J`
- ESLint: <https://eslint.org/>
- Prettier: <https://prettier.io/>
