Loading

T4 JavaScript · Lesson 1

Values and variables

The eight types of value and how to tell them apart, numbers and money done exactly, strings built with template literals and methods, names made with const, let and var, changing a value step by step, and turning one type into another on purpose.

  • name the eight types of value, and find any value's type with typeof
  • tell undefined from null, and choose a type for each piece of data
  • work with numbers safely: decimals, money in paise, rounding, very large numbers
  • build text with template literals, escape sequences and string methods
  • make names with const and let, read old code that uses var, and choose good names
  • change a value with the assignment operators, ++ and --
  • turn one type into another on purpose, and spot when JavaScript does it for you
About 70 minutesChecked against Node.js on the laptop (the kit runs every code block with it) 22.23.1 (2026-11-06)Play this lesson's games

The back cover

Every program is made of values: prices, names, answers, the yes or no of a tick box. Before a program can add, compare or show them, it must know what kind each one is, and it must keep them under names it can find again.

These pages show the eight types of value and how to tell them apart. They show numbers, with money done exactly in paise, and strings built with template literals. They make names with const and let, change values step by step, and turn one type into another without the usual surprises.

Before you start

The story: A ticket that made no sense

The Clock Tower rises over the harbour, ticking so loudly that its windows hum. Inside, every wall is covered with wheels, and every wheel is turning. Master Hakim Verge is bent over the ferry office's ticket machine, which he has opened like a pocket watch.

He tears off its last ticket and hands it to you. The ferry office wanted Passenger Asha, ticket 0007, fare ₹3.30. The ticket says: Passenger ${name}, ticket 7, fare ₹3.3000000000000003. Corin laughs and says the machine has been drinking.

"Machines do not drink," says Master Verge. "Nothing moves unless something moved it. Every mark on that ticket was put there by a line of its script." He gives you the script. It is short. Each line puts a value into a box with a name.

In the Learning to learn step you printed values, joined text and gave values names. That was enough to start. Now the Clock Tower asks for more: every value in a program has a kind, and most bugs begin with a value of the wrong kind in the wrong place. This lesson looks closely at the values themselves, and at the names that hold them.

It builds on these ideas. Each one has a tiny example, so you can check that you remember it.

What you already knowA tiny exampleWhere it comes back
Printing with console.log.console.log("Namaste");Every block here prints what it found.
Strings and numbers."5" is text; 5 is a number.They are two of the eight types.
typeof.typeof 5 gives number.We ask it about every type.
+ joins text."5" + 3 gives 53.The rules of conversion explain it.
Number(...).Number("40") gives 40.Its odd cases, such as an empty box.
const and let.let total = 10;With var, and when to choose each.
The rules for names.No spaces; capitals count.With the habits of working programmers.
A value read with a dot."Pune".length gives 4.Every string has a length and positions.
A method."chai".toUpperCase()Eleven string methods, side by side.
undefined and NaN.A name with nothing in it; a sum that failed.Both are values, with types of their own.
The three error kinds.SyntaxError, ReferenceError, TypeError.New messages from let and const.
=== asks "is exactly equal to?"2 + 2 === 4 gives true.true is a value of a type of its own.

By the end of this lesson you will be able to:

  • name the eight types of value, and find any value's type with typeof;
  • tell undefined from null, and choose a type for each piece of data;
  • work with numbers safely: decimals, money in paise, rounding and very large numbers;
  • build text with template literals, escape sequences and string methods;
  • make names with const and let, read old code that uses var, and choose good names;
  • change a value with the assignment operators, ++ and --;
  • turn one type into another on purpose, and spot when JavaScript does it for you.

How to follow this lesson

Every block on this page runs. Press Run to see what it prints, change a value, and run it again. The output under each block is exactly what it prints. When a line surprises you, add typeof to it and run it again: most surprises in this lesson are a type you did not expect.

In one line

A value is a piece of data with a type, and a variable is a name that holds one; this lesson is about both.

Every value has a type

At a glance

A railway booking form keeps its boxes apart: a name, an age, a tick for a lower berth, and a seat number still empty. You would never add a name to an age. JavaScript keeps kinds of value apart in the same way, and each kind is called a type.

There are eight: number, string, boolean, undefined, null, bigint, symbol and object. The typeof operator names a value's type, with one famous oddity: it says object for null. And a name is not tied to one type; it can hold a number now and a string later.

Take a guess: What does typeof say about null?

Picture a railway booking form. One box asks for the passenger's name: Asha Rao. Another asks for her age: 34. A tick box asks whether she wants a lower berth: yes. The seat number box is still empty, because the railway has not given her a seat yet.

Each box holds a different kind of thing. You would never add a name to an age, or put a number in a tick box. The form keeps the kinds apart, and so does JavaScript.

In the Learning to learn step you met two kinds of value, strings and numbers. JavaScript has eight kinds in all. Each kind is called a type.

Primitive value

One plain value, such as 34 or "Asha", that cannot be split into parts and cannot be changed. Seven of the eight types are primitive types.

The eighth type, object, holds many values together under one name. The objects lesson of this track is about it. Here are all eight, with what typeof says about each:

TypeWhat it holdsExamplestypeof gives
numberan amount, a count or a measure34, 4.5, -7"number"
stringtext"Asha", '411001'"string"
booleanyes or notrue, false"boolean"
undefinedno value yetundefined"undefined"
nullnothing, on purposenull"object", an old slip (see below)
biginta whole number of any size10n"bigint"
symbola label that is never equal to any otherSymbol("id")"symbol"
objectmany values together{}, []"object", or "function" for a function
console.log(typeof 42, typeof 4.5, typeof "chai", typeof true, typeof undefined, typeof null, typeof 10n, typeof Symbol("id"));
number number string boolean undefined object bigint symbol

Read the output in the same order as the values. A whole number and a decimal are both the type number. Text in quotes is a string. The rest are new, and the next few parts of this section meet them one at a time. Two of them, bigint and symbol, are rare in everyday code; you will meet bigint again in the numbers section.

console.log(typeof {}, typeof [], typeof function () {});
object object function

Objects come in several shapes. A list in square brackets, called an array, is an object too, and so is a function, although typeof gives a function a name of its own. The arrays, functions and objects lessons of this track take them one by one.

Booleans: yes or no

Boolean

A value that is either true or false, and nothing else. It answers a yes-or-no question: is the bill paid? Has the train left? The name comes from George Boole, an English mathematician of the nineteenth century, who wrote the rules of logic as algebra.

const isPaid = true;
const hasLeft = false;
console.log(isPaid, hasLeft, typeof isPaid, typeof "true");
true false boolean string

A boolean is written with no quotes. "true" in quotes is a string of four letters, as the last word of the output shows. Booleans usually come from questions that code asks, such as 2 + 2 === 4. The next lesson, on operators and conditionals, asks many such questions and acts on the answers.

undefined and null: two kinds of nothing

Go back to the booking form. The seat box is empty because nobody has filled it yet. Now picture a meal box in which the passenger has written "None" herself. Both boxes hold nothing, but they mean different things. JavaScript has a value for each.

undefined

The value of something that has not been given a value yet. A name made with let and no value holds undefined. So does a position past the end of a string, as the strings section shows.

null

A value that a programmer writes on purpose, to say "there is nothing here, and I know it".

let seat;
let meal = null;
console.log(seat, meal);
console.log(typeof seat, typeof meal);
undefined null
undefined object

The first line of output shows the two values. The second shows their types, and one of them is a surprise: typeof null gives "object", although null is not an object at all.

Why typeof null says object

In the very first version of JavaScript, each value was stored with a small tag for its type, and the tag for objects was 0. null was stored as 0 as well, so it looked like an object. A fix was proposed for the language later, and turned down, because it would have broken pages that rely on the old answer. So to test for null, write value === null.

A habit that keeps code clear: let JavaScript give you undefined for things not filled in yet, and write null yourself when you mean "empty, on purpose".

A name can hold any type

In some languages a name is made for one type only, like a jar labelled rice that may never hold sugar. JavaScript is not one of them. A name holds whatever value you last put in it, of any type.

Dynamic typing

A language's rule that the value has a type and the name does not, so one name can hold a number now and a string later.

let value = 42;
console.log(typeof value);
value = "forty-two";
console.log(typeof value);
number
string

Dynamic typing makes code quick to write. Its price is that a name can hold a type you did not expect, and nothing warns you. The TypeScript step, further along the path, gives each name a type of its own, so that such slips are caught before the code runs.

Worked example 1

A cricket scorecard records a batter's name, the runs scored, the overs faced, whether the batter is out, and the bowler who took the wicket, which is not known while the batter is still in. Riya has scored 48 runs from 12.3 overs and is not out. Choose a type for each fact, and check the choices with typeof.

