← Back to Tutorials Chapter 5

JavaScript & TypeScript Features

Modern JavaScript Features

Node.js supports the latest ECMAScript features. Here are some essential ones:

Destructuring

// 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 & Rest Operators

// 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 & Template Literals

// 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}`);

Optional Chaining & Nullish Coalescing

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;

The Process Object

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 Basics

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' };
}

TypeScript Configuration

// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "CommonJS",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

Advanced TypeScript

// 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';
}

Linting & Formatting

// 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"
}
Exercise: Create a TypeScript file that defines an interface for a "Task" (id, title, completed, dueDate), implements a function to filter incomplete tasks, and logs them. Compile and run with npx tsc.