JS Documentation

Intro to Modern JS

Modern JavaScript (ES6+) brings powerful features to simplify code, improve performance, and enhance readability. Features like arrow functions, modules, and async/await make JavaScript more expressive and easier to manage.

let & const

let and const are modern alternatives to var. Use const by default and let when reassignment is needed.

const name = "JS";
            let count = 0;
            count++;

Arrow Functions

Arrow functions provide a shorter syntax and lexical this.

// Traditional
            function add(a, b) {
              return a + b;
            }
            
            // Arrow
            const add = (a, b) => a + b;

Template Literals

Use backticks ` for multiline strings and embedding expressions.

const name = "JS";
            console.log(`Hello, ${name}!`);

Destructuring

Extract values from arrays or objects with ease.

const user = { name: "Alex", age: 25 };
            const { name, age } = user;
            
            const [x, y] = [10, 20];

Spread & Rest

Spread copies values. Rest collects remaining values.

const arr1 = [1, 2];
            const arr2 = [...arr1, 3]; // [1, 2, 3]
            
            function sum(...numbers) {
              return numbers.reduce((a, b) => a + b);
            }

Modules

Use import and export to split code across files.

// utils.js
            export const square = x => x * x;
            
            // main.js
            import { square } from './utils.js';

Promises

Promises handle asynchronous operations.

fetch('/api/data')
              .then(res => res.json())
              .then(data => console.log(data))
              .catch(err => console.error(err));

Async/Await

Async functions make async code look synchronous.

async function loadData() {
              try {
                const res = await fetch('/api/data');
                const data = await res.json();
                console.log(data);
              } catch (err) {
                console.error(err);
              }
            }

Reference

Modern JavaScript documentation sourced and adapted from MDN Web Docs.