What we have: five facts about one batter

What we need: a type for each fact

The plan: ask of each value: is it text, an amount you do sums with, a yes or no, or not known yet?

  1. The name is text: a string.
  2. The runs are an amount that grows by addition: a number.
  3. The overs need care. 12.3 overs means 12 overs and 3 balls, not twelve and three tenths, as an over has six balls. Adding overs as decimals gives nonsense, so scoring programs count balls instead: 12 × 6 + 3 = 75 balls, a number. They write 12.3 only to show it.
  4. Out or not out is a yes or no: a boolean.
  5. The bowler is not known yet, so the name is made with no value: undefined.
const batter = "Riya";
const runs = 48;
const balls = 75;
const isOut = false;
let bowler;
console.log(typeof batter, typeof runs, typeof balls, typeof isOut, typeof bowler);
string number number boolean undefined

string, number, number, boolean, undefined: the name, the runs, the balls faced, whether the batter is out, and the bowler not known yet.

Check: 12 × 6 + 3 is 75 balls, and the line of output names the five types in the order the values were given.

A path that fails: keeping the overs as the number 12.3. Two spells of 12.3 and 0.3 overs would add up to 12.6 as decimals, which is no real score: 12 overs and 3 balls, plus 3 more balls, makes exactly 13 overs.

Worked example 2

A school portal keeps three things for each student: the roll number 0042, the phone number 98765 43210 and the PIN code 411001. Should each be a number or a string?

What we have: three values made of digits

What we need: the right type for each

The plan: ask two questions of each value: will anyone do arithmetic with it, and do the zeros in front matter?

  1. Nobody adds two PIN codes or doubles a phone number. These are labels made of digits, not amounts.
  2. The zeros in front matter: roll number 0042 must be printed as 0042. Watch what happens to it as a number:
const roll = 0042;
console.log(roll);
34
  1. Not 42, but 34. An old rule of the language reads a number that starts with 0 and holds only the digits 0 to 7 in base 8, where 42 means 4 eights and 2 ones. In strict mode, which the modern JavaScript step explains, the same line is an error instead. Either way, the number type is wrong for this value.
  2. As strings, all three keep every character:
const roll = "0042";
const pin = "411001";
console.log(roll, pin, roll.length);
0042 411001 4

All three are strings: they are labels made of digits, not amounts.

Check: the string 0042 keeps its four characters, as its length of 4 shows, and 4 × 8 + 2 is 34, which explains the number the first block printed.

A path that fails: storing the roll number as a number and adding the zeros back when printing. That works only if every roll number has the same length, and the base 8 rule has already changed the value before any printing happens.

When you are stuck: a value is not the type you expected

Print the value and its type together: console.log(x, typeof x);.

Look for quotes. A value in quotes is a string, whatever it looks like inside.

Ask where the value came from. Anything a person types into a page reaches your code as a string.

If typeof says object, check whether the value is null with x === null.

Your turn

console.log(typeof "false", typeof false, typeof 0, typeof "");
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
string boolean number string
  1. "false" is in quotes, so it is a string.
  2. false with no quotes is a boolean.
  3. 0 is a number, even though it means nothing.
  4. "" is an empty string: a string with no characters, but still a string.

It prints string boolean number string.

A delivery app keeps the time each order was delivered. Before delivery an order has no time yet. A cancelled order will never have one. Which value fits each case?Tap to reveal
  1. Not delivered yet: the value has not been given. That is undefined, which JavaScript gives a name made with no value.
  2. Cancelled: the programmer knows there will never be a time, and says so on purpose. That is null.

undefined before delivery, and null for a cancelled order.

Choose a type for a UPI payment's amount of ₹250, the receiver's UPI ID such as asha@okbank, and whether the payment went through.Tap to reveal
  1. The amount is used in sums: a number.
  2. The UPI ID is text: a string.
  3. Went through or not is a yes or no: a boolean.

number, string, boolean.

Did you know?

A type named after a person

The boolean, the type of true and false, is named after a person. George Boole was born on 2 November 1815 in Lincoln, England, where his father kept a cobbler's shop. He approached logic in a new way, reducing it to a simple algebra. The data type with only two values carries his name.

Why it fits here: Every yes or no in this topic, such as a tick for a lower berth, is a boolean: a value with only two choices.

Sources: Wikipedia: Boolean data type; MacTutor History of Mathematics: George Boole

The youngest of the eight

The JavaScript standard names eight types today: Undefined, Null, Boolean, String, Symbol, Number, BigInt and Object. The youngest is BigInt. TC39's list of finished proposals places it in ECMAScript 2020, with Daniel Ehrenberg as its champion. It brought whole numbers too high or too low for the number type, so a very long ID number can be held exactly.

Why it fits here: It explains why this topic counts eight types, where books written before 2020 count seven.

Sources: ECMAScript Language Specification; TC39: Finished Proposals; MDN: BigInt

In one line

JavaScript has eight types: number, string, boolean, undefined, null, bigint, symbol and object. typeof names a value's type, and says object for null. A name can hold a value of any type.

Numbers: one type for every amount

At a glance

At a kirana shop, Ramesh sells 3 soaps, 1.5 kg of rice and a bottle of oil for ₹185.75. Some amounts are whole and some have a decimal point, but in JavaScript they are all one type: number. There is no separate type for whole numbers.

Numbers are stored in binary, so some decimals come out slightly off: 0.1 + 0.2 is not exactly 0.3. So money is counted in paise, and rounded only to show it. NaN and Infinity are numbers too, and whole numbers past a certain size need BigInt.

Take a guess: Why can 0.1 + 0.2 fail to equal 0.3 in JavaScript?

At a kirana shop, Ramesh sells 3 soaps, 1.5 kg of rice and a bottle of oil for ₹185.75. Some of these amounts are whole, and some have a decimal point. In JavaScript they are all one type: number. There is no separate type for whole numbers.

console.log(typeof 3, typeof 1.5, typeof 185.75, 7 / 2);
number number number 3.5

Dividing 7 by 2 gives 3.5, with nothing cut off. Some languages would give 3 here, keeping only the whole part. JavaScript keeps the exact share.

Why 0.1 + 0.2 is not 0.3

In the Learning to learn step you saw 0.1 + 0.2 print a strange answer. Here is why it happens.

Try writing one third as a decimal: 0.3333, with threes for ever. Any page runs out, so you stop somewhere, and the number you wrote is a little short of one third. A computer meets the same problem, in base 2. It stores numbers in binary, with only the digits 0 and 1, and in binary even one tenth goes on for ever.

Floating-point number

A number stored as a fixed number of binary digits, together with a note of where the point goes. JavaScript keeps every number in 64 binary digits. When a decimal does not fit exactly, the nearest value that fits is kept instead.

console.log(0.1 + 0.2, 1.1 + 2.2, 10.1 + 20.2);
0.30000000000000004 3.3000000000000003 30.299999999999997

Each answer is wrong only in its far digits. For most measurements that does not matter. For money it does: nobody wants a bill of ₹30.299999999999997.

Money in paise

Programs that handle money use a common cure: count in the smallest unit. For rupees, that is paise. Whole numbers are stored exactly, up to a very large size, so sums of paise are always exact.

const rupees = 1.1 + 2.2;
const paise = 110 + 220;
console.log(rupees, paise, paise / 100);
3.3000000000000003 330 3.3

The sum in paise is exact. You divide by 100 only at the very end, when the amount is shown to a person.

A common mistake

Turning rupees into paise by multiplying alone. 4.35 * 100 gives 434.99999999999994, because 4.35 itself was not stored exactly. Round the answer to the nearest whole number, and it is right: Math.round(4.35 * 100) gives 435.

console.log(4.35 * 100, Math.round(4.35 * 100));
434.99999999999994 435

Rounding, and the Math object

To show an amount, you often need to round it. JavaScript gives you two kinds of tool for this.

toFixed(n)

A method of every number that writes it with exactly n digits after the point, rounding the last one. It gives back a string, ready to show, not a number.

const price = 3.3;
console.log(price.toFixed(2), typeof price.toFixed(2));
3.30 string
Math

A built-in object: an object that comes ready-made with JavaScript, holding useful numbers and jobs. You never make it yourself; you use it with a dot, as in Math.round(2.5).

