Learn / Programming / JavaScript / Variables and Types

Beginner 13 min

Variables and Types

let, const, primitive types, template strings and the equality traps.

What you will learn

  • Choose const or let
  • Name the primitive types
  • Use === not ==

You create variables with const and let. const means the name cannot be reassigned; let allows reassignment. A good habit: use const by default and switch to let only when the value must change. Avoid the old var; its scoping rules cause bugs.

const name = "Ada";
let count = 0;
count += 1;
// name = "Bob";   // TypeError: assignment to constant
console.log(name, count);
Output
Ada 1

The types

  • number: all numbers, integers and decimals alike (42, 3.14). Also NaN and Infinity.
  • string, boolean, undefined (declared but no value), null (deliberately empty), bigint and symbol.
  • object: everything else, including arrays and functions.
console.log(typeof 42, typeof "hi", typeof true);
console.log(typeof undefined, typeof null, typeof [], typeof {});
Output
number string boolean
undefined object object object
Known quirk

typeof null is "object". It is a decades-old bug that cannot be fixed without breaking the web. Use value === null to check for null and Array.isArray(x) for arrays.

Template strings

Backticks create template literals: embed any expression with ${...} and write multi-line text without escapes.

const items = 3, price = 4.5;
console.log(`${items} items cost $${(items * price).toFixed(2)}`);
Output
3 items cost $13.50

Equality: always use ===

== converts types before comparing, giving odd results. === compares value and type and behaves predictably.

console.log(0 == "0", 0 === "0");
console.log(null == undefined, null === undefined);
console.log(0.1 + 0.2 === 0.3);
Output
true false
true false
false

The last line is not a JavaScript quirk but floating-point math: decimals are stored in binary, so 0.1 + 0.2 is 0.30000000000000004. Compare money in whole cents.

Truthy and falsy

In a condition, these are false: false, 0, "", null, undefined, NaN. Everything else, including "0" and [], is true. Use ?? to fall back only for null/undefined, and ?. to read nested values safely.

const user = { profile: null };
console.log(user.profile?.email ?? "no email");
Output
no email

Try it yourself

Convert the string "42" to a number, add 8, and print a message using a template string. Then check whether NaN === NaN and explain the result.

Show solution
const n = Number("42") + 8;
console.log(`The answer is ${n}`);
console.log(NaN === NaN);          // false: NaN is never equal to anything
console.log(Number.isNaN(NaN));    // true: the correct check