Understand var, let, and const, and explore JavaScript's primitive data types including strings, numbers, booleans, null, and undefined.
Variables are containers that store data values. JavaScript provides three keywords for declaring variables:
const — Declares a constant. The value cannot be reassigned after initialization. Use this by default.
const PI = 3.14159;
const name = 'Alice';let — Declares a variable that can be reassigned. Use this when the value needs to change.
let score = 0;
score = 10; // This is allowedvar — The legacy way to declare variables. It is function-scoped rather than block-scoped, which can lead to confusing bugs. Avoid var in modern JavaScript.
var oldWay = 'avoid this';Best practice: Always prefer const. Only use let when you know the value will need to change. Never use var in new code.
JavaScript has seven primitive data types:
| Type | Example | Description |
|---|---|---|
| string | 'hello', "world" | Text enclosed in quotes |
| number | 42, 3.14, -7 | Integers and floating-point numbers |
| boolean | true, false | Logical true or false |
| null | null | Intentional absence of a value |
| undefined | undefined | Variable declared but not assigned |
| symbol | Symbol('id') | Unique identifier (advanced) |
| bigint | 9007199254740991n | Arbitrarily large integers (advanced) |
You can check a value's type using the typeof operator:
typeof 'hello' // 'string'
typeof 42 // 'number'
typeof true // 'boolean'
typeof undefined // 'undefined'
typeof null // 'object' (a known JS quirk!)<div id="output"></div>
<script>
const greeting = "Hello";
const year = 2024;
const isLearning = true;
let score;
const output = document.getElementById('output');
output.innerHTML = `
<p>greeting: ${greeting} (${typeof greeting})</p>
<p>year: ${year} (${typeof year})</p>
<p>isLearning: ${isLearning} (${typeof isLearning})</p>
<p>score: ${score} (${typeof score})</p>
`;
</script>JavaScript is dynamically typed, meaning variables can hold any type and types can change. JavaScript also performs implicit type coercion — it automatically converts values from one type to another in certain situations. This can produce surprising results:
'5' + 3 // '53' (number 3 is coerced to string, then concatenated)
'5' - 3 // 2 (string '5' is coerced to number, then subtracted)
'5' * 2 // 10 (string '5' is coerced to number)
true + 1 // 2 (true is coerced to 1)To avoid coercion bugs, always use strict equality (===) instead of loose equality (==):
5 == '5' // true (loose: coerces types before comparing)
5 === '5' // false (strict: different types are never equal)Rule of thumb: Always use === and !==. The loose operators == and != introduce subtle bugs that are hard to track down.
What is the result of typeof null?