Skip to main content

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:

Bash
node

The prompt changes to >. Type these lines one at a time, pressing Enter after each:

JavaScript
const city = "Lagos"
city
city = "Accra"
let visits = 1
visits = visits + 1
typeof city

Here is what each line does:

  • const city = "Lagos" creates a variable called city and points it at the string "Lagos". The REPL prints undefined, because a declaration itself has no value to show.
  • city on its own asks for the value, and the REPL prints 'Lagos'. The quotes tell you it is a string.
  • city = "Accra" tries to point city at a new value. const forbids that, so you get an error.
  • let visits = 1 creates a variable that is allowed to change.
  • visits = visits + 1 reads the current value, adds one and stores the result back in visits. The REPL prints 2.
  • typeof city asks what type of value city holds. 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:

Bash
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.js

Line 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 be let, because the next two lines change it.
  • itemsInBasket += 2; is shorthand for itemsInBasket = 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 though prices is const.

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:

Text
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:

Bash
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.js

What happens, in order:

  • Inside the if block, price is visible because it was declared outside, in the enclosing scope. discount and note are visible because they were declared in the same block.
  • After the block, discount no longer exists. typeof discount prints undefined instead of crashing, because typeof is the one operator that accepts a name that was never declared.
  • var leaked is 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 sets early, and prints undefined with no warning. JavaScript creates every var at the start of its function or file (this is called hoisting) and fills it in later.
  • Reading notYet before its let line throws a ReferenceError. let and const are hoisted too, but reading them early is an error rather than a silent undefined. The try/catch catches 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:

Text
900 discount applied
undefined
var ignores the block
undefined
ReferenceError: Cannot access 'notYet' before initialization

Step 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:

Bash
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.js

How it works:

  • examples is 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. const is fine here because each pass of the loop gets a fresh label and value.
  • label.padEnd(10) adds spaces to the label so the second column lines up.
  • let notSetYet; declares a variable without a value. Its value is undefined, which means "nothing has been put here yet". null is different: it is a value you assign on purpose to mean "empty".
  • number is the type for both whole numbers and decimals. It stores them as 64-bit floating point, so whole numbers are exact only up to Number.MAX_SAFE_INTEGER (9,007,199,254,740,991). Past that, adding 2 gives the wrong answer.
  • A number with n on the end is a bigint, which stays exact at any size. You cannot mix it with ordinary numbers in one sum without converting first.
  • 0.1 + 0.2 shows 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:

Bash
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.js
  • withPlus joins five pieces with +. It works, but the spaces around each piece are easy to get wrong.
  • withTemplate writes the sentence as it reads. ${items * pricePerItem} is worked out first, then turned into text.
  • The last console.log shows 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:

Text
Hello Amara, you have 3 items.
Hello Amara, you have 3 items costing 1350.
Two lines:
second line

If 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:

Bash
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.js

The reasons:

  • "5" + 1 gives 51. If either side of + is a string, + joins text, so the number 1 becomes the string "1".
  • "5" - 1 gives 4. Minus only works on numbers, so the string "5" becomes the number 5.
  • "5" * "2" gives 10, for the same reason.
  • true + 1 gives 2, because true becomes 1 and false becomes 0.
  • == (loose equality) converts types before comparing, so "0" == 0 and "" == 0 are both true.
  • === (strict equality) compares type and value with no conversion, so "0" === 0 is false.
  • null == undefined is true and null === undefined is false.

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:

Bash
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("") returns 0, not NaN. Without it, a blank field would quietly count as zero.
  • Number(trimmed) converts the whole string or returns NaN: Number("12abc") is NaN. Compare parseInt("12abc"), which reads digits until it stops and returns 12, hiding the mistake. Be aware that Number() accepts more than plain decimals: "0x10" (hexadecimal) becomes 16, "1e6" (exponent notation) becomes 1000000 and "Infinity" becomes Infinity.
  • Number.isNaN(value) is true only for the actual NaN value. Do not write value === NaN: NaN is the one value that is not equal to itself, so that test is always false. The older global isNaN() converts its argument first, which brings back the coercion from the last step.
  • Number.isFinite(value) is false for Infinity and -Infinity. Those are valid numbers to JavaScript, so they pass the NaN check, but no one can pay an infinite amount, and one of them would turn the total into Infinity. 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.argv is the list of command-line words; slice(2) skips the first two, which are the path to node and the path to the script.
  • let total = 0 is let because total += result.value changes 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:

Text
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.5

The 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:

Bash
cd ~
rm -rf ~/js-variables-demo

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.