Node.js supports the latest ECMAScript features. Here are some essential ones:
// Object destructuring
const person = { name: 'Alice', age: 30, city: 'NYC' };
const { name, age } = person;
console.log(name, age);
// Array destructuring
const colors = ['red', 'green', 'blue'];
const [first, ...rest] = colors;
console.log(first, rest);
// Spread (expand arrays/objects)
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2); // [1, 2, 3, 4, 5]
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
console.log(obj2); // { a: 1, b: 2, c: 3 }
// Rest (collect remaining arguments)
function sum(...nums) {
return nums.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
// Arrow functions
const double = x => x * 2;
const greet = name => `Hello, ${name}!`;
// Template literals
const user = 'Node';
const version = 18;
console.log(`Running ${user} version ${version}`);
const user = { profile: { name: 'Alice' } };
// Optional chaining - no error if intermediate is null/undefined
console.log(user?.profile?.name); // Alice
console.log(user?.address?.city); // undefined
// Nullish coalescing - use default only for null/undefined
const port = process.env.PORT ?? 3000;
process is a global object with information about the current Node.js process.
// Environment variables
console.log(process.env.NODE_ENV);
console.log(process.env.PATH);
// Command line arguments
console.log(process.argv);
// Exit process
process.exit(0); // Success
process.exit(1); // Error
// Process events
process.on('exit', (code) => {
console.log(`Process exiting with code ${code}`);
});
process.on('uncaughtException', (err) => {
console.error('Uncaught exception:', err);
process.exit(1);
});
// Current working directory
console.log(process.cwd());
TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It's widely used in the Node.js ecosystem.
// Install: npm install -g typescript
// Or: npx tsc
// Basic types
let name: string = 'Node';
let version: number = 18;
let isActive: boolean = true;
let data: any = 'could be anything';
let nullable: string | null = null;
// Interfaces
interface User {
id: number;
name: string;
email?: string; // Optional property
}
function getUser(id: number): User {
return { id, name: 'Alice' };
}
// tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "CommonJS",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
// Generics
function wrap<T>(value: T): T[] {
return [value];
}
const wrapped = wrap(42); // number[]
const wrappedStr = wrap('hi'); // string[]
// Utility types
interface Todo {
title: string;
completed: boolean;
}
const partial: Partial<Todo> = { title: 'Learn Node' };
const readonly: Readonly<Todo> = { title: 'Done', completed: true };
// readonly.title = 'Try'; // Error!
// Type guards
function isString(val: unknown): val is string {
return typeof val === 'string';
}
// ESLint configuration (.eslintrc.json)
{
"env": { "node": true, "es2022": true },
"extends": ["eslint:recommended"],
"parserOptions": { "ecmaVersion": "latest" },
"rules": {
"no-unused-vars": "warn",
"no-console": "off"
}
}
// Prettier configuration (.prettierrc)
{
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "es5"
}
npx tsc.