console.log(Math.round(2.5), Math.round(2.49), Math.floor(4.9), Math.ceil(4.1));
console.log(Math.max(3, 9, 4), Math.min(3, 9, 4), Math.abs(-7), Math.PI);
3 2 4 5
9 3 7 3.141592653589793
WriteIt givesExample
Math.round(x)x to the nearest whole number; a half goes upMath.round(2.5) is 3
Math.floor(x)the whole number at or below xMath.floor(4.9) is 4
Math.ceil(x)the whole number at or above xMath.ceil(4.1) is 5
Math.trunc(x)x with its decimals cut offMath.trunc(-4.7) is −4
Math.max(a, b, ...)the largest of the valuesMath.max(3, 9, 4) is 9
Math.min(a, b, ...)the smallest of the valuesMath.min(3, 9, 4) is 3
Math.abs(x)x without its signMath.abs(-7) is 7
Math.sqrt(x)the square root of xMath.sqrt(144) is 12
Math.random()a new decimal from 0 up to, but not including, 1, each timedifferent on every run

One detail of Math.round catches people out: a half always goes up, towards the larger number. So 2.5 becomes 3, but −2.5 becomes −2, because −2 is larger than −3. And Math.floor goes down for negative numbers too, so it is not the same as cutting off the decimals:

console.log(Math.round(-2.5), Math.trunc(-4.7), Math.floor(-4.7));
-2 -4 -5

Math.random() gives a different number on every run, so no block here prints one. This block rolls a dice, and prints only facts that hold on every run: the roll is a whole number, and random numbers are of the type number.

const d = Math.floor(Math.random() * 6) + 1;
console.log(Number.isInteger(d), typeof Math.random());
true number

Read the roll from the inside out. Math.random() is from 0 up to 1. Times 6, it is from 0 up to 6. Math.floor turns that into 0, 1, 2, 3, 4 or 5. Adding 1 gives 1 to 6, the faces of a dice.

Infinity and NaN

In arithmetic class, dividing by zero cannot be done. JavaScript gives an answer instead: Infinity, a number larger than any other, or -Infinity below zero. Zero divided by zero has no sensible answer at all, so it gives NaN.

console.log(1 / 0, -1 / 0, 0 / 0, typeof NaN, typeof Infinity);
Infinity -Infinity NaN number number

NaN means "Not a Number", and yet its type is number. Think of it as the number type's way of saying "this arithmetic failed". It also spreads: any arithmetic with NaN gives NaN, so one failed step can spoil a whole bill. Number.isNaN(x) asks whether x is NaN, and gives a boolean.

const total = 100 + Number("abc");
console.log(total, total * 2, Number.isNaN(total));
NaN NaN true

Very large numbers

Whole numbers are exact only up to a limit, and JavaScript gives the limit a name: Number.MAX_SAFE_INTEGER. It is 9,00,71,99,25,47,40,991, a sixteen-digit number. Past it, not every whole number can be stored, and some are kept as a neighbour instead.

console.log(Number.MAX_SAFE_INTEGER);
console.log(9007199254740993);
9007199254740991
9007199254740992

The second line asked for a number ending in 3 and printed one ending in 2. There was no error and no warning. For whole numbers this large, JavaScript has another type.

BigInt

A whole number of any size, written with an n at the end, as in 10n. It is always exact, but it holds whole numbers only.

console.log(9007199254740993n + 2n, typeof 10n);
9007199254740995n bigint

A BigInt and an ordinary number cannot be mixed in one sum, and JavaScript says so at once:

console.log(10n + 5);
Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions
    at line 1

BigInt is rare in everyday code. You will meet it where whole numbers grow very long, such as some IDs. A long ID that is never used in sums can also be kept as a string, which keeps every digit.

Writing big numbers so you can read them

A long number such as 100000 is hard to read at a glance. Is it one lakh or ten lakh? JavaScript lets you put underscores between the digits of a number in your code, and ignores them. They may go between any two digits, so the Indian way of grouping works:

const lakh = 1_00_000;
const crore = 1_00_00_000;
console.log(lakh, crore, lakh * 100 === crore);
100000 10000000 true

The underscores belong to code only. Text that a person types is another matter: commas and underscores in a string are not digits, so Number(...) cannot read them.

console.log(Number("1,00,000"), Number("1_00_000"), Number("100000"));
NaN NaN 100000

Worked example 3

A customer at Ramesh's shop buys 3 soaps at ₹10.10 each and a packet of tea at ₹38.40. Work out the bill exactly, and show it with two digits after the point.

What we have: two prices in rupees and paise, and how many of each were bought

What we need: the exact bill, written as rupees and paise

The plan: turn each price into paise, multiply and add whole numbers, and turn the total back into rupees only to show it

  1. ₹10.10 is 1010 paise, and ₹38.40 is 3840 paise.
  2. Three soaps and one packet of tea: 3 × 1010 + 3840, all whole numbers, so the sum is exact.
  3. Divide by 100 for rupees, and write two digits after the point with toFixed(2).
const paise = 3 * 1010 + 3840;
console.log(paise, (paise / 100).toFixed(2));
6870 68.70

The bill is ₹68.70, which is 6870 paise.

Check: 3 × 10.10 is 30.30, and 30.30 + 38.40 is 68.70.

Another way: add in rupees and round at the end with toFixed(2), which gives 68.70 here. It works for one bill, but the tiny errors can pile up over thousands of sums, so paise are the safer habit.

A path that fails: adding the rupee prices as decimals and printing the sum. 3 * 10.1 + 38.4 gives 68.69999999999999. Another set of prices might happen to come out exact, which is worse: the bug then hides until a bill that does not.

Worked example 4

Three friends share a dinner bill of ₹1000 equally through a UPI app. How much does each one pay, and what is left over?

What we have: a bill of ₹1000 and three friends

What we need: each friend's share, in rupees and paise, and anything left over

The plan: work in paise, share the whole paise out with Math.floor, and find what is left over with %, the remainder

  1. ₹1000 is 1000 × 100 = 1,00,000 paise.
  2. Each friend gets the whole paise of 1,00,000 ÷ 3: Math.floor drops the part that cannot be paid.
  3. The paise left over are the remainder after dividing by 3.
const bill = 1000 * 100;
const each = Math.floor(bill / 3);
const left = bill % 3;
console.log(each, left, (each / 100).toFixed(2));
33333 1 333.33

Each friend pays ₹333.33, and 1 paisa is left over, so one of them pays ₹333.34.

Check: 3 × 33,333 + 1 is 1,00,000 paise, the whole bill.

A path that fails: dividing the rupees: 1000 / 3 is 333.3333333333333, an amount that no payment app can send.

When you are stuck: a number looks wrong

A long tail of 9s or 0s at the end is a decimal that was not stored exactly. Count in paise, and round only to show.

NaN means a step failed. Print each part of the sum to find the first part that is NaN.

A large whole number whose last digits change is past the safe limit. Use a BigInt, or a string if it is only a label.

A rounded value that will not add up may be the string from toFixed: check it with typeof.

Your turn

console.log(9 / 2, Math.floor(9 / 2), 9 % 2, (9 / 2).toFixed(2));
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
4.5 4 1 4.50
  1. 9 / 2 keeps the exact share: 4.5.
  2. Math.floor goes down to the whole number below: 4.
  3. 9 % 2 is the remainder: two goes into nine 4 times, and 1 is left.
  4. toFixed(2) writes 4.5 with two digits after the point: the string 4.50.

It prints 4.5 4 1 4.50.

Turn ₹19.99 into paise in a way that is always exact.Tap to reveal
  1. Multiplying alone can leave a tiny error, as 4.35 did.
  2. Round the product to the nearest whole number with Math.round.
console.log(Math.round(19.99 * 100));
1999

Math.round(19.99 * 100) gives 1999 paise.

Write one crore with underscores in the Indian way, and print it multiplied by 3.Tap to reveal
  1. One crore is 1,00,00,000: in code, 1_00_00_000.
console.log(1_00_00_000 * 3);
30000000

It prints 30000000, three crore.

Did you know?

A fraction that cost lives

A tiny error in a fraction once cost lives. On 25 February 1991, a Patriot missile battery at Dhahran, Saudi Arabia, failed to track an incoming Scud, which hit an Army barracks and killed 28 Americans. Its clock counted tenths of seconds, and its registers were only 24 bits long, so the time it worked out was slightly off. The error grew the longer the system ran, and it had run for over 100 hours.

Why it fits here: It is this topic's warning made real: a decimal in binary is slightly off, and a slight error repeated becomes a large one.

Source: U.S. GAO: Patriot Missile Defense, Software Problem Led to System Failure at Dhahran (IMTEC-92-26)

When adding 1 does nothing

Numbers have a largest safe whole number, Number.MAX_SAFE_INTEGER, which is 9,00,71,99,25,47,40,991. Past it, whole numbers can no longer all be stored exactly. MDN gives the proof in one line: Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2 evaluates to true, which is mathematically incorrect. Two different sums are stored as one and the same number.

Why it fits here: It is why this topic sends very large whole numbers, such as long ID numbers, to BigInt.

