Programming fundamentals · Beginner · 15 min
Declare variables with let and const in JavaScript, and understand its types
By Padding · Updated 18 Nov 2026
Node.js 26.13.1 LTS · node:26 image
You will declare variables with const and let in Node.js, see block scope and the seven primitive types for yourself, predict JavaScript's type coercion, and finish with a script that turns text input into numbers safely.
On this page
A variable is a name that points at a value, so you can use the value later without typing it again. JavaScript has three keywords for making one: const, let and the older var. Picking the right one is the first habit worth building, because it tells anyone reading your code, including you next month, which values are meant to change.
JavaScript is also loose about types. It will happily add a string to a number and give you an answer instead of an error. That answer is not always the one you expected, and many beginner bugs in web forms come from it: a price typed into a box arrives as text, not as a number.
In this tutorial you try variables in Node's interactive prompt, then write five short scripts: one for const and let, one for scope, one for types, one for template strings and coercion, and a final one that turns form-style text into numbers and rejects input that is empty, not a number, infinite or negative. Commands are shown for a Linux or macOS shell; on Windows, PowerShell runs the node commands the same way.
Step 1 · Try const and let in the REPL
The REPL (read, evaluate, print, loop) is a prompt where Node.js runs each line as you type it and prints the result. Start it by running node with no file name:
nodeThe prompt changes to >. Type these lines one at a time, pressing Enter after each:
const city = "Lagos"
city
city = "Accra"
let visits = 1
visits = visits + 1
typeof cityHere is what each line does:
const city = "Lagos"creates a variable calledcityand points it at the string"Lagos". The REPL printsundefined, because a declaration itself has no value to show.cityon its own asks for the value, and the REPL prints'Lagos'. The quotes tell you it is a string.city = "Accra"tries to pointcityat a new value.constforbids that, so you get an error.let visits = 1creates a variable that is allowed to change.visits = visits + 1reads the current value, adds one and stores the result back invisits. The REPL prints2.typeof cityasks what type of valuecityholds. It prints'string'.
Leave the REPL with .exit or by pressing Ctrl+D.
Check it worked
The third line printed something like Uncaught TypeError: Assignment to constant variable. and the REPL kept running. The line after visits = visits + 1 printed 2. If you see ReferenceError: city is not defined, the first line had a typo; type it again.
Step 2 · Use const by default and let when the value changes
The rule most JavaScript teams follow is short: declare everything with const, and switch to let only when you find you need to reassign it. Make a folder for this tutorial and write a script that shows both:
mkdir -p ~/js-variables-demo
cd ~/js-variables-demo
cat > basket.js <<'JS'
const shopName = "Mama Ada's Stores";
let itemsInBasket = 0;
itemsInBasket = itemsInBasket + 1;
itemsInBasket += 2;
console.log(shopName, "has", itemsInBasket, "items in the basket");
const prices = [500, 1200];
prices.push(300);
console.log(prices);
JS
node basket.jsLine by line:
const shopName = ...holds a value that never changes while the script runs. The string uses double quotes so the apostrophe inside it needs no special treatment.let itemsInBasket = 0;starts a counter. It must belet, because the next two lines change it.itemsInBasket += 2;is shorthand foritemsInBasket = itemsInBasket + 2;.console.log(...)prints its arguments separated by spaces.const prices = [500, 1200];makes a list (an array).prices.push(300)adds to the end of it, and that is allowed even thoughpricesisconst.
That last point catches many beginners. const fixes which value the name points at; it does not freeze the value. You cannot write prices = [], but you can change what is inside the array. For the same idea in Python, see understand variable references and mutability.
Check it worked
The output is two lines:
Mama Ada's Stores has 3 items in the basket
[ 500, 1200, 300 ]Change let itemsInBasket to const itemsInBasket and run the script again: Node stops with TypeError: Assignment to constant variable. and points at the line that tried the change. Put let back before you continue.
Step 3 · See block scope, and why var is avoided
A block is the code between a pair of curly braces, such as the body of an if. A variable made with const or let inside a block exists only inside that block. This is called block scope, and it stops a name used in one place from leaking into code elsewhere. var does not follow this rule, which is the main reason modern code avoids it:
cd ~/js-variables-demo
cat > scope.js <<'JS'
const price = 1000;
if (price > 500) {
const discount = 100;
let note = "discount applied";
console.log(price - discount, note);
}
console.log(typeof discount);
if (true) {
var leaked = "var ignores the block";
}
console.log(leaked);
console.log(early);
var early = "assigned later";
try {
console.log(notYet);
} catch (err) {
console.log(err.name + ": " + err.message);
}
let notYet = "assigned later";
JS
node scope.jsWhat happens, in order:
- Inside the
ifblock,priceis visible because it was declared outside, in the enclosing scope.discountandnoteare visible because they were declared in the same block. - After the block,
discountno longer exists.typeof discountprintsundefinedinstead of crashing, becausetypeofis the one operator that accepts a name that was never declared. var leakedis declared inside a block, yet it is still readable after the block closes. In a long file, that is how two unrelated pieces of code end up sharing and overwriting one variable.console.log(early)runs before the line that setsearly, and printsundefinedwith no warning. JavaScript creates everyvarat the start of its function or file (this is called hoisting) and fills it in later.- Reading
notYetbefore itsletline throws aReferenceError.letandconstare hoisted too, but reading them early is an error rather than a silentundefined. Thetry/catchcatches the error so the script can print it and finish.
A loud error on the line with the mistake is much easier to fix than a silent undefined that surfaces somewhere else. That is the practical case for let and const.
Check it worked
The output is:
900 discount applied
undefined
var ignores the block
undefined
ReferenceError: Cannot access 'notYet' before initializationStep 4 · Check the seven primitive types with typeof
A primitive is a single, simple value that is not an object. JavaScript has seven kinds: number, string, boolean, undefined, null, bigint and symbol. Everything else, including arrays and functions, is an object. This script prints the type of one example of each:
cd ~/js-variables-demo
cat > types.js <<'JS'
const examples = [
["number", 42.5],
["string", "Kigali"],
["boolean", true],
["undefined", undefined],
["null", null],
["bigint", 9007199254740993n],
["symbol", Symbol("id")],
];
for (const [label, value] of examples) {
console.log(label.padEnd(10), typeof value);
}
let notSetYet;
console.log(notSetYet);
console.log(Number.MAX_SAFE_INTEGER + 2);
console.log(9007199254740991n + 2n);
console.log(0.1 + 0.2);
JS
node types.jsHow it works:
examplesis an array of pairs: a label and a value of that type.for (const [label, value] of examples)visits each pair and unpacks it into two names.constis fine here because each pass of the loop gets a freshlabelandvalue.label.padEnd(10)adds spaces to the label so the second column lines up.let notSetYet;declares a variable without a value. Its value isundefined, which means "nothing has been put here yet".nullis different: it is a value you assign on purpose to mean "empty".numberis the type for both whole numbers and decimals. It stores them as 64-bit floating point, so whole numbers are exact only up toNumber.MAX_SAFE_INTEGER(9,007,199,254,740,991). Past that, adding 2 gives the wrong answer.- A number with
non the end is abigint, which stays exact at any size. You cannot mix it with ordinary numbers in one sum without converting first. 0.1 + 0.2shows the other side of floating point: some decimals cannot be stored exactly. For money, many programs count in the smallest unit (kobo, cents, pesewas) as whole numbers.
Check it worked
Every row shows the same word twice, except null, which shows object. That is a known mistake from the first version of JavaScript in 1995, kept so old web pages still work. To test for null, write value === null, not typeof. The last four lines are undefined, 9007199254740992 (wrong by one), 9007199254740993n (correct) and 0.30000000000000004.
Step 5 · Build text with template literals
A template literal is a string written between backticks (` ` ``) instead of quotes. Inside it, `${...} runs any expression and puts the result into the text. It replaces long chains of +, and it can span several lines:
cd ~/js-variables-demo
cat > greet.js <<'JS'
const name = "Amara";
const items = 3;
const pricePerItem = 450;
const withPlus = "Hello " + name + ", you have " + items + " items.";
const withTemplate = `Hello ${name}, you have ${items} items costing ${items * pricePerItem}.`;
console.log(withPlus);
console.log(withTemplate);
console.log(`Two lines:
second line`);
JS
node greet.jswithPlusjoins five pieces with+. It works, but the spaces around each piece are easy to get wrong.withTemplatewrites the sentence as it reads.${items * pricePerItem}is worked out first, then turned into text.- The last
console.logshows that a newline typed inside backticks stays in the string.
Template literals take any text, including accented letters, Arabic or Amharic script and emoji, because JavaScript strings are Unicode. If you build messages for users in several languages, keep each whole sentence as one template so a translator can reorder the parts.
Check it worked
The output is:
Hello Amara, you have 3 items.
Hello Amara, you have 3 items costing 1350.
Two lines:
second lineIf you see ${name} printed literally, you used quotes instead of backticks.
Step 6 · Predict type coercion and use ===
When an operator gets values of the wrong type, JavaScript converts one of them for you. This is called type coercion. Write down what you expect each line to print, then run the script and compare:
cd ~/js-variables-demo
cat > coercion.js <<'JS'
console.log("5" + 1);
console.log("5" - 1);
console.log("5" * "2");
console.log(true + 1);
console.log("0" == 0);
console.log("0" === 0);
console.log("" == 0);
console.log(null == undefined);
console.log(null === undefined);
JS
node coercion.jsThe reasons:
"5" + 1gives51. If either side of+is a string,+joins text, so the number 1 becomes the string"1"."5" - 1gives4. Minus only works on numbers, so the string"5"becomes the number 5."5" * "2"gives10, for the same reason.true + 1gives2, becausetruebecomes 1 andfalsebecomes 0.==(loose equality) converts types before comparing, so"0" == 0and"" == 0are bothtrue.===(strict equality) compares type and value with no conversion, so"0" === 0isfalse.null == undefinedistrueandnull === undefinedisfalse.
Use === and !== everywhere. Then a comparison means what it looks like it means, and you convert types yourself when you need to, which is the next step.
Check it worked
The output is 51, 4, 10, 2, then true, false, true, true, false, one per line. Count how many you predicted correctly; the + and == lines are the ones to remember.
Step 7 · Convert text input to numbers safely
Everything a person types arrives as a string: a value from a web form, from a prompt or from the command line. Before you add it up, convert it with Number(), and check the result with Number.isNaN(). NaN means "not a number"; it is what Number() returns when the text is not a valid number. This script takes amounts from the command line, which arrive as strings just like form fields:
cd ~/js-variables-demo
cat > amount.js <<'JS'
function toAmount(text) {
const trimmed = text.trim();
if (trimmed === "") {
return { ok: false, reason: "is empty" };
}
const value = Number(trimmed);
if (Number.isNaN(value)) {
return { ok: false, reason: "is not a number" };
}
if (!Number.isFinite(value)) {
return { ok: false, reason: "is not a finite number" };
}
if (value < 0) {
return { ok: false, reason: "is negative" };
}
return { ok: true, value };
}
const inputs = process.argv.slice(2);
let total = 0;
for (const input of inputs) {
const result = toAmount(input);
if (result.ok) {
total += result.value;
console.log(`accepted ${JSON.stringify(input)} as ${result.value}`);
} else {
console.log(`rejected ${JSON.stringify(input)}: it ${result.reason}`);
}
}
console.log(`total: ${total}`);
JS
node amount.js "1500" " 250.50 " "" "12abc" "1,000" "-40" "Infinity"Line by line:
function toAmount(text)takes one string and returns an object: either{ ok: true, value }or{ ok: false, reason }. Returning a result instead of printing inside the function keeps it reusable in a web page later.text.trim()removes spaces at both ends, which people often type by accident.- The empty check comes first because
Number("")returns0, notNaN. Without it, a blank field would quietly count as zero. Number(trimmed)converts the whole string or returnsNaN:Number("12abc")isNaN. CompareparseInt("12abc"), which reads digits until it stops and returns12, hiding the mistake. Be aware thatNumber()accepts more than plain decimals:"0x10"(hexadecimal) becomes 16,"1e6"(exponent notation) becomes 1000000 and"Infinity"becomesInfinity.Number.isNaN(value)istrueonly for the actualNaNvalue. Do not writevalue === NaN:NaNis the one value that is not equal to itself, so that test is alwaysfalse. The older globalisNaN()converts its argument first, which brings back the coercion from the last step.Number.isFinite(value)isfalseforInfinityand-Infinity. Those are valid numbers to JavaScript, so they pass theNaNcheck, but no one can pay an infinite amount, and one of them would turn the total intoInfinity. This script still accepts"0x10"and"1e6"; if your form should allow only digits and a decimal point, also test the trimmed text with a pattern such as/^\d+(\.\d+)?$/before converting it.process.argvis the list of command-line words;slice(2)skips the first two, which are the path tonodeand the path to the script.let total = 0isletbecausetotal += result.valuechanges it. Because every accepted value is a real number,+=adds instead of joining strings.JSON.stringify(input)prints each input in double quotes, so you can see spaces and empty strings.
"1,000" is rejected because Number() does not understand thousands separators. Many people type amounts that way, especially on a phone keyboard, and conventions differ by country: some write 1.000,50 or 1 000,50. Decide what your form accepts, tell the user, and strip or reject other formats on purpose rather than letting them turn into NaN further on.
Check it worked
The output is:
accepted "1500" as 1500
accepted " 250.50 " as 250.5
rejected "": it is empty
rejected "12abc": it is not a number
rejected "1,000": it is not a number
rejected "-40": it is negative
rejected "Infinity": it is not a finite number
total: 1750.5The total is 1750.5, a number, not "1500250.50", which is what + on the raw strings would have produced. Run it with your own amounts, such as node amount.js 20 abc 30, and check the total.
When you have finished, delete the demo folder:
cd ~
rm -rf ~/js-variables-demoNext steps
- Put many values in one variable and transform them: work with arrays in JavaScript: map, filter and reduce.
- See, in Python, why changing a list through one name changes it for every name: understand variable references and mutability.
- Compare how another language handles the same ideas: understand values and types in Python.
- If you skipped the setup, go back to Hello World in JavaScript to install Node.js 26.
Related tutorials
- Write your first class in Python: objects, attributes and methodsYou will model a library book loan as a Python class with attributes, methods, a readable __repr__ and a shared loan period, compare it with a dictionary version, rewrite it as a dataclass and end with a Loan class and a short script that uses it.
- Write your first JavaScript tests with the built-in Node.js test runnerYou will write a small price module in JavaScript, cover it with six passing tests using node:test and node:assert, and know how to read a failure and run one test on its own, with no packages installed.
- Write readable code: names, comments and a formatterYou will turn a working but cryptic Python script into a readable one with clear names, named constants, small functions and useful comments, tidy it with Ruff, prove its output has not changed and leave with your own style checklist.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials