T5 Modern JavaScript (ES6 and later) · Lesson 1
Modern JavaScript: strict mode, let, const and arrows
How JavaScript changes year by year, and what ES2015 changed most: strict mode and the slips it turns into errors, let and const in loops, freezing an object, arrow functions in depth, and how to choose between the ways of writing a function.
- say what ECMAScript, ES2015 and the yearly editions are, and how to check what a browser supports
- switch on strict mode, and say which silent slips it turns into errors
- explain why let in a loop gives each turn its own counter, and var does not
- freeze an object with Object.freeze, and say why it is only one level deep
- write arrow functions that return objects, and say what arrows do not have
- choose between a declaration, an arrow and a method for each job
The back cover
JavaScript keeps changing, a little every year. The biggest change came with ES2015, and most code written today uses what it brought. Old code is still everywhere too, so a programmer must read both, and know which habits have been replaced and why.
These pages show how a feature gets into the language and how to check where it works. They show strict mode, which turns silent slips into errors. They show let in loops, how to freeze an object, and arrow functions in depth. Last comes how to choose the right form of function for each job.
Before you start
The story: Three bells, one ferry
Master Hakim Verge leads you up the narrow stair to the Clock Tower's upper floor. The clocks here are older, and some were wound by clockmakers long gone. One of them sets the evening's reminder bells, one for each ferry: 6.15, 6.45 and 7.30.
Every evening all three bells ring together, at 7.30, and nobody hears a word about the first two ferries.
"This script was written in the old style of the Script," says Master Verge. "Old is not wrong. But the old rules hide surprises, and the city wrote new rules because of them. Learn what changed, and why, and you can read every clock on this floor."
The JavaScript step taught the language as it is written today. But JavaScript has been changing for thirty years, and the code you will read, in old projects, in answers on the web and in libraries, was written at every stage of that change. This step, modern JavaScript, is about the language's newer parts and why they came. It starts with the rules that changed most: strict mode, let and const, and arrow functions.
It builds on these ideas. Each one has a tiny example, so you can check that you remember it.
| What you already know | A tiny example | Where it comes back |
|---|---|---|
| let, const and var. | let count = 0; | Why let came, through a bug that var causes. |
| Block scope. | A let lives until its closing brace. | Each turn of a loop is a block of its own. |
| Closures. | A function that remembers its names. | Functions made in a loop. |
| Accidental globals. | total = 10; with no let. | Strict mode makes it an error. |
| const objects. | A const object can still change inside. | Object.freeze stops that. |
| Arrow functions. | (n) => n * 2 | What they return, and what they lack. |
| this in methods. | this === shop | Arrows take this from outside. |
| Errors. | TypeError, SyntaxError | The errors strict mode adds. |
| Modern operators. | ?., ??, ** | When each arrived. |
| MDN. | The reference used in every lesson. | Its tables of browser support. |
By the end of this lesson you will be able to:
- say what ECMAScript, ES2015 and the yearly editions are, and how to check what a browser supports;
- switch on strict mode, and say which silent slips it turns into errors;
- explain why let in a loop gives each turn its own counter, and var does not;
- freeze an object with
Object.freeze, and say why it is only one level deep; - write arrow functions that return objects, and say what arrows do not have;
- choose between a declaration, an arrow and a method for each job.
How to follow this lesson
Every block on this page runs. Several show the same code in an older and a newer form, side by side; run both, and look for the line where their answers part.
In one line
Modern JavaScript is the language's newer rules and features; this lesson starts with the ones that changed everyday code most.
How JavaScript changes
At a glance
A school's syllabus is revised from time to time. Old textbooks stay on the shelves, and some students still learn from them. But a student who knows only the old syllabus will be puzzled by this year's question paper.
JavaScript has a syllabus too: the ECMAScript standard, published by Ecma International and revised every year since ES2015. That edition changed everyday code the most, and both old and new code are everywhere. Before using a new feature, check MDN's Browser compatibility table, which says in which browsers and in Node it works.
Take a guess: Must a new feature already work in browsers before it can join the standard?
A school's syllabus is revised from time to time. Old textbooks are not burned; they stay on shelves, and some students still learn from them. But a student who knows only the old syllabus will be puzzled by this year's question paper. JavaScript has a syllabus too, revised every year, and both old and new code are everywhere.
The standard that says exactly what JavaScript is and how it behaves, published by a body called Ecma International. Browsers and Node build their JavaScript engines to follow it. The standard's number is ECMA-262.
Each revision of the standard is an edition. MDN's overview of JavaScript explains how they are named. Early editions came every few years and were numbered: ES3, ES5. The sixth, ES6, was a large one, and is also called ES2015, after its year. Since then, a new edition has been published every year and named by its year: ES2016, ES2017 and so on.
| Edition | Some of what it brought | Met in this path |
|---|---|---|
| ES2015 (ES6) | let and const, arrow functions, template literals, classes, modules, promises | the JavaScript step, and this step |
| ES2016 | the power operator ** | the Learning to learn step |
| ES2020 | ?. and ??, BigInt | the values and conditionals lessons |
| ES2021 | replaceAll, the separator _ in numbers, ||= and ??= | the values lesson, and this lesson |
| ES2022 | at(), Object.hasOwn | the arrays lesson, and this lesson |
ES2015 changed the everyday look of JavaScript more than any edition before or since, which is why "modern JavaScript" often means "JavaScript since ES2015". Every block of the JavaScript step used it. This block uses a feature from each row of the table:
console.log(2 ** 10, 1_000, typeof 10n, null ?? "x", ({}).a?.b);
console.log([1, 2, 3].at(-1), Object.hasOwn({ a: 1 }, "a"), "a-b".replaceAll("-", "+"));
1024 1000 bigint x undefined
3 true a+b
Two of ES2021's operators are new here. a ||= b sets a to b only when a is falsy, and a ??= b only when a is null or undefined: the two defaults of the conditionals lesson, written as assignments.
let name = "";
name ||= "Guest";
let score = 0;
score ??= 10;
console.log(name, score);
Guest 0
How a feature gets in
A new feature starts as a proposal, written in public by the committee that keeps the standard, called TC39. MDN's overview describes the stages a proposal passes through. Engines such as Chrome's and Node's usually start shipping a feature late in that process, before the year's edition is published. So a feature can work in your browser before its edition exists, and an older browser can lack a feature that the standard has had for years.
Will it work where my code runs?
Every MDN reference page ends with a section called Browser compatibility: a table of browsers and versions, and whether each supports the feature. Node is in the table too. This path checks every lesson against named versions, which each lesson's page states. When you write for old browsers, check the table first. When it says a feature is not supported somewhere you care about, use an older way, or a tool that rewrites new code into old, which later steps of this path meet.
Worked example 1
A colleague's code uses cart.at(-1) and must run on a school's old computers. How do you find out whether it is safe?
What we have: a method, at, and old computers whose browser is not known
What we need: whether those browsers support it
The plan: find the browser and version on the old computers, then read MDN's Browser compatibility table for Array.prototype.at
- Find what the computers run: the browser's About page shows its version.
- Open MDN's page for the at method of arrays and scroll to Browser compatibility.
- Compare: if the table's first supporting version is newer than theirs, the method is missing there, and
cart[cart.length - 1]does the same job in the older way.
Read MDN's Browser compatibility table against the browser's version; if it is too old, use cart[cart.length - 1].
Check: the older form gives the same item on every browser, as the arrays lesson showed.
A path that fails: trying it on your own new laptop and calling it safe. Your browser updates itself; theirs may not.
When you are stuck: old and new code look different
A var where you expected let, or function where you expected an arrow, usually means older code, not wrong code.
For any feature, MDN's page names it and shows its Browser compatibility.
If something works in your browser but not in a user's, compare versions before anything else.
Remember that ES6 and ES2015 are the same edition.
Your turn
What is another name for ES6?Tap to reveal
- After ES6, editions are named by year.
- ES6 was published in 2015.
ES2015.
Where on MDN do you check whether a feature works in a given browser?Tap to reveal
- Every reference page ends with a table of browsers and versions.
The Browser compatibility section.
Why might a feature work in your browser before the year's edition is published?Tap to reveal
- Engines usually ship a feature late in the proposal process, before the edition comes out.
Because engines ship features before the edition is published.
Did you know?
Working before it is written
A feature joins JavaScript only after it already works. TC39, the committee that writes the standard, asks for two things before a proposal reaches its last stage: two compatible implementations that pass Test262, the standard's own tests, and real experience with shipping implementations, such as two independent engines. So browsers often have a feature before the edition that names it.
Why it fits here: It explains this topic's advice to check MDN's tables: a feature reaches the engines first, and the yearly edition records it afterwards.
Source: TC39: The TC39 Process
What ECMA stood for
The ECMA in ECMAScript was once a set of initials: European Computer Manufacturers Association. Ecma's own history says the association officially came into being on 17 May 1961. In 1994 it changed its name to Ecma International, to reflect its work around the world. Its standard ECMA-262, the one that defines JavaScript, reached its 17th edition in June 2026.
Why it fits here: It explains the odd name of this topic's standard: ECMAScript is named after the body that publishes it.
Sources: Ecma International: History; Ecma International: ECMA-262
In one line
JavaScript is defined by the ECMAScript standard, revised every year since ES2015, the edition that changed everyday code most. MDN's Browser compatibility tables say where each feature works.
Strict mode: silent slips made loud
At a glance
Some exams are marked leniently: a spelling slip is ignored, a missing unit forgiven. That feels kind, until the habit costs marks in a strict exam. Early JavaScript was a lenient marker, so that pages would not break.
Strict mode is the strict marker. The line "use strict"; at the top of a script turns silent slips into errors, at the line where they happen. Among them are a name assigned without being declared, a write that cannot work, an old base 8 number and a repeated parameter. Modules and classes are always strict.
Take a guess: Why is strict mode switched on with a plain string instead of a keyword?
Some exams are marked leniently: a spelling slip is ignored, a missing unit forgiven. That feels kind, until the habit costs marks in a strict exam. Early JavaScript was a lenient marker. It let many slips pass in silence, so that pages would not break. Strict mode is the strict marker: it turns those slips into errors, at the line where they happen.
A way of running JavaScript in which some silent slips become errors and a few confusing rules are removed. It is switched on by the line "use strict"; at the very top of a script or a function. Modules and classes are always in strict mode.
The JavaScript step promised this lesson twice: in the values lesson, about numbers that start with 0, and in the scope lesson, about accidental globals. Here are those slips and others, each first in ordinary mode, often called sloppy mode, and then in strict mode.
Accidental globals
function f() {
total = 5;
}
f();
console.log(total);
5
"use strict";
function f() {
total = 5;
}
f();
console.log(total);
Uncaught ReferenceError: total is not defined
at f (line 3)
at line 5
In sloppy mode, the assignment to a name never declared quietly made a global, as the scope lesson showed. In strict mode it is a ReferenceError at the exact line, so a misspelt name is caught at once.
Writes that would be ignored
Some writes cannot work, and sloppy mode drops them without a word: a character of a string, or a property of a frozen object, which the next section explains. Strict mode raises a TypeError instead:
"use strict";
let word = "cat";
word[0] = "b";
Uncaught TypeError: Cannot assign to read only property '0' of string 'cat'
at line 3
Confusing old syntax, refused
Strict mode refuses two old pieces of syntax outright, so the program does not start:
"use strict";
let x = 010;
Uncaught SyntaxError: Octal literals are not allowed in strict mode.
"use strict";
function f(a, a) {}
Uncaught SyntaxError: Duplicate parameter name not allowed in this context
The first is the base 8 number of the values lesson, which read 0042 as 34. The second is a function with two parameters of the same name, which sloppy mode allows, the second silently hiding the first.
this in a plain function
Called on its own, not as a method, a plain function in sloppy mode receives the global object as this, which lets it change global names by accident. In strict mode, this is undefined there, so such a mistake fails loudly:
"use strict";
function f() {
return typeof this;
}
console.log(f());
undefined
| Slip | Sloppy mode | Strict mode |
|---|---|---|
| assigning to an undeclared name | makes a global | ReferenceError |
| writing to a string's character, or a frozen property | ignored | TypeError |
| a number written with a leading 0, such as 010 | read in base 8 | SyntaxError |
| two parameters with the same name | allowed | SyntaxError |
| this in a function called on its own | the global object | undefined |
Where do you need the line? In a module, never: modules, which a later lesson of this step teaches, are always strict, and so is the body of every class. Most modern code is written in modules, so most modern code is already strict without the words.
Worked example 2
An old script has a function that is meant to add to a total, but the total on the page never changes. Switch on strict mode to find the slip.
What we have: an old script with a silent bug
What we need: an error that names the slip
The plan: add "use strict"; at the top, run it, and read the error
"use strict";
let total = 0;
function add(price) {
totl = total + price;
}
add(50);
console.log(total);
Uncaught ReferenceError: totl is not defined
at add (line 4)
at line 6
- In sloppy mode, totl would have become a new global, and total would have stayed 0 with no message. Strict mode names the misspelt name and its line.
Strict mode names the slip: totl, at line 4.
Check: spelling it total makes the program print 50.
A path that fails: adding console.log lines to watch total stay at 0. They show that it does not change, but not why; strict mode shows why in one line.
When you are stuck: an old script behaves strangely
Add "use strict"; as its first line and run it: silent slips become errors with lines.
If the script breaks in strict mode, the break is usually a real bug that was hiding.
In a module or a class there is no need for the line; it is already strict.
Read the error's name: ReferenceError for a name, TypeError for a write, SyntaxError for old syntax.
Your turn
What does "use strict"; do to the line count = 1; when count was never declared?Tap to reveal
- In sloppy mode it makes a global.
- In strict mode an assignment to an undeclared name is an error.
It becomes a ReferenceError.
Do you need "use strict"; in a module?Tap to reveal
- Modules are always in strict mode.
No.
Why does strict mode make a write to a frozen object an error instead of ignoring it?Tap to reveal
- An ignored write leaves the program believing it changed something.
- An error stops it at the line, with a message.
So that a write that cannot work is noticed, at its line.
Did you know?
A switch written as a string
Strict mode is switched on by a plain string. The standard defines a Use Strict Directive as a statement that is only the text use strict, in double or single quotes, at the start of a script or a function. To an engine from before strict mode, that line is a string that does nothing, so old browsers run the code on. Even an escape sequence inside the text stops it counting.
Why it fits here: It answers this topic's question about the string: a keyword would have broken old browsers, while a string they could ignore.
Source: ECMAScript Language Specification: Directive Prologues and the Use Strict Directive
Words kept for later
Strict mode also keeps a list of words free for the future. MDN lists them as newly reserved in anticipation of future language features: implements, interface, let, package, private, protected, public, static and yield cannot be names in strict code. Some have since found work, such as let. The standard still lists implements, interface, package, private, protected and public as future reserved words in strict code.
Why it fits here: It shows another job of this topic's strict mode: besides catching slips, it kept names free for the features ES2015 would bring.
Sources: MDN: Strict mode; ECMAScript Language Specification: Keywords and Reserved Words
In one line
"use strict"; at the top of a script turns silent slips into errors: undeclared assignments, ignored writes, base 8 numbers, repeated parameters, and a global this. Modules and classes are always strict.
let in loops: each turn its own counter
At a glance
Before ES2015, var was the only way to make a name, and var ignores blocks. That matters most in a loop that makes functions to be called later, such as handlers or reminders.
A loop written with var has one counter for all its turns, so every function made in it sees the counter's last value. A loop written with let gives each turn its own counter, so each function keeps its own turn. Use const for the item of a for...of loop, and let for a counter.
Take a guess: How can a tool make let work in an old browser that knows only var?
Before ES2015, var was the only way to make a name, and var ignores blocks, as the scope lesson showed. That matters most in a loop that makes functions to be called later, such as handlers or reminders. This is the bug of the three bells.
const bells = [];
for (var i = 0; i < 3; i++) {
bells.push(() => i);
}
console.log(bells.map((ring) => ring()));
[ 3, 3, 3 ]
The loop makes three arrow functions, each meant to remember its own turn: 0, 1 and 2. But var made one i for the whole loop. Each arrow is a closure over that one i, as the scope lesson described, and closures see a name's latest value. By the time the arrows are called, the loop has finished, and the one i holds 3.
const bells = [];
for (let i = 0; i < 3; i++) {
bells.push(() => i);
}
console.log(bells.map((ring) => ring()));
[ 0, 1, 2 ]
One word changed. MDN's page for the for statement explains why: with let, the loop makes a new scope, with a new i, for each turn, and copies the value across. Each arrow closes over its own turn's i, which nothing changes afterwards.
The rule that a for loop whose counter is made with let gives each turn of the loop a fresh copy of the counter, so that a function made in that turn keeps that turn's value.
The old fix, which you will meet in older code, was an IIFE inside the loop, as the scope lesson showed, to give each turn a function scope of its own. let does the same job with no extra code.
const in a for...of loop
In a for...of loop, the name for each item is fresh in each turn too, which is why it can be a const: within one turn it never changes. The habit of the values lesson holds: const by default, let for a counter that the loop itself changes.
const timers = [];
for (const ferry of ["6.15", "6.45", "7.30"]) {
timers.push(() => `Ring for ${ferry}`);
}
console.log(timers.map((t) => t()).join(", "));
Ring for 6.15, Ring for 6.45, Ring for 7.30
Worked example 3
The bell clock of the story sets a reminder for each of three ferries, and each reminder is a function to be called later. Show the bug with var, and the fix.
What we have: three ferry times, and a loop that makes three reminder functions
What we need: each reminder naming its own ferry
The plan: make the reminders in a loop with var and call them afterwards; then change var to let
const times = ["6.15", "6.45", "7.30"];
const old = [];
for (var i = 0; i < times.length; i++) {
old.push(() => times[i]);
}
const fixed = [];
for (let j = 0; j < times.length; j++) {
fixed.push(() => times[j]);
}
console.log(old.map((r) => r()), fixed.map((r) => r()));
[ undefined, undefined, undefined ] [ '6.15', '6.45', '7.30' ]
- With var, every reminder reads times[i] when it is called, after the loop, when i is 3, and times[3] is undefined: no ferry at all, for every bell. With let, each reminder keeps its own turn's index.
With var, every reminder is lost; with let, each names its own ferry.
Check: the fixed reminders give the three times in order.
A path that fails: moving the reminder's call inside the loop to test it. Called at once, the var version gives the right answers, because i has not moved on yet, so the test passes and the bug stays hidden until the bells ring later.
When you are stuck: functions made in a loop all give the last value
Look at the loop's counter: if it is made with var, there is one counter for all turns.
Change var to let, and each turn gets its own.
Use for...of with const when you need the items, not the indexes.
Test the functions after the loop has finished, as they will really be called.
Your turn
const fs = [];
for (var k = 1; k <= 2; k++) {
fs.push(() => k * 10);
}
console.log(fs[0](), fs[1]());
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
30 30
- var makes one k for the whole loop.
- After the loop, k is 3, since the loop stopped when k <= 2 became false.
- Both functions read that k: 3 × 10.
It prints 30 30.
What single change makes that block print 10 20?Tap to reveal
- Make the counter with let, so each turn has its own k.
Change var to let.
Why can the item of a for...of loop be a const?Tap to reveal
- Each turn gets a fresh name for its item.
- Within one turn, the name never changes.
Because each turn has its own name, which never changes during that turn.
Did you know?
let in 2006
The keyword let reached a browser long before ES2015. On 24 October 2006 Mozilla released Firefox 2, and its release notes describe JavaScript 1.7, a language update with generators, iterators, array comprehensions, let expressions and destructuring assignments. The keyword let became part of the standard nine years later, in ES2015, whose section 13.3.1 is called Let and Const Declarations.
Why it fits here: It shows how long this topic's let waited: tried in one browser in 2006, it joined the standard only in 2015.
Sources: Mozilla: Firefox 2 Release Notes; Wikipedia: Firefox version history; ECMAScript 2015 Language Specification
let for old browsers
Code with let can still run in browsers older than ES2015. Babel, a tool that converts ECMAScript 2015 and later into older JavaScript, rewrites let and const for them. For a loop whose turns make functions, its guide says the rewrite is impossible without adding an extra function and closure. That extra function gives each turn its own copy of the counter, as let does.
Why it fits here: It shows what this topic's let does underneath: to copy it with var, a tool must wrap each turn in a function of its own.
Sources: Babel: What is Babel?; Babel: @babel/plugin-transform-block-scoping
In one line
var makes one counter for a whole loop, so functions made in the loop all see its last value; let gives each turn its own counter, so each function keeps its turn. Use const for a for...of item, let for a counter.
const, and freezing an object
At a glance
A fare table kept with const still has fares that any code can change, because const keeps only the name pointing at the same object. For settings that must never change, JavaScript can lock the object itself.
After Object.freeze(obj), no property of obj can be added, changed or removed. In sloppy mode a write to a frozen object is ignored in silence; in strict mode it throws a TypeError. Freezing is shallow: an object inside a frozen object can still change, so freeze the inner objects too.
Take a guess: Is there an object that Object.freeze refuses to freeze?
const keeps a name pointing at the same object, as the objects lesson showed, but the object itself can still change. A fare table made with const can still have its fares changed by any code that holds it. For settings that must never change, JavaScript can lock the object itself.
A function that locks an object: after Object.freeze(obj), no property of obj can be added, changed or removed. It gives back the same object.
const o = Object.freeze({ a: 1 });
o.a = 2;
console.log(o.a, Object.isFrozen(o));
1 true
The write was ignored, without a word, as sloppy mode does with writes that cannot work. In strict mode the same write is an error, which is one more reason to write modern code in strict mode or in modules:
"use strict";
const o = Object.freeze({ a: 1 });
o.a = 2;
Uncaught TypeError: Cannot assign to read only property 'a' of object '#<Object>'
at line 3
| const | Object.freeze | |
|---|---|---|
| protects | the name: it always holds the same object | the object: its properties cannot change |
| a new value for the name | TypeError | not its job |
| changing a property | allowed | ignored, or a TypeError in strict mode |
Only one level deep
Like the shallow copy of the objects lesson, freezing works on the top level only. A property that holds an array or another object can still have that inner value changed:
const settings = Object.freeze({ theme: "dark", sizes: [1, 2] });
settings.sizes.push(3);
console.log(settings.sizes);
[ 1, 2, 3 ]
settings.sizes cannot be given a different array, but the array it holds is not frozen. To lock it too, freeze it as well, Object.freeze(settings.sizes), or freeze each level as you build the object.
Worked example 4
A railway app keeps its fare rules in an object that no code should ever change: a base fare of ₹30 and ₹1.50 a kilometre, kept in paise. Freeze it, and show that a slip in another part of the code cannot change it in strict mode.
What we have: a fare object, and code that tries to change it
What we need: the fares unchanged, and the slip named
The plan: build the object, freeze it, and try to change it in strict mode, catching the error to print its name
"use strict";
const FARES = Object.freeze({ basePaise: 3000, perKmPaise: 150 });
try {
FARES.perKmPaise = 100;
} catch (err) {
console.log(err.name);
}
console.log(FARES.perKmPaise);
TypeError
150
The fare stays 150 paise a kilometre, and the slip is a TypeError.
Check: FARES.perKmPaise printed 150 after the failed write.
A path that fails: relying on const alone. const FARES = {...} stops FARES from holding another object, but FARES.perKmPaise = 100 would change every fare in the app, with no error.
When you are stuck: an object changed although it is a const
const protects the name, not the object; freeze the object.
A frozen object's inner arrays and objects are not frozen; freeze them too.
In sloppy mode, writes to a frozen object are ignored silently; use strict mode to see them fail.
Check with Object.isFrozen(obj).
Your turn
After const s = Object.freeze({ n: 1 }); s.n = 5; in sloppy mode, what is s.n?Tap to reveal
- The object is frozen, so the write cannot work.
- Sloppy mode ignores the write.
Still 1.
Why can Object.freeze(obj).list.push(9) still change the list?Tap to reveal
- freeze locks only the top level of obj.
- obj.list is an array that was not frozen.
Because freezing is shallow.
What does const protect, and what does Object.freeze protect?Tap to reveal
- const: the name always holds the same object.
- freeze: the object's own properties.
const the name; freeze the object.
Did you know?
Three locks, from weak to strong
Object.freeze is the strongest of three locks. Object.preventExtensions only stops new properties from ever being added. Object.seal also stops properties being removed, though MDN notes that their values can still be changed as long as they are writable. Object.freeze stops changes to the values too, and MDN calls freezing the highest integrity level that JavaScript provides.
Why it fits here: It places this topic's Object.freeze at the top of a ladder: two lighter locks allow some changes that freeze forbids.
Sources: MDN: Object.preventExtensions(); MDN: Object.seal(); MDN: Object.freeze(); ECMAScript Language Specification: Object.seal
Objects that refuse to freeze
Not every object can be frozen. MDN warns that a typed array or a DataView that holds elements throws a TypeError when frozen, because such objects are views over memory. A typed array, such as Uint8Array, is a list of raw numbers kept in a block of memory. An empty one freezes without complaint, since it has no elements to lock.
Why it fits here: It answers this topic's question: Object.freeze refuses objects whose elements are views over memory, and says so with a TypeError.
Sources: MDN: Object.freeze(); ECMAScript Language Specification: TypedArray [[DefineOwnProperty]]
In one line
const keeps a name on one object; Object.freeze locks the object's own properties, ignoring writes in sloppy mode and throwing a TypeError in strict mode. Freezing is shallow, so freeze inner objects too.
Arrow functions in depth
At a glance
Arrows are ES2015's short way to write a function, and the most used form in modern code. They differ from the older forms in a few ways that matter. MDN's page for them lists the differences.
An arrow with no braces returns its expression, so an object to be returned must be wrapped in round brackets, or its braces are read as the body. Arrows have no this or arguments of their own, and cannot be called with new. They are best for callbacks and small jobs.
Take a guess: Can an arrow function's => be moved to the start of the next line?
The functions lesson introduced arrows, ES2015's short way to write a function. They are the most used function form in modern code, and they differ from the older forms in a few ways that matter. MDN's page for them lists the differences; this section measures the ones you will meet.
Returning an object
An arrow with no braces returns its expression. But an object is written in braces, so an arrow that should return an object is misread: JavaScript takes the braces for the arrow's body. Wrap the object in round brackets, and it is read as a value:
const make = (name) => ({ name, ok: true });
console.log(make("Asha"));
{ name: 'Asha', ok: true }
const broken = (name) => { name, ok: true };
Uncaught SyntaxError: Unexpected token ':'
const broken = (name) => { name };
console.log(broken("Asha"));
undefined
The first broken form is a SyntaxError, because a body cannot hold ok: true. The second is worse: { name } is a body holding the expression name, with no return, so it quietly gives undefined. The round brackets are the cure for both.
No this of their own
An arrow does not get its own this. It uses the this of the code around it, as the objects lesson measured: an arrow written as a method does not get the object, while an arrow inside a method gets the method's this. MDN's page adds that arrows have no arguments object of their own either, which older code used to read a function's arguments; modern code uses the three dots of a later lesson instead.
Not a constructor
Older JavaScript made objects by calling a function with the word new, as in new Shop("Ravi"). The classes lesson of this step teaches the modern way; for now, notice that a function declaration can be called with new, and an arrow cannot:
function Shop(name) {
this.name = name;
}
console.log(new Shop("Ravi").name);
Ravi
const Shop = (name) => { this.name = name; };
new Shop("Ravi");
Uncaught TypeError: Shop is not a constructor
at line 2
| function declaration | arrow function | |
|---|---|---|
| its own this | yes, decided by the call | no: the surrounding this |
| its own arguments object | yes | no |
| can be called with new | yes | no: TypeError |
| can be called above its line | yes, it is hoisted | no: it is a const like any other |
| short form for one expression | no | yes, with an implicit return |
Arrows are still functions in every other way. They have a name, taken from the const that holds them, and a length, the number of parameters:
const add = (a, b) => a + b;
console.log(add.length, add.name, typeof add);
2 add function
Worked example 5
A shop's app turns a list of item names into objects with a name and a starting quantity of 1, using map. Write the arrow that does it, and check the result.
What we have: the names tea and dal
What we need: the objects { name: 'tea', qty: 1 } and { name: 'dal', qty: 1 }
The plan: map with an arrow that returns an object, wrapped in round brackets
const items = ["tea", "dal"].map((name) => ({ name, qty: 1 }));
console.log(items);
[ { name: 'tea', qty: 1 }, { name: 'dal', qty: 1 } ]
Two objects, each with its name and a quantity of 1.
Check: the shorthand name gives the key name and its value from the parameter.
A path that fails: writing (name) => { name, qty: 1 }. It does not even run: a SyntaxError at the colon.
When you are stuck: an arrow does something unexpected
If it returns undefined, it has braces and no return; to return an object, wrap the object in round brackets.
If this is not the object, the arrow was used as a method; use the short method form.
If new fails with "is not a constructor", an arrow cannot be used with new.
If it cannot be called above its line, remember that an arrow in a const is not hoisted.
Your turn
Fix const pair = (a, b) => { a, b }; so that it returns an object with a and b.Tap to reveal
- Wrap the object in round brackets, so that it is read as a value.
const pair = (a, b) => ({ a, b });
What happens with new (() => {})()?Tap to reveal
- Arrows cannot be called with new.
A TypeError: it is not a constructor.
Inside a method, why is an arrow callback the right choice?Tap to reveal
- The arrow uses the this of the method around it, which is the object.
- A plain function callback would get a this of its own, not the object.
Because the arrow keeps the method's this.
Did you know?
No break before the arrow
An arrow is strict about where its lines break. MDN warns that an arrow function cannot have a line break between its parameters and its arrow, and the standard's grammar marks the spot with the words no LineTerminator here. A break after the arrow is fine. Arrows also cannot be generators, the functions that pause with yield.
Why it fits here: It adds two limits to this topic's list of arrow differences: where the line may break, and no yield.
Sources: MDN: Arrow function expressions; ECMAScript Language Specification: Arrow Function Definitions
A fat arrow before ES2015
Arrows were tried out in another language first. CoffeeScript, a language that compiles to JavaScript, began with Jeremy Ashkenas's first commit on 13 December 2009. Its fat arrow, written =>, defined a function and bound it to the current value of this on the spot. In 2011 Brendan Eich named CoffeeScript as an influence on Eich's own thoughts about JavaScript's future.
Why it fits here: It gives this topic's arrows a forerunner: a language built on JavaScript had an arrow that kept this, years before ES2015.
Sources: Wikipedia: CoffeeScript; CoffeeScript
In one line
Wrap an object in round brackets to return it from an arrow with no braces. Arrows have no this or arguments of their own and cannot be used with new; they are best for callbacks and small jobs.
Choosing the form for each job
At a glance
A carpenter's box holds a saw, a chisel and a plane, and each does one kind of cut best. JavaScript has three everyday ways to write a function, and each has jobs it does best.
Use a declaration for a program's main named jobs, and an arrow for callbacks and small jobs. Use the short method form for jobs that belong to an object. Write modern code in strict mode or in modules, with const by default, let when a name must change, and no var. Teams that agree on these habits write code that reads the same from file to file.
Take a guess: Can a tool rewrite every var in a file into let or const by itself?
A carpenter's box holds a saw, a chisel and a plane, and each does one kind of cut best. JavaScript has three everyday ways to write a function, and each has jobs it does best. Teams that agree on when to use which write code that reads the same from file to file.
| Form | Looks like | Best for |
|---|---|---|
| declaration | function billTotal(items) { ... } | a program's main named jobs, which can be called from anywhere in the file |
| arrow | (n) => n * 2 | callbacks and small jobs, written where they are used |
| method | total() { ... } in an object | jobs that belong to an object and use its this |
const nums = [3, 1, 2];
console.log(nums.map((n) => n * 2).filter((n) => n > 2));
[ 6, 4 ]
Callbacks such as these are where arrows shine: short, written in place, and with no this of their own to get in the way. A named job used in many places reads better as a declaration, because its name says what it does and it can be called from above its line. A job that belongs to an object, and reads the object's properties, is a method.
function lineTotal(item) {
return item.price * item.qty;
}
const cart = {
items: [{ price: 40, qty: 2 }, { price: 15, qty: 1 }],
total() {
return this.items.map((item) => lineTotal(item)).reduce((s, n) => s + n, 0);
},
};
console.log(cart.total());
95
This one block uses all three, each for its job. lineTotal is a declaration: a named rule. total is a method: it belongs to the cart and reads this.items. The two arrows are callbacks: they keep the method's this, and are written where they are used.
Modern habits, together
- Write files as modules, or start a script with
"use strict";. - Make names with const, and with let only when the value must change; never with var.
- Use arrows for callbacks, the short form for methods, and declarations for named jobs.
- Check MDN's Browser compatibility table before relying on a new feature in an old browser.
Worked example 6
Rewrite this older code in the modern style, keeping what it does: var total = 0; var prices = [120, 45]; for (var i = 0; i < prices.length; i++) { total = total + prices[i] * 118 / 100; }.
What we have: an older loop that adds prices with 18% GST
What we need: the same total, written with modern habits
The plan: const for the list, reduce with an arrow callback for the total, and no var
"use strict";
const prices = [120, 45];
const total = prices.reduce((sum, p) => sum + p * 118 / 100, 0);
console.log(total);
194.7
- The total is never reassigned, so it can be a const, made in one line by reduce.
The modern version gives the same 194.7.
Check: (120 + 45) × 1.18 = 165 × 1.18 = 194.7.
A path that fails: changing every var to const and leaving the loop as it was. The loop reassigns total and i, so the first round stops with TypeError: Assignment to constant variable.
When you are stuck: which form to use
A callback, passed to map, filter, an event or a timer: an arrow.
A job that reads an object's this: the short method form.
A named job used in many places: a declaration.
Never an arrow as a method, and never an arrow with new.
Your turn
Which form suits the callback in items.filter(...)?Tap to reveal
- A callback written in place, with no need for its own this.
An arrow.
Which form suits a job that reads this.items of the cart it belongs to?Tap to reveal
- It belongs to the object and uses this.
A method, in the short form.
Why is var not in the list of modern habits?Tap to reveal
- var ignores blocks, leaks out of loops, and gives one counter for all turns of a loop.
Because let and const do its job without its surprises.
Did you know?
Rule 8.1
Teams write their choices down. Airbnb's JavaScript style guide, rule 8.1, says that when you must use an anonymous function, as when passing an inline callback, you should use arrow notation. Its reason: the arrow runs in the context of this, which is usually what you want, and is shorter. Each rule names the ESLint checks that enforce it, so a tool can hold a team to it.
Why it fits here: It shows this topic's advice in a real team's rules: arrows for callbacks, written down and checked by a tool.
Source: Airbnb JavaScript Style Guide
A tool that retires var
The habit of const by default has a checker. ESLint's prefer-const rule says that if a variable is never reassigned, const is better, because it tells readers the name will never change. Its no-var rule requires let or const instead of var. Both rules are fixable: run with the --fix option, ESLint rewrites much of the code by itself.
Why it fits here: It answers this topic's question about a tool: a linter can find each var and much of the time replace it for you.
Sources: ESLint: prefer-const; ESLint: no-var
In one line
Use declarations for named jobs, arrows for callbacks and small jobs, and the short method form for jobs that belong to an object. Write modern code in strict mode or modules, with const by default and no var.
Where it is used
Everything in this lesson shows up as soon as you read code written by others. Here is where.
| What you learned | Where it is used | A real example |
|---|---|---|
| editions and compatibility | deciding what code may use | a school site that must run on old lab computers checks MDN's tables |
| strict mode | every module and class, and careful scripts | a misspelt name in an old script caught as a ReferenceError |
| let in loops | functions made in loops | a reminder or a handler made for each row of a list |
| Object.freeze | settings and constants | a frozen table of fares or tax rates |
| arrows returning objects | turning lists into lists of records | names mapped to objects with a quantity of 1 |
| choosing the function form | every codebase | a team's style guide: arrows for callbacks, declarations for named jobs |
Mistakes and debugging
These are the slips that people meet most often with this lesson's ideas. Every output below is the real one, from the code shown.
1. var in a loop that makes functions
const fs = [];
for (var i = 0; i < 3; i++) {
fs.push(() => i);
}
console.log(fs.map((f) => f()));
[ 3, 3, 3 ]
No error: one counter for all turns. The fix: for (let i = 0; ...).
2. An object returned from an arrow without brackets
const make = (n) => { n };
console.log(make(1));
undefined
No error: the braces were read as a body. The fix: (n) => ({ n }).
3. Trusting const to freeze
const RATES = { gst: 18 };
RATES.gst = 5;
console.log(RATES.gst);
5
No error: const does not protect properties. The fix: Object.freeze({ gst: 18 }).
4. new on an arrow
const Shop = (name) => { this.name = name; };
new Shop("Ravi");
Uncaught TypeError: Shop is not a constructor
at line 2
The fix: use a factory function, or the class syntax of a later lesson.
5. An old script that breaks in strict mode
"use strict";
function add(price) {
totl = price;
}
add(5);
Uncaught ReferenceError: totl is not defined
at add (line 3)
at line 5
This is strict mode doing its job: the slip was there before, silent. The fix: declare the name, or correct its spelling.
The debugging corner: modernise to find bugs
When an old script misbehaves, two small changes often reveal the bug: put "use strict"; at the top, and change each var to let or const. Silent slips then become errors with lines, and loop counters stop being shared. Make one change at a time, as the debugging method says, and run the script after each.
Quick card
The whole lesson on one card. Come back to it whenever you need a reminder.
The lesson in code
"use strict"; // silent slips become errors; modules and classes are always strict
// let in a loop: each turn its own counter
const bells = [];
for (let i = 0; i < 3; i++) {
bells.push(() => i);
}
console.log(bells.map((b) => b()));
// const keeps the name; Object.freeze keeps the properties (one level deep)
const FARES = Object.freeze({ perKmPaise: 150 });
try {
FARES.perKmPaise = 100;
} catch (err) {
console.log(err.name, FARES.perKmPaise);
}
// arrows: wrap a returned object in round brackets; no this, no new
const make = (name) => ({ name, qty: 1 });
console.log(make("tea"));
// ES2021 defaults as assignments
let guest = "";
guest ||= "Guest";
console.log(guest);
[ 0, 1, 2 ]
TypeError 150
{ name: 'tea', qty: 1 }
Guest
| When you see | It means | Look at |
|---|---|---|
| functions from a loop that all give the last value | a var counter shared by every turn | let |
| undefined from an arrow meant to return an object | braces read as a body | round brackets around the object |
| a const object that changed | const protects the name only | Object.freeze |
TypeError: Cannot assign to read only property | a write to a frozen object, in strict mode | who is trying to change it |
TypeError: ... is not a constructor | new on an arrow | a factory function or a class |
ReferenceError after adding "use strict" | an undeclared name that used to become a global | declare it, or fix its spelling |
The story: Each bell its own ferry
You find the loop that set the bells. In the old style, its counter was one box for the whole loop, and every bell was told to look in that box when its time came. By then the box held the last ferry. You change one word, so that each turn of the loop keeps a counter of its own.
At 6.15 one bell rings, at 6.45 the next, at 7.30 the last.
Master Verge nods towards the other old clocks along the wall. "Now you know the first new rule," he says. "The rest of this floor is full of them."
Reagents gathered: ECMAScript, strict mode, let, const, Object.freeze, arrow function.
Sources
- MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)
- The ECMAScript language specification (ECMA-262) (Ecma International copyright; facts and ideas only)