JavaScript Reference
0. Basics
0.1 Hello World
// console.log prints to stdout with a trailing newline
console.log("Hello, World!");Hello, World!
0.2 Building & Running
JavaScript is an interpreted language typically run in a browser or a runtime like Node.js.
# Execute a script using Node.js
node script.js
# For browsers, include via HTML
# <script type="module" src="script.js"></script>Hello, World!
0.3 Comments
// This is a single-line comment
/* This is a
multi-line comment */(No output)
0.4 Imports (import/export)
Modern JavaScript uses ECMAScript Modules (ESM).
// math.js
export const add = (a, b) => a + b;
export default add;
// main.js
import { add } from './math.js';
import addAlias from './math.js'; // Default import(No output)
0.5 Exit Codes
Exit codes are specific to the environment (e.g., Node.js).
// Terminate the process with a status code (0 for success, non-zero for error)
// process.exit(1); (Process exits with status 1)
0.6 Error Handling
try {
throw new Error("Something went wrong");
} catch (error) {
console.log(`Caught: ${error.message}`);
} finally {
console.log("Cleanup complete");
}Caught: Something went wrong
Cleanup complete
1. Environment & Time
1.1 Variable Declaration
const constant = 10; // Block-scoped, immutable reference
let mutable = 5; // Block-scoped, mutable variable
var legacy = 1; // Function-scoped (avoid in modern JS)(No output)
1.2 Integer Types (Number/BigInt)
JavaScript Number is a 64-bit float.
BigInt handles arbitrary-precision
integers.
const num = 42;
const large = 9007199254740991n; // BigInt literal
const maxSafe = Number.MAX_SAFE_INTEGER;
console.log(maxSafe);9007199254740991
1.3 Casting
const s = "123";
const n = Number(s); // 123
const b = Boolean(1); // true
const str = String(42); // "42"
const i = parseInt("10px", 10); // 10(No output)
1.4 Truthiness
Values that are “falsy”: false,
0, -0, 0n,
"", null, undefined,
and NaN. Everything else is “truthy”.
if ("") console.log("True"); else console.log("False");
if ([]) console.log("Empty array is truthy");False
Empty array is truthy
1.5 Environment Vars
Environment variables are accessed via
process.env in Node.js.
// In Node.js environment
const apiKey = process.env.API_KEY || "default_key";
console.log(apiKey);default_key (or environment value)
1.6 Time
const now = new Date();
console.log(now.toISOString()); // ISO 8601 string
const timestamp = Date.now(); // Current time in milliseconds
console.log(typeof timestamp);2024-01-01T00:00:00.000Z (example)
number
2. Operators & Regex
2.1 Arithmetic/Logic
let x = 10 + 5 * 2; // 20
let pow = 2 ** 3; // 8
let logic = true && (false || !false); // true
let nullish = null ?? "default"; // "default"(No output)
2.2 Regex
const regex = /ID: (\d+)/i;
const match = "User ID: 123".match(regex);
if (match) {
console.log(match[1]); // 123
}123
3. Argument Parsing
3.1 CLI Argument Parsing
In Node.js, process.argv contains the
command-line arguments.
// node script.js --user=admin
const args = process.argv.slice(2);
console.log(args);[ '--user=admin' ]
4. Functions & Memory
4.1 Declaration/Returns
function greet(name) {
return `Hello, ${name}`;
}
const square = (x) => x * x; // Arrow function
console.log(greet("World"));
console.log(square(4));Hello, World!
16
4.2 References/Pointers
Objects and Arrays are passed by reference. Primitives are passed by value.
const obj = { val: 10 };
const modify = (o) => { o.val = 20; };
modify(obj);
console.log(obj.val);20
5. Loops & Iteration
5.1 Basic Loops
for (let i = 0; i < 3; i++) {
console.log(i);
}
let j = 0;
while (j < 2) {
console.log(j++);
}0
1
2
0
1
5.2 Break/Continue
for (let i = 0; i < 5; i++) {
if (i === 1) continue;
if (i === 3) break;
console.log(i);
}0
2
5.3 Iterating Collections
const arr = ["a", "b"];
arr.forEach((val, index) => console.log(`${index}: ${val}`));
for (const val of arr) {
console.log(val);
}0: a
1: b
a
b
6. Strings & Files
6.1 Manipulation
const s = "JavaScript";
console.log(s.slice(0, 4)); // "Java"
console.log(s.toUpperCase()); // "JAVASCRIPT"
console.log(`${s} is fun`); // Template literalJava
JAVASCRIPT
JavaScript is fun
6.2 Path Joining (generic)
Using the URL API for cross-platform path
handling or Node’s path.
// Generic approach using URL
const base = "https://example.com/api/";
const endpoint = "users";
const full = new URL(endpoint, base).href;
console.log(full);https://example.com/api/users
6.3 Streaming I/O (generic Streams API)
Modern JavaScript uses the Web Streams API.
const stream = new ReadableStream({
start(controller) {
controller.enqueue("Chunk 1");
controller.close();
}
});(No output)
6.4 Read to Memory
Using fetch (Web API) or fs
(Node.js).
// Node.js example (CommonJS or ESM with prefix)
// import { readFile } from 'node:fs/promises';
// const content = await readFile('file.txt', 'utf8');(No output)
7. Binary & Bitwise
7.1 Allocation/Packing
const buffer = new ArrayBuffer(8); // 8 bytes
const view = new DataView(buffer);
view.setInt32(0, 42); // Set int32 at offset 0
const uint8 = new Uint8Array(buffer);
console.log(uint8[0]);0 (or 42 depending on endianness/offset)
7.2 Bitwise Ops
console.log(5 & 1); // AND (1)
console.log(5 | 1); // OR (5)
console.log(1 << 2); // Shift Left (4)1
5
4
7.3 Hex Conversion
const hex = (255).toString(16); // "ff"
const num = parseInt("ff", 16); // 255
console.log(hex, num);ff 255
8. Collections & JSON
8.1 Lists/Maps/Sets
const list = [1, 2, 3];
const map = new Map([["key", "value"]]);
const set = new Set([1, 1, 2]); // {1, 2}
console.log(map.get("key"));
console.log(set.size);value
2
8.2 JSON Parsing
const json = '{"id": 1, "name": "JS"}';
const obj = JSON.parse(json);
const str = JSON.stringify(obj);
console.log(obj.name);JS
9. Systems & Networking
9.1 TCP
Requires a runtime like Node.js (net
module).
// Node.js
// import net from 'node:net';
// const server = net.createServer((socket) => { ... }).listen(8080);(No output)
9.2 UDP
Requires a runtime like Node.js (dgram
module).
// Node.js
// import dgram from 'node:dgram';
// const client = dgram.createSocket('udp4');(No output)
9.3 Concurrency (Promises, Async/Await)
const delay = (ms) => new Promise(res => setTimeout(res, ms));
async function run() {
console.log("Start");
await delay(10);
console.log("End");
}
run();Start
End
9.4 SQLite (generic SQL interop)
Requires a library (e.g., sqlite3 or
better-sqlite3).
// import Database from 'better-sqlite3';
// const db = new Database(':memory:');
// const row = db.prepare('SELECT "JS" as name').get();(No output)