1. Basics: Variables, Types & Operators
Variables
const PI = 3.14; // Constant
let score = 10; // Can be reassigned
var alt = "legacy"; // (Avoid)
Primitive Data Types
- String:
"Hello"
- Number:
10, 3.14, NaN
- Boolean:
true, false
- undefined: Not assigned
- null: Intentionally empty
Structural Types
- Object:
{ key: "value" }
- Array:
[1, 2, 3]
- Function:
function() {}
Important Operators
- Strict Equality:
===
- Loose Equality:
== (Avoid)
- Logical:
&& (AND), || (OR), ! (NOT)
- Ternary:
(condition) ? "true" : "false"
2. Control Structures
Conditionals (If / Else)
if (age > 18) {
console.log("Adult");
} else if (age === 18) {
console.log("Just turned 18");
} else {
console.log("Minor");
}
Switch
switch (status) {
case "success":
break;
case "error":
break;
default:
}
Loops
// For Loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
// While Loop
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
3. Functions
Classic Declaration
function sayHello(name) {
return `Hello, ${name}!`;
}
Arrow Function (ES6)
// Short syntax
const add = (a, b) => a + b;
// With block body
const add = (a, b) => {
return a + b;
};
Scope
- Global Scope: Available everywhere.
- Block Scope (let/const): Only inside
{ }.
- Function Scope (var): Only inside function.
4. Objects & Arrays
Object Literal
const user = {
firstname: "Nici",
skills: ["JS", "CSS"]
};
// Access
console.log(user.firstname); // "Nici"
console.log(user["skills"]);
Array Basics
const colors = ["Red", "Green"];
console.log(colors[0]); // "Red"
colors.push("Blue"); // Add
colors.pop(); // Remove last
console.log(colors.length); // 2
Important Array Methods
.forEach() (Loop)
.map() (Create new array)
.filter() (Filter new array)
.find() (Find first element)
.reduce() (Reduce to single value)
5. Modern JS (ES6+)
Destructuring
// Object
const { firstname } = user;
console.log(firstname);
// Array
const [firstColor] = colors;
console.log(firstColor);
Spread & Rest (...)
// Spread (Copy)
const copy = [...colors];
const userCopy = { ...user };
// Rest (Function)
function collect(...args) {
console.log(args); // Array
}
JSON
JSON.stringify(obj) (Object -> String)
JSON.parse(string) (String -> Object)
6. Async JS & DOM
Promises (fetch)
fetch("url")
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
Async / Await (More readable)
async function loadData() {
try {
const res = await fetch("url");
const data = await res.json();
console.log(data);
} catch (err) {
console.error(err);
}
}
DOM (HTML Manipulation)
// Find
const title = document.querySelector("h1");
// Manipulate
title.textContent = "New Title";
title.style.color = "red";
title.classList.add("new");
// Event
const btn = document.querySelector("button");
btn.addEventListener("click", () => {
console.log("Clicked!");
});