Sources: MDN: Number.MAX_SAFE_INTEGER; ECMAScript Language Specification: Number.MAX_SAFE_INTEGER

In one line

Every number is one type, stored in binary, so decimals can be slightly off. Count money in paise, and round only to show it: toFixed gives a string. Watch for NaN and Infinity, and use BigInt for whole numbers past 9,00,71,99,25,47,40,991.

Strings: text, written three ways

At a glance

A family in Pune prints three hundred wedding cards, the same words on each, with only the name changing. The card is a template: fixed words with gaps to fill. JavaScript builds text the same way.

A string can be written in single quotes, double quotes or backticks, and only backticks fill gaps with ${...}. A backslash starts an escape, such as \n for a new line. Characters are counted from index 0, and a string never changes, so keep what a method gives back.

Take a guess: Which of the three kinds of quote can fill a gap in the text?

A family in Pune prints three hundred wedding cards. Each says: Dear ___, please join us on 12 December at the community hall in Kothrud. The words are the same on every card, and only the name in the blank changes. The card is a template: fixed words with gaps to fill.

JavaScript builds text the same way. A string can be written with three kinds of quote, and one kind can hold gaps.

QuotesWrittenCan hold inside
single'Asha'double quotes, as plain text
double"Asha"single quotes, as plain text
backticks`Asha`both kinds of quote, line breaks, and gaps written ${...}

The backtick is the key to the left of 1 on an Indian or American keyboard, below Esc. It is easy to miss, so look for it now.

Template literals: text with gaps

Template literal

A string written between backticks. Inside it, ${...} marks a gap: JavaScript works out what is inside the braces and puts the answer into the text. Filling gaps this way is called string interpolation.

Read ${name} aloud as "the value of name". The dollar sign and the braces are not printed; only the value is.

const name = "Asha";
const total = 240;
console.log(`Hello ${name}, your bill is ₹${total}.`);
Hello Asha, your bill is ₹240.

Any expression can go inside the braces: a sum, a method, or a name. JavaScript works it out first, then puts the answer into the text.

console.log(`3 plates cost ₹${3 * 80}`);
3 plates cost ₹240

Compare the older way of building the same line with + and ordinary quotes: "Hello " + name + ", your bill is ₹" + total + ".". It works, but every space and every quote must be placed by hand, and one missing space gives HelloAsha. A template literal reads like the finished line, so slips are easier to see.

Strings over many lines

A template literal keeps its line breaks, exactly as typed:

const slip = `Name: Asha
Seat: 42`;
console.log(slip);
Name: Asha
Seat: 42

Single and double quotes do not allow a line break inside them. For a new line inside those, you write an escape sequence instead.

Escape sequences

Some characters are hard to put inside quotes: the quote mark itself, a new line, or a backslash. A backslash in front of a character gives it a special meaning.

Escape sequence

A backslash followed by a character, standing for one character that is hard to type inside quotes. \n stands for a new line.

WriteYou get
\na new line
\"a double quote, inside double quotes
\'a single quote, inside single quotes
\`a backtick, inside backticks
\\one backslash
\ta tab: a wide space
console.log("Line one\nLine two");
console.log("She said \"wait\"");
console.log('It\'s here');
console.log("C:\\files");
Line one
Line two
She said "wait"
It's here
C:\files

Each escape sequence is one character, however it is written. The string "a\\b" holds three characters, a, one backslash and b, and "\"" holds just one:

console.log("a\\b".length, "\"".length);
3 1

Length and positions

Every string knows its length: how many characters it holds, spaces and punctuation included. You read it with a dot, as you did in the Learning to learn step.

Index

The position of a character in a string, counted from 0. The first character is at index 0, the second at index 1, and the last at index length − 1. Read city[0] aloud as "city at 0".

Why count from 0? An index says how many steps a character is from the start, and the first character is zero steps in. Nearly every programming language counts this way, so it pays to get used to it now.

const city = "Pune";
console.log(city.length, city[0], city[3], city[4]);
4 P e undefined

"Pune" has 4 characters, at indexes 0, 1, 2 and 3. Asking for index 4 asks for a fifth character that does not exist, and JavaScript answers undefined, with no error.

To reach the last character, count back from the length, or use the method at, which also takes a negative number and counts from the end:

const city = "Pune";
console.log(city.at(-1), city[city.length - 1], city.at(0));
e e P

Strings cannot be changed

Immutable

Not able to be changed once made. Every string is immutable: you can build a new string from an old one, but you cannot change a character inside it.

let word = "cat";
word[0] = "b";
console.log(word);
cat

The line word[0] = "b"; gives no error, and changes nothing. In strict mode, which the modern JavaScript step explains, the same line is a TypeError instead. To change text, build the new string and put it into the name:

let word = "cat";
word = "b" + word.slice(1);
console.log(word);
bat

String methods

A string can do many jobs. Each job is a method, run with a dot and brackets, as toUpperCase() was in the Learning to learn step. These are the ones used most. The table writes each string answer in quotes, to show that it is a string.

MethodWhat it givesExampleAnswer
toUpperCase()the text in capitals"chai".toUpperCase()"CHAI"
toLowerCase()the text in small letters"PUNE".toLowerCase()"pune"
trim()the text without spaces at either end" ok ".trim()"ok"
includes(x)true if x is somewhere inside"Masala chai".includes("chai")true
startsWith(x)true if the text begins with x"Asha".startsWith("As")true
indexOf(x)the index where x first starts, or −1 if it is not there"Masala chai".indexOf("chai")7
slice(a, b)the characters from index a up to, but not including, index b"Masala chai".slice(0, 6)"Masala"
replace(x, y)the text with the first x changed to y"a-b-c".replace("-", "+")"a+b-c"
replaceAll(x, y)the text with every x changed to y"a-b-c".replaceAll("-", "+")"a+b+c"
padStart(n, c)the text made n characters long, with c added in front"7".padStart(4, "0")"0007"
repeat(n)the text n times over"ab".repeat(3)"ababab"

This block runs every example in the table. console.log prints text without its quotes.

console.log("chai".toUpperCase(), "PUNE".toLowerCase(), "  ok  ".trim());
console.log("Masala chai".includes("chai"), "Asha".startsWith("As"), "Masala chai".indexOf("chai"));
console.log("Masala chai".slice(0, 6), "a-b-c".replace("-", "+"), "a-b-c".replaceAll("-", "+"));
console.log("7".padStart(4, "0"), "ab".repeat(3));
CHAI pune ok
true true 7
Masala a+b-c a+b+c
0007 ababab

A method never changes the string it was called on, since strings are immutable. It gives back a new value, and you must keep that value if you want it:

let city = "pune";
city.toUpperCase();
console.log(city);
city = city.toUpperCase();
console.log(city);
pune
PUNE

A common mistake

Calling a method and throwing its answer away, as the second line above does. The name still holds the old text. Store the answer: city = city.toUpperCase();.

Worked example 5

The ferry office's ticket machine must print a line such as Passenger Asha, ticket 0007, fare ₹3.30. Its script has the name, the ticket number as the number 7, and the fare in paise: 110 for the ride and 220 for the harbour tax. Write the line.

What we have: the name as a string, the ticket number as the number 7, and the fare as 110 + 220 paise

What we need: one line of text, with the ticket number four characters long and the fare in rupees with two digits after the point

The plan: build the line with a template literal; turn the number into text and pad it; turn paise into rupees and fix two decimals

  1. The ticket number is the number 7, and padStart is a string method. So turn the number into text first with String(...), then pad it to 4 characters with zeros.
  2. The fare is 330 paise. Divide by 100 for rupees, then write two digits after the point with toFixed(2), which gives the string 3.30.
  3. Put the name and both answers into one template literal.
const name = "Asha";
const ticket = 7;
const farePaise = 110 + 220;
const number = String(ticket).padStart(4, "0");
const fare = (farePaise / 100).toFixed(2);
console.log(`Passenger ${name}, ticket ${number}, fare ₹${fare}`);
Passenger Asha, ticket 0007, fare ₹3.30

It prints Passenger Asha, ticket 0007, fare ₹3.30.

Check: the ticket part has four characters, 0007, and 330 paise is ₹3.30.

A path that fails: writing the line in double quotes: "Passenger ${name}" prints the gap as it stands, dollar sign and all, because only backticks fill gaps.

Worked example 6

A payment app shows a customer's phone number as ******3210, hiding all but the last four digits. The number is stored as the string 98765 43210, with a space in the middle. Build the hidden form.

What we have: the phone number as a string with a space in it

What we need: six stars followed by the last four digits

The plan: take the last four characters with slice(-4), and make the stars with repeat

  1. A negative number in slice counts from the end, so slice(-4) gives the last four characters: 3210. The space in the middle does not matter.
  2. "*".repeat(6) gives six stars.
  3. Join the two with +, and print the length too, as a check.
const phone = "98765 43210";
const hidden = "*".repeat(6) + phone.slice(-4);
console.log(hidden, hidden.length);
******3210 10

It shows ******3210.

Check: the hidden form has 10 characters, 6 stars and 4 digits, as its length shows.

Another way: phone.slice(-4).padStart(10, "*") does it in one step: it pads the last four digits with stars in front until the text is 10 characters long.

When you are stuck: text comes out wrong

If you see ${...} in the output, the string was written in ordinary quotes. Use backticks.

If you see undefined inside the text, a name in a gap holds no value, or an index went past the end. Print the name on its own.

If a method seems to do nothing, check that you stored its answer.

Count indexes from 0. The last character is at length − 1, not at length.

Your turn

const s = "Namaste";
console.log(s.length, s[0], s[s.length - 1], s.slice(1, 4));
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
7 N e ama
  1. Namaste has 7 characters.
  2. Index 0 is the first character, N.
  3. The last is at index 7 − 1 = 6: e.
  4. slice(1, 4) takes indexes 1, 2 and 3, and stops before 4: ama.

It prints 7 N e ama.

Make the initials AR from the string Asha Rao.Tap to reveal
  1. The first initial is the character at index 0.
  2. The second is the character just after the space: find the space with indexOf, and add 1.
const full = "Asha Rao";
console.log(full[0] + full[full.indexOf(" ") + 1]);
AR

full[0] + full[full.indexOf(" ") + 1] gives AR.

Print the line Order #42 is ready, with 42 kept in a name called order, using a template literal.Tap to reveal
const order = 42;
console.log(`Order #${order} is ready`);
Order #42 is ready

