A variable is a named place to keep a value so you can use it later. In modern JavaScript you create variables with let and const. Every value has a data type, such as number, string or boolean, and JavaScript works out the type by itself while the program runs. This lesson shows how to declare variables, what the types are and how JavaScript converts between them.
In this lesson you will learn
- The difference between
let,constandvar - JavaScript’s primitive data types
- Checking a type with
typeof - Template literals for building strings
- Type conversion and its surprises
Declaring Variables
let score = 10; // can be reassigned
score = score + 5;
const pi = 3.14159; // cannot be reassigned
// pi = 3; // TypeError: Assignment to constant variable.
let city = "Dhaka";
let isOpen = true;
let nothing = null;
let notSet; // declared but not assigned
console.log(score, pi, city, isOpen, nothing, notSet);
Output
15 3.14159 Dhaka true null undefined
letcreates a variable you can change later.constcreates one that cannot be reassigned. Use it by default and switch toletonly when the value must change.- A variable declared without a value holds
undefined.nullis a value you assign on purpose to mean “nothing here”. varis the old keyword. It ignores block scope and allows confusing re-declaration, so modern code avoids it.
Naming rules: names may contain letters, digits, _ and $, cannot start with a digit and cannot be keywords such as let or class. The usual style is camelCase: totalPrice, isLoggedIn.
Data Types and typeof
console.log(typeof 42); // number
console.log(typeof 4.5); // number (no separate float type)
console.log(typeof "hi"); // string
console.log(typeof true); // boolean
console.log(typeof undefined); // undefined
console.log(typeof null); // object (a famous old quirk)
console.log(typeof 10n); // bigint
console.log(typeof [1, 2]); // object
console.log(typeof { a: 1 }); // object
console.log(typeof function () {}); // function
const user = "Nadia";
const age = 21;
console.log(`${user} is ${age} years old and will be ${age + 1} next year.`);
Output
number
number
string
boolean
undefined
object
bigint
object
object
function
Nadia is 21 years old and will be 22 next year.
| Type | Examples | Notes |
|---|---|---|
| number | 42, -3.5, NaN, Infinity | One type for whole and decimal numbers |
| string | "hi", 'hi', `hi` | Text, in single, double or back quotes |
| boolean | true, false | Yes/no values |
| undefined | undefined | No value has been assigned |
| null | null | Deliberately empty |
| bigint | 10n | Whole numbers of any size |
| symbol | Symbol("id") | Unique identifiers (advanced) |
| object | {}, [], functions | Everything that is not one of the primitives above |
typeof nullgives"object". This is a bug from JavaScript’s first version that can never be fixed without breaking old websites.- Arrays are objects, so
typeofcannot tell them apart. UseArray.isArray(value)instead. - Template literals use back quotes and
${...}to place values, even whole expressions, inside a string.
Type Conversion
console.log("5" + 2); // string joining wins
console.log("5" - 2); // minus converts to number
console.log(Number("42") + 1);
console.log(Number("abc")); // not a number
console.log(String(99) + "!");
console.log(parseInt("120px"), parseFloat("3.5kg"));
console.log(0.1 + 0.2);
Output
52
3
43
NaN
99!
120 3.5
0.30000000000000004
- If either side of
+is a string, JavaScript joins text:"5" + 2is"52". The other arithmetic operators convert to numbers, so"5" - 2is3. Number()converts a whole string; it returnsNaN(“not a number”) when it cannot.parseInt()andparseFloat()read digits from the start and stop at the first character that does not fit.0.1 + 0.2is not exactly0.3because computers store decimals in binary. Round for display withtoFixed(2).
Common Mistakes
- Adding numbers read from inputs: form values are strings, so
"10" + "5"is"105". Convert withNumber()first. - Reassigning a
const, which throws a TypeError. - Using a variable before declaring it with
letorconst, which throws a ReferenceError. - Testing for NaN with
===:NaN === NaNis false. UseNumber.isNaN(x).
Practice Exercises
Exercise 1. Store a product name and price, then print “Pen costs 20 taka” using a template literal.
Show answer
const product = "Pen";
const price = 20;
console.log(`${product} costs ${price} taka`);
Exercise 2. What does "3" * "4" give, and why?
Show answer
12. The * operator only works on numbers, so both strings are converted to numbers first.
Frequently Asked Questions
Can a const object be changed?
Its contents can. const stops the variable from pointing to a different value, but the properties of an object or the items of an array it holds can still be modified.
What is the difference between null and undefined?
undefined means a value was never set; JavaScript uses it automatically. null is set by the programmer to say a value is intentionally empty.
Summary
- Use
constby default,letwhen the value changes, and avoidvar. - Primitives are number, string, boolean, undefined, null, bigint and symbol; everything else is an object.
typeofreports a value’s type, with thenullquirk.+joins strings when either side is text; convert input withNumber().
Next: JavaScript Operators.
