beginner

Modern JavaScript Essentials

The parts of JavaScript you will use every day: const and let, functions and arrow functions, template literals, objects and arrays, destructuring and spread, map/filter/reduce, equality and truthiness, and modules. Practise with array methods and destructuring.

50 min

1. Why “modern” JavaScript

JavaScript has changed a great deal since 2015 (ES2015, often called ES6, and yearly releases since). Code written in the modern style is shorter, safer and easier to read. Every current browser supports it, and every tutorial, framework and job assumes you know it. You can try everything here in the browser’s DevTools console (open it with F12).

2. Variables: const and let

const siteName = 'Learn.GT';   // cannot be reassigned
let visits = 0;                // can be reassigned
visits = visits + 1;
  • Use const by default. Use let only when the variable changes.
  • Do not use var. It is function-scoped and hoisted, which causes confusing bugs. let and const are block-scoped: they exist only inside the { } where they are declared.
  • const stops reassignment, not change: a const array can still have items pushed to it.

3. Types and truthiness

Values are one of: string, number, boolean, null, undefined, bigint, symbol and object (which includes arrays, functions and dates).

  • typeof 42 is "number". Beware typeof null === "object" (a historic mistake) and NaN (a number that means “not a number”).
  • Falsy values: false, 0, '', null, undefined, NaN. Everything else is truthy, including '0', [] and {}.
  • Use === and !==. Loose equality (==) converts types: 0 == '' is true.
  • Optional chaining and nullish coalescing handle missing data gracefully:
const city = user?.address?.city ?? 'Unknown';   // no error if address is missing; ?? only replaces null/undefined
const count = input || 10;                        // careful: || also replaces 0 and ''

4. Functions

function add(a, b) { return a + b; }            // declaration (hoisted)
const add2 = (a, b) => a + b;                    // arrow function, implicit return
const greet = (name = 'friend') => `Hello, ${name}!`;   // default parameter + template literal
  • Template literals (backticks) embed expressions with ${...} and can span lines.
  • Arrow functions are short and do not have their own this, which makes them ideal for callbacks.
  • Functions are values: you can store them, pass them to other functions (callbacks) and return them.
  • A closure is a function that remembers the variables around it:
function counter() {
  let n = 0;
  return () => ++n;
}
const next = counter();
next(); next();   // 1, then 2

5. Objects and arrays

const student = { name: 'Ada', tier: 'pro', xp: 320 };
student.xp += 10;
student['name'];              // bracket access
Object.keys(student);         // ['name', 'tier', 'xp']
Object.entries(student);      // [['name','Ada'], ...]

const scores = [70, 85, 90];
scores.push(100);
scores.length;                // 4

Destructuring and spread

Destructuring unpacks values into variables, with defaults and renaming:

const { name, tier = 'free', xp: points } = student;   // points is student.xp
const [first, , third] = scores;                       // skip the second
function show({ name, tier = 'free' }) { return `${name} (${tier})`; }

Spread (...) copies or merges, creating new values rather than changing old ones:

const updated = { ...student, xp: student.xp + 50 };   // new object; student is unchanged
const more = [...scores, 95];                          // new array
const merged = { ...defaults, ...options };            // later keys win
Math.max(...scores);                                   // spread into arguments

Preferring new values over in-place changes (“immutability”) makes programs easier to follow and is how frameworks detect that something changed.

6. Array methods: map, filter, reduce

These replace most for loops. Each takes a function and returns a new value without changing the array:

const students = [
  { name: 'Ada', tier: 'pro', xp: 320 },
  { name: 'Bode', tier: 'free', xp: 90 },
  { name: 'Chidi', tier: 'pro', xp: 510 },
];

students.map((s) => s.name);                       // ['Ada', 'Bode', 'Chidi']
students.filter((s) => s.tier === 'pro');          // only the pro students
students.reduce((sum, s) => sum + s.xp, 0);        // 920
students.find((s) => s.xp > 400);                  // the first match (or undefined)
students.some((s) => s.xp > 500);                  // true
students.every((s) => s.xp > 100);                 // false
[...students].sort((a, b) => b.xp - a.xp);         // sort a COPY (sort changes the array it is called on)
students.includes(x); [1, 2, 2, 3].flat(); Array.from({ length: 3 }, (_, i) => i);

Chain them to read like a sentence:

const proNames = students
  .filter((s) => s.tier === 'pro')
  .sort((a, b) => b.xp - a.xp)
  .map((s) => s.name);

(Call .sort on a copy when you do not want to reorder the original: [...students].sort(...), or toSorted() in current browsers.)

7. Modules

Split code into files with ES modules:

// math.js
export const tax = 0.075;
export function withTax(price) { return price * (1 + tax); }
export default function round(n) { return Math.round(n * 100) / 100; }

// app.js
import round, { withTax, tax } from './math.js';
<script type="module" src="app.js"></script>

Modules have their own scope (no accidental globals), run in strict mode, and load once. Tools such as Vite bundle them for production. Named exports are easier to refactor than default exports.

8. Habits that prevent bugs

  • Prefer const, ===, template literals and array methods.
  • Keep functions small and pure (same input, same output, no hidden changes).
  • Handle null and undefined deliberately with ?. and ??.
  • Use 'use strict' (modules are strict already) and a linter (ESLint) and a formatter (Prettier).
  • Read errors in the console: the message and line number usually tell you what is wrong.

9. Your turn: array methods and destructuring

Complete four functions. The students list is already defined in the script.

  • totalXp(list): the sum of every student’s xp (use reduce).
  • proNames(list): the names of pro students, highest xp first, without changing the original array.
  • describe(student): use destructuring with a default and return text like Ada (pro): 320 XP. If tier is missing, it should say free.
  • withBonus(student, bonus): return a new object with xp increased by bonus, leaving the original unchanged (use spread).
Array methods, destructuring and spread
PREVIEW

Your tasks

  • ○The script runs without errors and logs something
  • ○totalXp(students) is 1160
  • ○proNames(students) is ['Chidi','Ada','Esosa']
  • ○proNames does not reorder the original students array
  • ○describe(students[0]) is 'Ada (pro): 320 XP'
  • ○describe uses the default tier 'free' when tier is missing
  • ○withBonus returns a new object with the extra xp
  • ○withBonus leaves the original object unchanged

10. What you learned

You write const by default, use ===, template literals and arrow functions, unpack and copy with destructuring and spread, and replace loops with map, filter and reduce. These patterns are the vocabulary of every modern JavaScript framework. Next: code that waits, such as loading data from a server.

🧪 Want to practise this on your own computer? See how to set up your lab →

🤖

Need clarification? Ask GT

Hi, I'm GT — your AI tutor for Modern JavaScript Essentials. What would you like to know?
📝

Knowledge Check

1 of 4

Which declaration should you use by default?

Report a problem

About: /lessons/modern-javascript-essentials