The gap ${order} is filled with 42: Order #42 is ready.

Did you know?

Backticks since 2015

Template literals are younger than many JavaScript habits. They arrived with ECMAScript 2015, the 6th edition of the standard, dated June 2015, which has a section called Template Literals. Before that, text with gaps was built by joining pieces with +, quote by quote. Older code, and older answers online, still build text that way.

Why it fits here: It explains why this topic meets both styles: + joins in older code, and backticks in newer code.

Source: ECMAScript 2015 Language Specification

One face, two code units

A string's length is not always the number of characters you see. JavaScript uses UTF-16, where each Unicode character may be encoded as one or two code units, and length counts code units. MDN warns that scripts such as emojis and mathematical symbols need care. So "😀".length is 2: one face, two code units.

Why it fits here: It refines this topic's rule on length: it counts code units, which match the characters for most text, but not for emojis.

Sources: MDN: String length; ECMAScript Language Specification: The String Type

In one line

Strings are written in single quotes, double quotes or backticks, and only backticks fill gaps with ${...}. A backslash starts an escape such as \n. Characters are counted from index 0. A string never changes, so keep what a method gives back.

Variables: names made with const, let and var

At a glance

In a kitchen, jars carry labels: rice, sugar, dal. The label stays the same while what is inside is used up and refilled. A variable is such a label: a name that holds a value, so that the value can be used and changed by its name.

Make names with const by default, with let when the value must change, and never with var, the old way. A const needs a first value and refuses a second. A name is declared once, used only below its line, and should say what it holds.

Take a guess: What happens if you give a const a second value?

In a kitchen, jars carry labels: rice, sugar, dal. The label stays the same while what is inside is used up and refilled. In the Learning to learn step you met a name made with let as "a jar you can refill". This section looks at how names are made and filled, and at which kind of jar to choose.

Variable

A name that holds a value, so that the value can be used, and changed, by its name. The value can be of any type.

Three words describe what happens to a variable. To declare it is to make the name. To initialise it is to give it its first value. To assign it is to put a value into it, at the start or later. Read = aloud as "is set to".

let count;        // declared, with no value yet
console.log(count);
count = 3;        // assigned
console.log(count);
let total = 10;   // declared and initialised in one line
console.log(total);
undefined
3
10

The name count existed from its first line, holding undefined, until the third line put 3 into it. The name total was declared and given its first value in one line, which is the usual way.

const: a sealed jar

A name made with const must be filled when it is made, and can never be filled again. JavaScript checks both rules.

const rate;
Uncaught SyntaxError: Missing initializer in const declaration

An initializer is the first value, the part after the =. A const with no first value could never get one, so JavaScript refuses the whole program. The second rule is checked while the program runs:

const rate = 18;
rate = 12;
console.log(rate);
Uncaught TypeError: Assignment to constant variable.
    at line 2

Why would anyone want a name that cannot change? Because most values in a program do not change: a tax rate, the number of seats in a hall, the name of a shop. Making them const tells every reader so, and JavaScript stops anyone who tries. A slip that changes one is caught at once, with a clear message, instead of spoiling a sum quietly.

let: a jar you can refill

A name made with let can be assigned as often as you like. Use it for values that must change: a running total, a count, the seats left in a hall.

Two rules guard let. First, a name can be declared only once in the same place. A second let with the same name is a SyntaxError, and as with every SyntaxError, nothing runs, not even the lines above it:

console.log("start");
let total = 5;
let total = 6;
Uncaught SyntaxError: Identifier 'total' has already been declared

Identifier is the language's word for a name. Look at what is missing: the word start was never printed. JavaScript reads the whole program before it runs any of it, and it will not run a program with a broken line in it.

Second, a name made with let cannot be used above the line that makes it:

console.log(price);
let price = 40;
Uncaught ReferenceError: Cannot access 'price' before initialization
    at line 1

This message differs from "price is not defined". JavaScript knows the name, since it read the whole program first, but the name may not be touched until its let line has run. The stretch of the program before that line is called the name's temporal dead zone. The scope lesson of this track comes back to it.

var: the old way

Before 2015, JavaScript had only one word for making a variable: var. You will meet it in old code and in old answers on the web, so you need to be able to read it. It breaks both of let's rules without a word:

console.log(seats);
var seats = 120;
var seats = 100;
console.log(seats);
undefined
100

Using seats above its line printed undefined, not an error. Before anything runs, every var name is made at the top of the program, but its value is not given until its own line runs. This is called hoisting, as if the name were lifted to the top. And declaring seats twice was allowed, so the second line quietly replaced the first value.

Both of these hide mistakes that let and const would catch. var also differs in where a name can be seen, which the scope lesson explains. So most teams today follow one rule.

Which to choose

Use const by default. Use let when the value must change. Do not use var in new code.

Good names

In the Learning to learn step you met the rules for names. Here they are again, with the message each broken rule gives:

The ruleBroken byThe message
letters, digits, _ and $ onlylet my-name = "x";SyntaxError: Unexpected token '-'
no digit firstlet 2fast = 1;SyntaxError: Invalid or unexpected token
not one of the language's own wordslet class = 1;SyntaxError: Unexpected token 'class'
capitals countlet Total = 1; and then totalReferenceError: total is not defined

The language's own words, such as let, const, class, if and return, are called reserved words. MDN's page on the lexical grammar lists them all. A name may contain one, as letter contains let, but may not be one.

Beyond the rules, working programmers follow habits that make names easy to read:

  • camelCase for most names: the words joined, each one after the first starting with a capital, as in seatsLeft and totalPrice.
  • UPPER_SNAKE_CASE for fixed settings, as in GST_RATE: capitals, with underscores between the words.
  • A name that says what the value is: seatsLeft, not s or x.
  • A boolean named as a yes-or-no question: isPaid, hasTicket.
const GST_RATE = 18;
const price = 500;
console.log(price * GST_RATE / 100);
90

Anyone can read that line and see that it works out 18 percent of 500. With names such as a and b it would need a comment to explain it.

Comments

A comment is a note for people, which JavaScript skips. Two slashes start a comment that runs to the end of its line. A slash and a star start one that can run over many lines, and a star and a slash end it.

// a note for people
/* a longer note,
   over two lines */
console.log("comments are skipped");
comments are skipped

A good comment says why, not what. // add one only repeats the code beside it. // the first ticket of the day is number 1, not 0 tells the reader something that the code cannot.

Worked example 7

A cinema app keeps the price of a ticket, ₹180, the number of seats in the hall, 120, and the seats left, which go down as people book. Asha books 4 seats. Choose const or let for each name, then print the seats left and her bill.

What we have: a ticket price of 180, a hall of 120 seats, and a booking of 4

What we need: the right kind of name for each value, the seats left, and the bill

The plan: ask of each value: will it change while the app runs?

  1. The ticket price stays the same all evening: const, and in capitals, as a fixed setting.
  2. The number of seats in the hall never changes: const.
  3. The seats left change with every booking: let, starting with the full hall.
  4. The bill is worked out once for this booking: const.
