⬅ Previous TopicJava Cheat Sheet
Next Topic ⮕Kotlin Cheat Sheet
var
is function-scoped; let
and const
are block-scoped. Use const
by default unless reassignment is needed.
var a = 1;
let b = 2;
const c = 3;
var
is function-scoped; let
and const
are block-scoped. Use const
by default unless reassignment is needed.
var a = 1;
let b = 2;
const c = 3;
Primitive types: string, number, boolean, null, undefined, symbol, bigint.
let str = "Hello";
let num = 42;
let isTrue = true;
let nothing = null;
let notDefined;
Arithmetic (+, -, *, /), Comparison (==, ===, !=, !==), Logical (&&, ||, !).
let x = 5 + 3;
let isEqual = 5 === "5"; // false
let logic = true && false;
Automatic (coercion) or manual (conversion).
let n = "42";
let num = Number(n);
console.log("5" + 1); // "51" (coercion)
Use backticks and ${}
for interpolation.
let name = "Alice";
let message = `Hello, ${name}!`;
if (x > 0) {
console.log("Positive");
} else {
console.log("Not positive");
}
switch(day) {
case "Mon": console.log("Start"); break;
default: console.log("Other");
}
for (let i = 0; i < 5; i++) {
console.log(i);
}
while (x > 0) {
x--;
}
for (let key in obj) {}
for (let value of arr) {}
for (let i = 0; i < 10; i++) {
if (i === 5) break;
if (i % 2 === 0) continue;
}
function greet() { return "Hi"; }
const sayHi = function() { return "Hi"; };
const add = (a, b) => a + b;
function sum(a = 1, ...rest) {
return a + rest.length;
}
arr.forEach(function(item) {
console.log(item);
});
function outer() {
let count = 0;
return function() {
return ++count;
}
}
(function() {
console.log("Run immediately");
})();
let arr = [1, 2, 3];
arr.map(x => x * 2);
arr.filter(x => x > 1);
arr.reduce((a, b) => a + b);
let obj = { a: 1, b: 2 };
Object.keys(obj);
Object.values(obj);
Object.entries(obj);
// this keyword
function show() { console.log(this); }
// Scope & Hoisting
console.log(a); var a = 5;
// Strict Mode
"use strict";
// Destructuring
let [a, b] = [1, 2];
let { x, y } = { x: 1, y: 2 };
// Spread & Rest
let arr1 = [1, 2];
let arr2 = [...arr1, 3];
// Optional Chaining
obj?.prop?.sub
// Nullish Coalescing
let val = input ?? "default";
// Callbacks
setTimeout(() => console.log("Done"), 1000);
// Promises
fetch(url)
.then(res => res.json())
.catch(err => console.error(err));
// async/await
async function getData() {
try {
let res = await fetch(url);
let data = await res.json();
} catch (err) {
console.error(err);
}
}
// DOM
let el = document.getElementById("id");
el.textContent = "Hello";
// Events
el.addEventListener("click", () => alert("Clicked"));
// Storage
localStorage.setItem("key", "value");
sessionStorage.getItem("key");
// Fetch
fetch("/api").then(r => r.json());
// Console
console.log("msg");
console.table([1, 2, 3]);
try {
throw new Error("Oops");
} catch (e) {
console.error(e.message);
} finally {
console.log("Always runs");
}
// JSON
let obj = JSON.parse('{"a":1}');
let str = JSON.stringify(obj);
// Date
let now = new Date();
// Math
Math.random();
Math.floor(4.7);
// Regex
let match = "hello".match(/h/);
// Modules
// file1.js
export const x = 1;
// file2.js
import { x } from "./file1.js";
// Classes
class Person {
constructor(name) { this.name = name; }
greet() { return `Hi ${this.name}`; }
}
// Enhanced Object Literals
let a = 1;
let obj = { a, greet() { return "Hi"; } };
// Map / Set
let m = new Map();
m.set("key", "value");
let s = new Set([1, 2]);
// Short-circuit Evaluation
let val = input || "default";
// Event Loop
setTimeout(() => console.log("macro"));
Promise.resolve().then(() => console.log("micro"));
// Debounce
function debounce(fn, delay) {
let timeout;
return function() {
clearTimeout(timeout);
timeout = setTimeout(fn, delay);
};
}
// Throttle
function throttle(fn, limit) {
let inThrottle;
return function() {
if (!inThrottle) {
fn();
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
Comments