Tutorials / JavaScript Fundamentals / Data types: numbers, strings, booleans, null and undefined

Data types: numbers, strings, booleans, null and undefined

13 min read javascript
Course contents (16 lessons)
  1. Getting started
  2. What is JavaScript and where does it run?
  3. Variables with let and const
  4. Values and operators
  5. Data types: numbers, strings, booleans, null and undefined
  6. Operators: arithmetic, comparison and logical
  7. Strings and template literals
  8. Making decisions and repeating work
  9. Conditionals: if, else and switch
  10. Loops: for, while and for...of
  11. Functions
  12. Functions: declarations, parameters and return values
  13. Arrow functions and callbacks
  14. Arrays and objects
  15. Arrays: creating, reading and changing lists
  16. Array methods: map, filter, find and reduce
  17. Objects: properties, methods and copying
  18. Scope and the browser
  19. Scope and closures, gently
  20. The DOM: selecting and changing elements
  21. Events: reacting to clicks, input and forms
  22. Final project
  23. Project: build a to-do list in the browser

Every value has a type

Each value in JavaScript has a type. The type decides what you can do with the value. You can multiply numbers, join strings and use booleans in conditions. The language has seven simple (primitive) types and one complex type, the object. In this lesson we cover the simple ones you will use daily.

TypeExampleUse
number42, 3.14, -7Any number, whole or decimal
string"hello", 'hi'Text
booleantrue, falseYes or no
undefinedundefinedA variable with no value yet
nullnullAn empty value you set on purpose
bigint9007199254740993nWhole numbers beyond the safe range
symbolSymbol("id")Unique keys (rarely needed at the start)

Checking a type with typeof

The typeof operator tells you the type of a value as a string.

console.log(typeof 42);          // "number"
console.log(typeof 3.14);        // "number"
console.log(typeof "hello");     // "string"
console.log(typeof true);        // "boolean"
console.log(typeof undefined);   // "undefined"
console.log(typeof null);        // "object"  (a famous old bug)
console.log(typeof [1, 2, 3]);   // "object"
console.log(typeof { a: 1 });    // "object"
console.log(typeof function () {}); // "function"

Most of these are what you expect. Two surprises. First, typeof null returns "object". That is a mistake from the first version of the language that nobody can fix now without breaking old websites. Just remember it. Second, arrays are also reported as "object". To check for an array, use Array.isArray(value).

Numbers

JavaScript has one number type for both whole numbers and decimals. There is no separate int and float.

const age = 30;
const price = 19.99;
console.log(age + price); // 49.99

There is one special number worth knowing about, NaN, which means "not a number". You get it when a calculation makes no sense:

console.log("abc" * 2);       // NaN
console.log(Number("12px"));  // NaN
console.log(Number("12"));    // 12
console.log(Number.isNaN(NaN)); // true

NaN is odd because NaN === NaN is false. To test for it, use Number.isNaN(value).

Decimal surprises

Computers store numbers in binary, and some decimals cannot be stored exactly:

console.log(0.1 + 0.2);            // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3);    // false
console.log((0.1 + 0.2).toFixed(2)); // "0.30"

This is not a JavaScript bug. Python, C# and Java behave the same way. When you work with money, I suggest storing the amount in the smallest unit, such as paisa or cents, as whole numbers, and only formatting it as a decimal for display. Use toFixed for showing a rounded value, but remember it returns a string.

Strings

A string is text inside quotes. Single and double quotes work the same:

const first = "Ghulam";
const city = 'Lahore';
console.log(first.length); // 6

We give strings a full lesson soon, including template literals.

Booleans

A boolean is true or false. You usually get one from a comparison such as age > 18, and use it in an if statement.

const isAdult = 20 >= 18;
console.log(isAdult); // true

undefined and null

Both mean "no value", but they come from different places.

  • undefined is what JavaScript gives you when something has not been set: a variable with no value, a missing object property, a function that returns nothing.
  • null is what you set yourself to say "there is deliberately nothing here".
let result;
console.log(result);        // undefined
result = null;
console.log(result);        // null

In practice, treat them both as "empty" and check for either one when you need to.

Converting between types

JavaScript converts types for you in some situations, which can surprise you. The explicit way is better.

console.log(Number("42") + 1);     // 43
console.log(String(42) + 1);       // "421"
console.log(Boolean(""));          // false
console.log(Boolean("text"));      // true
console.log(parseInt("42px"));     // 42
console.log(parseFloat("3.5kg"));  // 3.5

The values that become false when converted to a boolean are false, 0, "" (empty string), null, undefined and NaN. Everything else is true. These are called falsy values, and you will use that idea in the conditionals lesson.

Common mistakes

  • Forgetting that input is text. A value read from a form field is always a string. "5" + "3" gives "53", not 8. Convert with Number() first.
  • Comparing floating point results with ===. Use rounding or compare against a small tolerance.
  • Using typeof to detect null or arrays. It will not work. Use value === null and Array.isArray(value).
  • Mixing up null and undefined. Decide on a convention in your project and stick to it.

Try it yourself

  1. Predict the output of typeof "5", typeof 5, typeof "5" + 5, and then run them. Which result surprised you?
  2. Convert the string "150.75" to a number and add 10 to it.
  3. Work out what Boolean(0), Boolean("0") and Boolean([]) return. Check in the console.
  4. Calculate 0.1 * 3 and display it rounded to two decimals.
javascript
console.log(typeof 42);          // "number"
console.log(typeof 3.14);        // "number"
console.log(typeof "hello");     // "string"
console.log(typeof true);        // "boolean"
console.log(typeof undefined);   // "undefined"
console.log(typeof null);        // "object"  (a famous old bug)
console.log(typeof [1, 2, 3]);   // "object"
console.log(typeof { a: 1 });    // "object"
console.log(typeof function () {}); // "function"

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account