const TICKET_PRICE = 180;
const SEATS = 120;
let seatsLeft = SEATS;
const booked = 4;
seatsLeft = seatsLeft - booked;
const bill = booked * TICKET_PRICE;
console.log(`Seats left: ${seatsLeft}, bill: ₹${bill}`);
Seats left: 116, bill: ₹720

It prints Seats left: 116, bill: ₹720, with only seatsLeft made with let.

Check: 120 − 4 is 116, and 4 × 180 is 720.

A path that fails: making seatsLeft a const as well. The line that takes away the booking then stops the program with TypeError: Assignment to constant variable.

When you are stuck: which error is it?

A SyntaxError means nothing ran at all. Look for a let or const written twice for one name, a const with no value, or a broken name.

ReferenceError: x is not defined means the name was never made, or is spelt differently, capitals included.

ReferenceError: Cannot access 'x' before initialization means the name is made lower down. Move its let or const above the line that uses it.

TypeError: Assignment to constant variable. means a const was changed. Use let, or find out why it changed.

Your turn

const x = 5;
let y;
console.log(x, y);
y = x * 2;
console.log(y);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
5 undefined
10
  1. x is 5 from its first line.
  2. y is declared with no value, so it holds undefined.
  3. Then y is set to 5 × 2.

It prints 5 undefined, then 10.

Which of these names are allowed: seats_left, 3seats, seatsLeft, seats-left, $seats, let?Tap to reveal
  1. seats_left: letters and an underscore, allowed.
  2. 3seats: starts with a digit, not allowed.
  3. seatsLeft: allowed, and in camelCase.
  4. seats-left: a hyphen is read as a minus sign, not allowed.
  5. $seats: a dollar sign is allowed.
  6. let: one of the language's own words, not allowed.

seats_left, seatsLeft and $seats are allowed.

A program's first line prints start, but when you run it, nothing prints except SyntaxError: Identifier 'count' has already been declared. Why did start not print, and what is the fix?Tap to reveal
  1. A SyntaxError is found while JavaScript reads the program, before any line runs, so even the first line never ran.
  2. The message names count: somewhere, count is declared twice with let.
  3. If the second line meant to change the value, remove its let, so that it assigns instead of declaring.

Nothing ran because of the SyntaxError. Remove the second let, so that the line becomes an assignment.

Did you know?

Names in Hindi

JavaScript names are not limited to English letters. MDN explains that identifiers are not limited to ASCII: a name may start with any character in Unicode's ID_Start category, or with _ or $. Unicode lists the Devanagari letters as ID_Start and its vowel signs as ID_Continue, so राशि is a valid name. Whether to use such names is a team's choice; these lessons use English ones.

Why it fits here: It shows that this topic's naming rules are about clarity, not a limit of the language: the language accepts far more than good style.

Sources: MDN: Lexical grammar; Unicode Character Database: DerivedCoreProperties.txt

let and const since 2015

The jar labels let and const are young. They came with ECMAScript 2015, whose section 13.3.1 is called Let and Const Declarations; before that edition, var made every variable. A name made with let can only be used after the place of its declaration is reached. MDN calls the stretch before it the temporal dead zone.

Why it fits here: It is why this topic prefers const and let: they are the newer way, and var stays for old code.

Sources: ECMAScript 2015 Language Specification; MDN: let

In one line

Make names with const by default, with let when the value must change, and never with var. A const needs a first value and refuses a second. A name is declared once, used only below its line, and should say what it holds.

Changing a value

At a glance

On a cricket scoreboard, the runs go up by 4, by 6, by 1, and the wickets go up one at a time. Nobody rubs out the whole board after each ball; the scorer adds to what is there. Code changes values in the same way.

In code, = does not mean equals. It sets the name on its left to the value on its right, worked out with the old value. Shortcuts such as += and *= change a name by a step, and ++ and -- change it by one. Assigning a number or a string copies it, so two names never share it.

Take a guess: If runs is 10, what is runs after runs = runs + 4?

On a cricket scoreboard the runs go up by 4, by 6, by 1, and the wickets go up one at a time. Nobody rubs out the whole board after each ball. The scorer adds to what is already there. Code changes values in the same way.

First, read the plain way of doing it slowly: runs = runs + 4. As a statement in mathematics it would be false, since no number equals itself plus 4. In code, = means "is set to". The right side is worked out first, using the old value of runs, and the answer then goes into runs.

let runs = 10;
runs = runs + 4;
console.log(runs);
14

The shortcuts

Changing a name by a step is so common that JavaScript has a short form for each operator. Each is called an assignment operator: it works out a new value and assigns it in one go.

WriteIt meansRead it aloud
runs += 4runs = runs + 4runs is increased by 4
stock -= 2stock = stock - 2stock is decreased by 2
bill *= 2bill = bill * 2bill is multiplied by 2
share /= 4share = share / 4share is divided by 4
n %= 3n = n % 3n is set to its remainder after dividing by 3
n **= 2n = n ** 2n is raised to the power 2
let stock = 50;
stock -= 3;
stock -= 2;
let bill = 0;
bill += 120;
bill += 45;
bill *= 2;
console.log(stock, bill);
45 330

Follow each name down the lines. stock starts at 50, loses 3 to make 47, then loses 2 to make 45. bill starts at 0, gains 120, then 45, making 165, and is then doubled to 330.

Going up or down by one

Adding one is the most common change of all: one more visitor, one more ticket, one more ball. visitors++ means "visitors goes up by one", and visitors-- means "visitors goes down by one". The ++ is called the increment operator, and the -- the decrement operator.

let visitors = 0;
visitors++;
visitors++;
visitors--;
console.log(visitors);
1

The ++ can go before or after the name. The two forms differ in one way only: the value they give back when they sit inside a bigger line.

let a = 5;
const b = a++;
const c = ++a;
console.log(a, b, c);
7 5 7

In the second line, a++ gives b the old value of a, which is 5, and only then adds one, so a becomes 6. In the third line, ++a adds one first, so a becomes 7, and then gives c the new value, 7.

Keep ++ on its own line

On a line of its own, as in visitors++;, both forms do exactly the same thing. Surprises come only when ++ sits inside a bigger line, so many teams keep it on a line of its own.

Changing text

+= works on strings too. It joins, as + does, and it is a common way to build text one piece at a time.

let msg = "Order";
msg += " #";
msg += 42;
console.log(msg);
Order #42

A common mistake

Using += on a string of digits that you meant as a number. A string "5" with += 1 becomes the text 51. The ++ operator always does arithmetic, so the same string with ++ becomes the number 6. Two names that look alike end up as different types:

let a = "5";
a += 1;
let b = "5";
b++;
console.log(a, typeof a, b, typeof b);
51 string 6 number

Copying a value

When you assign one name to another, the value is copied. The two names then live separate lives:

let a = 100;
let b = a;
a = 200;
console.log(a, b);
200 100

b received a copy of 100. Changing a afterwards did not touch b. This holds for every primitive value: numbers, strings, booleans and the rest. Objects behave differently, and the objects lesson of this track shows how.

Swapping two values

To swap the contents of two glasses, you need a third, empty glass to hold one of them while you pour. Code needs the same:

let left = 10;
let right = 20;
let spare = left;
left = right;
right = spare;
console.log(left, right);
20 10

spare keeps a copy of 10. Then left takes 20 from right, and right takes 10 from spare. Without spare, the first pour would lose the 10 for good. The modern JavaScript step shows a way to swap in one line.

Worked example 8

A rice godown starts the week with 500 bags. On Monday 120 bags go out. On Tuesday a lorry brings 80. On Wednesday 35 go out. The manager also counts the changes, one for each. Write the changes with assignment operators, and print the stock and the count.

What we have: 500 bags at the start, and three changes: out 120, in 80, out 35

What we need: the bags left after Wednesday, and the number of changes

The plan: keep the bags and the count in names made with let; change the bags with -= and +=, and count each change with ++

let bags = 500;
let moves = 0;
bags -= 120;
moves++;
bags += 80;
moves++;
bags -= 35;
moves++;
console.log(`Bags: ${bags}, changes: ${moves}`);
Bags: 425, changes: 3
  1. Each -= or += changes bags by one day's movement, and each ++ adds one change to the count.

It prints Bags: 425, changes: 3.

Check: 500 − 120 + 80 − 35 is 425, and there were three days of changes.

A path that fails: writing bags - 120; with no = at all. The line works out 380 and throws it away, so bags stays 500. Nothing warns you, as the block just below shows with a smaller example.

let x = 5;
x + 1;
console.log(x);
5

When you are stuck: a value did not change

Check that the line stores its answer: bags - 120; works out a value and drops it, while bags -= 120; keeps it.

