Variables and types
const name = "Mia"; // fixed
let score = 0; // can change
score += 10;
score++;
typeof "hi" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof null // "object" (old bug)
Number("42") // 42
String(42) // "42"
Boolean("") // false
"5" + 3 // "53" (glue)
"5" - 3 // 2 (math)
Strings
const s = "JavaScript";
`Hello, ${name}!` // template
s.length // 10
s[0] // "J"
s.at(-1) // "t"
s.toUpperCase() // "JAVASCRIPT"
" hi ".trim() // "hi"
s.includes("Scr") // true
s.startsWith("J") // true
s.indexOf("a") // 1
s.slice(0, 4) // "Java"
s.replace("Java", "Type")
"a,b".split(",") // ["a", "b"]
Operators
+ - * / ** // math
% // remainder
=== !== > < >= <= // compare
&& || ! // and, or, not
a ?? b // b if a is null
// or undefined
obj?.prop // no crash if
// obj is missing
ok ? "yes" : "no" // ternary
// Always === (never ==)
Decisions
if (score >= 80) {
grade = "A";
} else if (score >= 70) {
grade = "B";
} else {
grade = "C";
}
switch (day) {
case "Sat":
case "Sun":
console.log("Weekend!");
break;
default:
console.log("Weekday");
}
// Falsy: false 0 "" null
// undefined NaN (and -0, 0n)
Loops
for (let i = 0; i < 5; i++) {
// counts 0 to 4
}
while (lives > 0) {
// until it changes
}
for (const item of list) {
// each item
}
for (const key in obj) {
// each key
}
break; // stop the loop
continue; // skip to the next
Functions
function add(a, b = 0) {
return a + b;
}
const square = (n) => n * n;
const sum = (...nums) =>
nums.reduce((t, n) => t + n, 0);
add(2, 3); // 5
square(4); // 16
sum(1, 2, 3) // 6
Arrays
const arr = [3, 1, 2];
arr.push(4) // add to end
arr.pop() // remove end
arr.unshift(0) // add to start
arr.shift() // remove start
arr.includes(2) // true
arr.indexOf(2) // 2
arr.slice(1, 3) // copy a part
arr.join(", ") // "3, 1, 2"
[...a, ...b] // join arrays
arr.sort((a, b) => a - b)
arr.map((x) => x * 2)
arr.filter((x) => x > 1)
arr.find((x) => x > 1)
arr.some((x) => x > 1)
arr.every((x) => x > 0)
arr.reduce((t, x) => t + x, 0)
[...new Set(arr)] // no repeats
Objects
const user = {
name: "Omar",
age: 17,
greet() {
return `Hi, I'm ${this.name}`;
},
};
user.name // "Omar"
user["age"] // 17
user.city = "Paris";
delete user.city;
"name" in user // true
Object.keys(user)
Object.values(user)
Object.entries(user)
const { name, age } = user;
const copy = { ...user, age: 18 };
JSON.stringify(user)
JSON.parse(text)
Errors
try {
riskyThing();
} catch (error) {
console.log(error.message);
} finally {
cleanUp(); // always runs
}
throw new Error("Oh no!");
The DOM and events
const el =
document.querySelector("#id");
const items =
document.querySelectorAll("li");
el.textContent = "Safe text";
el.classList.add("big");
el.classList.toggle("big");
const li =
document.createElement("li");
list.append(li);
li.remove();
button.addEventListener("click",
(event) => {
console.log(event.target);
});
form.addEventListener("submit",
(event) => {
event.preventDefault();
});
Saving data
localStorage.setItem("todos",
JSON.stringify(todos));
const saved = JSON.parse(
localStorage.getItem("todos")
) ?? [];
Async
setTimeout(() => {
console.log("1 second later");
}, 1000);
const id = setInterval(tick, 1000);
clearInterval(id);
async function load(url) {
try {
const res = await fetch(url);
if (!res.ok) {
throw new Error(res.status);
}
return await res.json();
} catch (error) {
console.log(error.message);
}
}
const [a, b] = await Promise.all([
taskA(),
taskB(),
]);
Classes
class Animal {
#secret = 42; // private
static count = 0;
constructor(name) {
this.name = name;
Animal.count++;
}
speak() {
return `${this.name} speaks`;
}
get shout() {
return this.name.toUpperCase();
}
}
class Dog extends Animal {
speak() {
return super.speak() + "!";
}
}
const d = new Dog("Bingo");
Modules and Node
// app.js
export function helper() {}
export default class App {}
// main.js
import App, { helper }
from "./app.js";
import { readFile }
from "node:fs/promises";
process.argv.slice(2) // args
// In the terminal:
// node file.js
// npm init -y
// npm install package-name
// node --test
Know the syntax? Now use it
CurlyScript turns all of this into short questions and small projects, with an explanation after every answer.