~/saidqb cat ecosystem/programming-language/javascript.md
JS
JavaScript
Bahasa scripting untuk web, frontend & backend (Node.js)
commit by saidqb
Introduction
JavaScript: bahasa scripting, awalnya cuma jalan di browser (client-side), sekarang juga di server lewat Node.js. Multi-paradigm: procedural, object-oriented, functional.
Where To
html
<script>
console.log("inline script");
</script>
<script src="script.js"></script> <!-- external -->
<script src="script.js" defer></script> <!-- jalan setelah HTML selesai di-parse -->
<script src="script.js" async></script> <!-- jalan begitu selesai di-download -->- Taruh
<script>sebelum</body>atau pakaideferbiar tidak blocking render HTML.
Output
js
console.log("halo");
console.error("pesan error");
console.warn("peringatan");
document.write("halo"); // jarang dipakai, overwrite seluruh dokumen
alert("halo"); // blocking popupSyntax
js
let x = 5; // statement diakhiri ; (opsional tapi disarankan)
// case-sensitive, whitespace umumnya diabaikan
{
// block statement
}Operators
js
5 + 3; 5 - 3; 5 * 3; 5 / 3; 5 % 3; 5 ** 2; // aritmatika, ** = pangkat
5 == "5"; // true -- cuma bandingkan nilai (type coercion)
5 === "5"; // false -- bandingkan nilai + tipe, selalu pakai ===
5 ?? 10; // nullish coalescing: 10 kalau kiri null/undefined
a ??= 10; // logical assignmentIf Conditions
js
if (age >= 18) {
console.log("dewasa");
} else if (age >= 13) {
console.log("remaja");
} else {
console.log("anak-anak");
}
const status = age >= 18 ? "dewasa" : "belum"; // ternaryLoops
js
for (let i = 0; i < 5; i++) { ... }
for (const tag of tags) { ... } // iterate value (array, string, Set, Map)
for (const key in config) { ... } // iterate key (object)
let i = 0;
while (i < 5) { i++; }
do { i++; } while (i < 5);Strings
js
const name = "SaidQB";
`Halo ${name}, umur ${8} tahun`; // template literal
name.length; name.toUpperCase(); name.trim();
name.slice(0, 4); name.split(",");
name.includes("Said"); name.replace("Said", "Q");Numbers
js
Number("42"); parseInt("42px"); parseFloat("3.14");
Number.isInteger(8); Number.isNaN(NaN);
(19.999).toFixed(2); // "20.00"
Math.max(1, 2, 3);Functions
js
function greet(name, greeting = "Halo") {
return `${greeting}, ${name}!`;
}
const square = (x) => x * x; // arrow function
const total = (...args) => args.reduce((a, b) => a + b, 0); // rest paramsTimers
js
const id = setTimeout(() => console.log("jalan sekali"), 1000);
clearTimeout(id);
const intervalId = setInterval(() => console.log("tiap 1 detik"), 1000);
clearInterval(intervalId);Objects
js
const user = { name: "SaidQB", age: 8, greet() { return `Halo ${this.name}`; } };
user.name; user["age"];
const { name, age } = user; // destructuring
Object.keys(user); Object.values(user); Object.entries(user);Scope
js
function outer() {
let x = 5; // hidup selama scope function outer()
{
let y = 10; // block-scoped, cuma hidup di dalam { }
}
}
var z = "function-scoped"; // var abaikan block scope, hindari pemakaian varDates
js
const now = new Date();
new Date("2026-08-23");
now.getFullYear(); now.getMonth(); now.getDate();
now.toISOString();Arrays
js
const tags = ["js", "go", "php"];
tags.push("rust"); tags.pop();
tags.map((t) => t.toUpperCase());
tags.filter((t) => t.length > 2);
tags.reduce((acc, t) => acc + t, "");
tags.find((t) => t === "go");
[...tags].sort(); [...tags].reverse(); // spread biar tidak mutate array asliSets
js
const unique = new Set([1, 2, 2, 3]); // otomatis buang duplikat
unique.add(4); unique.has(2); unique.delete(1);
[...unique]; // konversi ke arrayMaps
js
const scores = new Map();
scores.set("SaidQB", 90);
scores.get("SaidQB"); scores.has("SaidQB"); scores.delete("SaidQB");
for (const [key, val] of scores) { ... }Iterations
js
for (const tag of tags) { console.log(tag); } // iterable: array, string, Set, Map
function* range(start, end) { // generator
for (let i = start; i < end; i++) yield i;
}
[...range(0, 5)];Math
js
Math.round(4.5); Math.floor(4.9); Math.ceil(4.1);
Math.random(); // 0 s/d <1
Math.max(1, 2, 3); Math.min(1, 2, 3);
Math.abs(-5); Math.pow(2, 3); Math.sqrt(16);RegExp
js
const re = /^\d+$/; // hanya digit
re.test("12345"); // true
"halo dunia".match(/\w+/g); // ["halo", "dunia"]
"2026-08-23".replace(/-/g, "/"); // "2026/08/23"Data Types
js
typeof "halo"; // "string"
typeof 8; // "number"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object" (quirk historis JS)
typeof {}; // "object"
typeof []; // "object" -- pakai Array.isArray() buat cek array
typeof Symbol(); // "symbol"
typeof 10n; // "bigint"Errors
js
try {
JSON.parse("{invalid}");
} catch (e) {
console.error(e.message);
} finally {
console.log("selesai");
}
throw new Error("custom error");
class ValidationError extends Error {}Debugging
js
console.log(value); // paling umum
console.table(arrayOfObjects); // tabel rapi di console
debugger; // breakpoint manual, browser DevTools berhenti di sini
console.assert(age > 0, "age harus positif");Style Guide
- 2 spasi indentasi,
const/let(hindarivar),===/!==, semicolon konsisten. - Nama variabel/fungsi
camelCase, classPascalCase, konstanta globalUPPER_SNAKE_CASE. - Satu deklarasi per baris; hindari nested callback dalam-dalam, pakai async/await.
HTML DOM API
js
document; // root object buat akses/manipulasi HTML dari JS
document.title;
window.innerWidth;Selecting Elements
js
document.getElementById("app");
document.querySelector(".card"); // elemen pertama yang cocok
document.querySelectorAll("li"); // NodeList semua yang cocok
document.getElementsByClassName("item"); // HTMLCollection (live)Changing HTML
js
const el = document.querySelector("#app");
el.innerHTML = "<b>halo</b>";
el.textContent = "halo (aman dari XSS)";
el.setAttribute("data-id", "8");Changing CSS
js
el.style.color = "red";
el.style.display = "none";
el.classList.add("active");
el.classList.toggle("hidden");
el.classList.contains("active");Form Validation
js
const input = document.querySelector("#email");
if (!input.value.includes("@")) {
input.setCustomValidity("Email tidak valid");
} else {
input.setCustomValidity("");
}
form.checkValidity();DOM Animations
js
el.animate(
[{ opacity: 0 }, { opacity: 1 }],
{ duration: 300, easing: "ease-out" }
);
el.style.transition = "opacity 0.3s";
el.style.opacity = "1";Document Reference
js
document.body; document.head;
document.cookie;
document.readyState; // "loading" | "interactive" | "complete"Element Reference
js
el.id; el.className; el.children; el.parentElement;
el.getAttribute("href");
el.remove();HTML Events
js
el.addEventListener("click", (e) => console.log(e.target));
el.addEventListener("input", (e) => console.log(e.target.value));
document.addEventListener("DOMContentLoaded", () => { ... });
el.removeEventListener("click", handler);HTML First
js
document.addEventListener("DOMContentLoaded", () => {
// pastikan DOM siap sebelum manipulasi elemen
});
// alternatif: taruh <script> sebelum </body>, atau pakai atribut `defer`Window API
js
window.innerWidth; window.innerHeight;
window.location.href; window.location.reload();
window.localStorage.setItem("key", "value");
window.localStorage.getItem("key");
window.history.back();Fetch API
js
async function getUser(id) {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error("Gagal fetch");
return res.json();
}
fetch("/api/users", { method: "POST", body: JSON.stringify(data) });JSON
js
JSON.stringify({ name: "SaidQB", age: 8 }); // object -> string
JSON.parse('{"name":"SaidQB"}'); // string -> object
JSON.stringify(data, null, 2); // pretty print, indent 2Temporal
js
// API baru pengganti Date (masih proposal, mulai didukung di browser terbaru)
const now = Temporal.Now.plainDateTimeISO();
const date = Temporal.PlainDate.from("2026-08-23");
date.add({ days: 7 });Functions (Advanced)
js
function counter() {
let count = 0;
return () => ++count; // closure: fungsi "ingat" scope tempat dia dibuat
}
const inc = counter();
inc(); inc(); // 1, 2
(function () { console.log("IIFE"); })(); // langsung jalan sekaliObjects (Advanced)
js
const obj = Object.freeze({ x: 1 }); // immutable, tidak bisa diubah
Object.defineProperty(obj, "y", { get() { return this.x * 2; } });
class Point {
#x; // private field
constructor(x) { this.#x = x; }
get x() { return this.#x; }
}Classes
js
class User {
constructor(name, email) {
this.name = name;
this.email = email;
}
greet() { return `Halo, saya ${this.name}`; }
static create(name) { return new User(name, ""); } // static method
}
class Admin extends User {
constructor(name, email) { super(name, email); }
}Asynchronous
js
async function getUser(id) {
const res = await fetch(`/api/users/${id}`);
return res.json();
}
Promise.all([getUser(1), getUser(2)]); // jalan paralel
Promise.race([getUser(1), timeout(5000)]);
getUser(1).then((u) => console.log(u)).catch((e) => console.error(e));Modules
js
export function add(a, b) { return a + b; }
export default class User {}
import User, { add } from "./user.js";
import * as utils from "./utils.js";Meta & Proxy
js
const handler = {
get(target, prop) { return prop in target ? target[prop] : `no ${prop}`; },
};
const proxy = new Proxy({ x: 1 }, handler);
proxy.x; proxy.y; // "no y"
Reflect.has(proxy, "x");Typed Arrays
js
const buffer = new ArrayBuffer(16);
const view = new Int32Array(buffer);
view[0] = 42;
const floats = new Float64Array([1.1, 2.2, 3.3]);DOM Navigation
js
el.parentNode; el.parentElement;
el.children; el.firstElementChild; el.lastElementChild;
el.nextElementSibling; el.previousElementSibling;Graphics
js
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 100, 50);