Check that the name was made with let, as a const cannot change.

Print the value just before and just after the line, each with a label.

If text grew where a number should have, the value was a string. Look for quotes, or for a value that came from a page.

Your turn

let runs = 0;
runs += 4;
runs += 6;
runs += 1;
let wickets = 0;
wickets++;
console.log(`${runs}/${wickets}`);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
11/1
  1. runs goes from 0 to 4, then 10, then 11.
  2. wickets goes up by one, to 1.
  3. The template literal puts a slash between them, as Indian scoreboards write runs for wickets.

It prints 11/1: 11 runs for 1 wicket.

What does let n = 10; n %= 4; n **= 3; leave in n?Tap to reveal
  1. n %= 4 sets n to the remainder of 10 ÷ 4: four goes into ten twice, and 2 is left.
  2. n **= 3 raises 2 to the power 3: 2 × 2 × 2.
let n = 10;
n %= 4;
n **= 3;
console.log(n);
8

n holds 8.

After let a = "tea"; let b = a; a += " with milk";, what do a and b hold?Tap to reveal
  1. b received a copy of the string tea.
  2. a was then given a new, longer string. Strings cannot change, so b's copy is untouched.
let a = "tea";
let b = a;
a += " with milk";
console.log(a, "|", b);
tea with milk | tea

a holds tea with milk, and b still holds tea.

Did you know?

When += was =+

The shortcut += once had its sign the other way round. Dennis Ritchie's history of C tells how B introduced generalized assignment operators, written x=+y to add y to x. In B and early C the operator was spelled =+, and Ritchie calls that a mistake, repaired in 1976. The fix put the sign first, as += is written in C and in JavaScript today.

Why it fits here: It shows that this topic's shortcuts are older than JavaScript: they came down from B and C.

Source: Dennis M. Ritchie: The Development of the C Language

Who invented ++

The ++ and -- operators have a known inventor. Ken Thompson created the B language in 1969 and 1970, and Ritchie writes that Thompson went a step further by inventing the ++ and -- operators. Their place, before or after the name, decides whether the change happens before or after the value is noted. That is why this topic keeps them on a line of their own.

Why it fits here: Since the two places differ, a ++ inside a longer line is easy to misread; on a line of its own, both mean the same.

Source: Dennis M. Ritchie: The Development of the C Language

In one line

The = sign sets a name to the value on its right, worked out with the old value. The operators += -= *= /= %= **= change a name by a step, and ++ and -- change it by one; keep those on a line of their own. Assigning copies a primitive value, so two names never share it.

Turning one type into another

At a glance

A form on a page hands you everything as text, even a price or an age. Before you can add, the text must become a number. Turning one type into another is called conversion.

Number() turns a whole string into a number, or NaN if it cannot. Then parseInt and parseFloat read from the front and stop at the first character they cannot use, so "260px" gives 260. String() and template literals turn values into text. And JavaScript sometimes converts on its own, which is where surprises live.

Take a guess: What does Number give for an empty string?

A customer types 3 into the quantity box of a shopping page. The page hands your code the string "3", never the number 3, because a box on a page holds text. Before you can multiply, the text must become a number. To show the total on the page, it must become text again. Values change type all the time on their way through a program.

A value's type can change in two ways. You can ask for the change by name, with a function such as Number(...). This is explicit conversion. Or JavaScript can change the type for you, without being asked, when an operator needs another type. This is implicit conversion, which the Learning to learn step called type coercion.

Into a number

Number(...) reads the whole string as one number, or gives NaN if it cannot. Most of its answers are what you would expect. A few are not, and they cause real bugs:

console.log(Number("42"), Number(" 42 "), Number(""), Number("4 2"), Number("12px"));
42 42 0 NaN NaN
console.log(Number(true), Number(false), Number(null), Number(undefined));
1 0 0 NaN
What goes inNumber(...) givesWhy
"42"42the digits are read as a number
" 42 "42spaces at the two ends are dropped first
"", an empty box0an empty string counts as zero: a trap
"4 2"NaNa space in the middle stops it
"12px"NaNa letter anywhere stops it
true and false1 and 0true counts as one, false as zero
null0nothing on purpose counts as zero
undefinedNaNno value cannot be a number

The empty string is the one to remember. A quantity box left empty gives Number(""), which is 0. So a cart can quietly show a bill of ₹0, where it should have asked the customer to type a quantity.

parseInt and parseFloat: reading from the front

Sometimes a number sits at the start of some text, as in 12px or 3.5kg. parseInt reads a whole number from the front of a string, and stops at the first character that cannot belong to one. parseFloat does the same, but also reads a decimal point and the digits after it.

Parse

To read text and work out what it means. Read parseInt aloud as "parse integer" and parseFloat as "parse float": an integer is a whole number, and a float is a floating-point number.

console.log(parseInt("12px"), parseFloat("3.5kg"), parseInt("3.9"), parseInt("px12"));
12 3.5 3 NaN

parseInt read 12 and stopped at p. parseFloat read 3.5 and stopped at k. parseInt on 3.9 stopped at the point, so it gave 3: it cuts, and does not round. And px12 gave NaN, because there was no number at the front to read.

Into a string

Going the other way, String(...) turns any value into text, and every number has a toString() method that does the same. toString can also write a number in another base: 2 for binary.

console.log(String(42), String(true), String(null), (255).toString(), (255).toString(2));
42 true null 255 11111111

The brackets around 255 are needed. A dot straight after digits would be read as a decimal point, so 255.toString() is a SyntaxError:

console.log(255.toString());
Uncaught SyntaxError: Invalid or unexpected token

A template literal turns the value in each gap into text too, whatever its type. That is how undefined and null can turn up as words in the middle of a sentence:

let city;
console.log(`From ${city}`, `To ${null}`);
From undefined To null

When JavaScript converts for you

Operators convert on their own, by the rules you met in the Learning to learn step: + joins if either side is a string, and the other arithmetic operators turn strings into numbers. The operators run from left to right, one pair at a time, which explains all four of these:

console.log("6" * "7", "6" + 7, 6 + 7 + "px", "px" + 6 + 7);
42 67 13px px67
  • "6" * "7": * only does arithmetic, so both strings become numbers: 42.
  • "6" + 7: one side is a string, so + joins: the text 67.
  • 6 + 7 + "px": the left pair first. 6 + 7 is the number 13, and 13 + "px" joins: 13px.
  • "px" + 6 + 7: the left pair first again. "px" + 6 joins to make px6, and px6 + 7 joins again: px67.

A short form that you will see in other people's code is a plus sign in front of a value. It turns the value into a number, by the same rules as Number(...), empty string included:

console.log(+"42", +"", +"abc");
42 0 NaN

After any conversion that might fail, check the answer. Number.isNaN gives true when the conversion did not find a number:

const typed = "abc";
const qty = Number(typed);
console.log(qty, Number.isNaN(qty));
NaN true

Convert on purpose

Do not lean on the automatic rules. When a value comes from a page, a file or another program, convert it yourself, once, at the point where it arrives, and check the answer. Every line after that then works with the type it expects.

Worked example 9

A shopping page reads the quantity box as text. Work out the bill for an item at ₹45 when the box holds "3", and say what happens when the box is left empty.

What we have: the box's text, and a price of 45

What we need: the bill, and what an empty box does to it

The plan: convert the text with Number(...) once, then multiply; then try the empty string

const typed = "3";
const qty = Number(typed);
console.log(qty * 45);
135
  1. Now leave the box empty. The page gives the empty string, and the conversion gives 0 with no complaint:
const typed = "";
console.log(Number(typed) * 45, typed === "");
0 true
  1. The check typed === "" gives true for an empty box. The next lesson's if statement lets the page act on it, by asking for a quantity instead of showing ₹0.

₹135 for three items. An empty box gives 0, so the page must check for the empty string first.

Check: 3 × 45 is 135.

A path that fails: multiplying the text as it stands. "3" * 45 happens to give 135 as well, by the automatic rules, but the same value with + in a later line, "3" + 45, gives the text 345.

Worked example 10

A page's script reads a box's width as the text 240px. Make the box 20 pixels wider, and write the new width back as text.

What we have: the width as the string 240px

What we need: the string 260px

The plan: read the number from the front with parseInt, add 20, and put the px back with a template literal

const width = "240px";
const wider = parseInt(width) + 20;
console.log(`${wider}px`);
260px
  1. parseInt("240px") reads 240 and stops at p. Adding 20 makes the number 260, and the template literal joins it with px.

The new width is 260px.

Check: 240 + 20 is 260, and the unit is back on the end.

A path that fails: converting with Number(...). Number("240px") is NaN, NaN + 20 is NaN, and the new width would be the text NaNpx, which is not a width at all.

