~/saidqb cat ecosystem/programming-language/javascript.md
JS
JavaScript
Bahasa scripting untuk web, frontend & backend (Node.js)
commit by saidqb
Requirements
- Node.js
20.xLTS ke atas — cek nodejs.org npm(sudah include di instalasi Node.js)
node --version && npm --version
Variabel & Tipe
const name = "SaidQB"; // tidak bisa di-reassign
let age = 8, active = true; // bisa di-reassign
var legacy = "hindari var"; // function-scoped, sebaiknya dihindari
const tags = ["js", "go", "php"];
const config = { debug: true, port: 8000 };
`Halo ${name}, umur ${age} tahun` // template literal
typeof age; Array.isArray(tags);
Function & Arrow Function
function greet(name, greeting = "Halo") {
return `${greeting}, ${name}!`;
}
const square = (x) => x * x;
const total = (...args) => args.reduce((a, b) => a + b, 0); // rest params
Array Methods
tags.map((t) => t.toUpperCase());
tags.filter((t) => t.length > 2);
tags.reduce((acc, t) => acc + t, "");
tags.find((t) => t === "go");
tags.some((t) => t === "js"); tags.every((t) => t.length > 0);
tags.includes("php");
[...tags].sort(); [...tags].reverse(); // spread biar tidak mutate array asli
Object & Destructuring
const { name, age } = user; // object destructuring
const [first, ...rest] = tags; // array destructuring
const merged = { ...config, timeout: 30 }; // spread merge
Object.keys(config); Object.values(config); Object.entries(config);
Async, Promise, Fetch
async function getUser(id) {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error("Gagal fetch");
return res.json();
}
getUser(1).then((u) => console.log(u)).catch((e) => console.error(e));
Promise.all([getUser(1), getUser(2)]); // jalan paralel
Class
class User {
constructor(name, email) {
this.name = name;
this.email = email;
}
greet() {
return `Halo, saya ${this.name}`;
}
}
class Admin extends User {
constructor(name, email) {
super(name, email);
}
}
Module (ESM)
export function add(a, b) { return a + b; }
export default class User {}
import User, { add } from "./user.js";
import * as utils from "./utils.js";