When you are stuck: a conversion gives NaN or 0

Print the value between brackets, so spaces and empty strings show up: console.log("[" + typed + "]");.

NaN from Number(...) means some character was not part of a number. If the number is at the front, use parseFloat.

0 from an empty box is not an amount. Check for the empty string first.

A sum that joins instead of adding has a string on one side. Convert it with Number(...).

Your turn

console.log(Number("  7 "), parseInt("7.9 kg"), String(7) + 7, "7" * "7");
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
7 7 77 49
  1. Number drops the spaces at the ends: 7.
  2. parseInt reads 7 and stops at the point: 7.
  3. String(7) is text, so + joins: 77.
  4. * does arithmetic, so both strings become numbers: 49.

It prints 7 7 77 49.

What does Number(null) + Number(undefined) give, and why?Tap to reveal
  1. Number(null) is 0: nothing on purpose counts as zero.
  2. Number(undefined) is NaN.
  3. 0 + NaN is NaN, since NaN spreads through arithmetic.
console.log(Number(null) + Number(undefined));
NaN

It gives NaN.

The text ₹1,250 arrives from a page. Turn it into the number 1250.Tap to reveal
  1. Number cannot read the ₹ sign or the comma, so remove them first.
  2. slice(1) drops the first character, the ₹ sign.
  3. replaceAll removes every comma.
const text = "₹1,250";
const n = Number(text.slice(1).replaceAll(",", ""));
console.log(n, typeof n);
1250 number

Number(text.slice(1).replaceAll(",", "")) gives the number 1250.

Did you know?

Nothing becomes zero

One conversion surprises nearly everyone. MDN notes that empty or whitespace-only strings are converted to 0, and the standard agrees: a string of only white space has the value +0. So Number("") and Number(" ") both give 0, not NaN. An empty box on a form can turn into a real zero in a sum, so test for an empty string first when empty should mean missing.

Why it fits here: It is a trap of this topic's conversions: an empty input is not NaN, so a missing price can quietly count as zero.

Sources: MDN: Number; ECMAScript Language Specification

Two nothings, two numbers

The two kinds of nothing convert differently. MDN's list of number conversions says that undefined turns into NaN, while null turns into 0. The standard's own ToNumber steps agree: if the value is undefined, return NaN; if it is null or false, return +0. So a sum with a missing value can give NaN or a quiet zero, depending on which nothing it met.

Why it fits here: It joins two ideas of this lesson: null and undefined differ in meaning, and also in what they become as numbers.

Sources: MDN: Number; ECMAScript Language Specification: ToNumber

In one line

Convert on purpose. Number(...) reads a whole string: an empty one gives 0, and a stray character gives NaN. parseInt and parseFloat read a number from the front, and String(...) and toString() make text. The + sign joins when either side is text, and operators run from left to right.

Where it is used

Values and names are in every line of every program. Here is where each idea of this lesson shows up in real work.

What you learnedWhere it is usedA real example
types and typeofchecking data before using ita results portal checks that each mark arrived as a number before adding it to a total
undefined and nullfields that are not filled in yet, or empty on purposea food delivery order keeps its delivery time undefined until the rider arrives, and null if the order is cancelled
money in paiseshops, banks and payment servicesa payment service takes ₹3.30 as 330, in the smallest unit, so every sum is exact
toFixed and Math.roundprices, marks and percentages on screena results portal shows a percentage of 87.666... as 87.67
BigInt, or a string, for long IDsvery long numbersan ID longer than sixteen digits is kept as text, so that its last digits survive
template literalsevery message a program showsan SMS that reads: Your OTP is 4821, valid for 10 minutes
padStart and sliceinvoice numbers, tickets, hidden digitsa GST invoice numbered INV-0042, and a card shown as ************1234
string methodssearch boxes and formsa search box trims the spaces and compares in small letters, so " Pune " finds pune
const and letevery programa tax rate kept in a const, and a cart total kept in a let that grows with each item
assignment operatorscounters, totals and scoresa cricket app adds each ball's runs to the score with +=
conversionsevery form and every filea quantity box's "3" becomes the number 3 before the bill is worked out

Mistakes and debugging

These are the slips that people meet most often with values and names, with what each one prints and the fix. Every output below is the real one, from the code shown. Four of them give no error at all, which makes them the most dangerous.

1. A gap in ordinary quotes

const name = "Asha";
console.log("Hello ${name}");
Hello ${name}

No error: the gap is printed as it stands. The fix: only backticks fill gaps. Write `Hello ${name}`.

2. A const with no value

const rate;
Uncaught SyntaxError: Missing initializer in const declaration

The fix: give the const its value on the same line. If the value is not known yet, make the name with let.

3. The same name declared twice

let total = 5;
let total = 6;
Uncaught SyntaxError: Identifier 'total' has already been declared

The fix: the second line meant to change the value, so drop its let: total = 6;. If it meant a new value, give it a new name.

4. A name used above its line

console.log(price);
let price = 40;
Uncaught ReferenceError: Cannot access 'price' before initialization
    at line 1

The fix: move the let or const above the first line that uses the name.

5. A method's answer thrown away

let city = "pune";
city.toUpperCase();
console.log(city);
pune

No error: the method gave back PUNE, and nothing kept it. The fix: city = city.toUpperCase();.

6. Arithmetic after toFixed

const price = 19.99;
console.log(price.toFixed(2) + 1);
19.991

No error: toFixed gives a string, so + joins. The fix: do all the arithmetic first, and call toFixed last, only to show the answer.

7. An empty box read as zero

const typed = "";
console.log(Number(typed) * 45);
0

No error: an empty string converts to 0. The fix: check typed === "" before converting, and ask for a value instead.

8. A BigInt mixed with a number

console.log(10n + 5);
Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions
    at line 1

The fix: convert one side, as the message asks: 10n + BigInt(5) gives 15n, and Number(10n) + 5 gives 15.

console.log(10n + BigInt(5), Number(10n) + 5);
15n 15

9. A label written as a number

const roll = 0042;
console.log(roll);
34

A number that starts with 0 and holds only the digits 0 to 7 is read in base 8. The fix: a roll number is a label, so write it as a string: "0042".

The debugging corner: ask the value what it is

When a line gives a strange answer, print each value with its type: console.log(x, typeof x);. A string where you expected a number, or undefined where you expected a value, explains most of the slips above. You can also try a conversion in the Console of the DevTools step before writing it into a program: type Number("") and see the 0 for yourself.

Quick card

The whole lesson on one card. Come back to it whenever you need a reminder.

The lesson in code

// eight types: typeof names them (null says "object")
console.log(typeof 42, typeof "hi", typeof true, typeof undefined, typeof null);

// numbers: one type; count money in paise; round only to show
console.log(0.1 + 0.2, (110 + 220) / 100, (3.3).toFixed(2), Math.round(2.5));

// strings: backticks fill gaps; indexes from 0; methods give new strings
const name = "Asha";
console.log(`Hi ${name}`, name[0], name.length, name.toUpperCase(), "7".padStart(3, "0"));

// names: const by default, let to change, never var
const RATE = 18;
let total = 100;
total += total * RATE / 100;
total++;
console.log(total);

// converting: Number reads all of it, parseInt the front
console.log(Number(""), Number("12px"), parseInt("12px"), String(5) + 5);
number string boolean undefined object
0.30000000000000004 3.3 3.30 3
Hi Asha A 4 ASHA 007
119
0 NaN 12 55
When you seeIt meansLook at
${name} printed as it standsthe string is in ordinary quotesuse backticks
a long tail of digitsa decimal not stored exactlycount in paise; round only to show
NaNarithmetic or a conversion failedprint each value and its typeof
undefinedno value yet, or an index past the endthe name's first line; the index
SyntaxError: Missing initializer in const declarationa const with no valuegive it one, or use let
SyntaxError: Identifier '...' has already been declaredone name declared twiceassign the second time, with no let
ReferenceError: Cannot access '...' before initializationa name used above its linemove the let or const up
TypeError: Assignment to constant variable.a const was changeduse let, or find out why it changed

The story: Every value in its box

You go through the script line by line, and ask each value what kind of thing it is. Three of the answers surprise you. You change the quotes around the greeting, keep the ticket number as text with its zeros in front, and count the fare in paise until the very last moment.

The machine clicks, and a new ticket slides out: Passenger Asha, ticket 0007, fare ₹3.30. The ferry clerk reads it twice, and pins it to her board.

Master Verge winds the machine shut. "You did not guess," he says. "You asked each value what it was. Tomorrow the clocks must decide things for themselves."

Reagents gathered: typeof, template literal, const and let, paise, padStart, toFixed.

Sources