Data Types in JavaScript
By Syncfusion®, Inc. · Last updated
Declaring variables with var, let and const, the seven primitive types and the non-primitive object, array and function, and how implicit and explicit type conversion work.
What Is a Data Type?
Variable = a named box that holds a value. Data type = the kind of value in the box.
349is a number."Lunch box"is a string (text).trueis a boolean (yes or no).
Simple lesson: the type decides what you can do with a value. You add numbers, but you join strings.
A Real-World Example
A shop form sends the quantity as the text "2", not the number 2.
The code does "2" + 1 and the cart shows 21 items.
Turning the text into a number first, Number("2") + 1, gives 3.
number: price
string: name
boolean: inStock 349 "Lunch box" true
Each variable is a named box. The value inside has a type.
Some boxes fail on purpose to show an error. Their title says so.
What You Will Learn
- How to make variables with
const,letandvar. - The seven primitive types.
- Objects, arrays and functions.
- How JavaScript changes types by itself (coercion).
- How you change types on purpose (conversion).
Introduction to Variables and Data Types
Three variables, three different types of value
const productName = "Lunch box";
const price = 349;
const inStock = true;
console.log(productName, price, inStock);
console.log(typeof productName, typeof price, typeof inStock);
Expected output:
Lunch box 349 true
string number boolean
typeof tells you the type of any value.
Declaring Variables - var, let, const
| Keyword | Can change? | Use it for |
|---|---|---|
const | No | Most values. Start here. |
let | Yes | Values that change, like a running total |
var | Yes | Old code only |
const
A const keeps its first value. Giving it a new one is an error.
Giving a const a new value is an error
const shopName = "ShopEasy";
shopName = "ShopFast";
let
Use let when the value must change.
A let variable updated as items are added
let cartTotal = 0;
console.log("Start:", cartTotal);
cartTotal = cartTotal + 250;
cartTotal = cartTotal + 120;
console.log("After two items:", cartTotal);
Expected output:
Start: 0
After two items: 370
var
var is the old keyword. It leaks out of { } blocks; let stays inside.
var escapes the block, let stays inside it
if (true) {
var oldStyle = "visible outside";
let newStyle = "only inside";
}
console.log(oldStyle);
console.log(typeof newStyle);
Expected output:
visible outside
undefined
Primitive Data Types
Primitive = a single, simple value. JavaScript has seven.
Number
Whole numbers, decimals and negatives are all one type.
Whole numbers, decimals and negatives are all numbers
const quantity = 3;
const price = 49.5;
const refund = -20;
console.log(quantity * price, typeof price, typeof refund);
Expected output:
148.5 number number
Numbers also have special values: Infinity and -Infinity (dividing by zero), and NaN ("Not a Number", from maths that makes no sense).
Infinity and NaN are numbers too
console.log(10 / 0, -10 / 0);
console.log("apple" * 2);
console.log(typeof NaN);
Expected output:
Infinity -Infinity
NaN
number
String
Text inside "double", 'single' or `backtick` quotes.
Backticks let you put a value inside with ${ }.
Three kinds of quotes, and a value placed inside text
const first = "Asha";
const item = 'lunch box';
const total = 349;
console.log(`${first} bought a ${item} for ₹${total}`);
Expected output:
Asha bought a lunch box for ₹349
Boolean
Only two values: true and false. Comparisons give booleans.
A comparison produces a boolean
const stock = 4;
const canBuy = stock > 0;
console.log(canBuy, typeof canBuy);
Expected output:
true boolean
Undefined
undefined = no value was given yet.
A variable with no value, and a property that does not exist
let coupon;
const product = { name: "Pen" };
console.log(coupon);
console.log(product.price);
Expected output:
undefined
undefined
Null
null = "empty on purpose". You set it yourself.
null is set deliberately, and typeof has a famous quirk
let selectedAddress = null;
console.log(selectedAddress);
console.log(typeof selectedAddress);
console.log(selectedAddress === null);
Expected output:
null
object
true
typeof null says "object". It is an old bug. Check with === null instead.
Symbol
A symbol is a value that is always unique, even with the same label.
Two symbols with the same description are still different
const idA = Symbol("id");
const idB = Symbol("id");
console.log(idA === idB);
console.log(typeof idA);
Expected output:
false
symbol
BigInt
Normal numbers are exact only up to Number.MAX_SAFE_INTEGER (about 9 quadrillion). A BigInt (ends in n) has no limit.
A normal number loses accuracy, and a BigInt does not
console.log(Number.MAX_SAFE_INTEGER);
console.log(9007199254740993);
console.log(9007199254740993n);
console.log(typeof 10n);
Expected output:
9007199254740991
9007199254740992
9007199254740993n
bigint
Non-Primitive Data Types
These hold many values, or code.
Object
Named values grouped together, as key: value pairs.
One object holds several related values
const product = { name: "Lunch box", price: 349, inStock: true };
console.log(product.name, product.price);
console.log(typeof product);
Expected output:
Lunch box 349
object
Array
An ordered list. Positions start at 0.
A list of product names, read by position
const cart = ["Pen", "Notebook", "Lunch box"];
console.log(cart[0], cart.length);
console.log(Array.isArray(cart), typeof cart);
Expected output:
Pen 3
true object
typeof says "object" for arrays. Use Array.isArray() to check.
Function
Code stored in a name, run when you call it.
A function stored in a variable, then called
const addTax = (price) => price * 1.18;
console.log(addTax(100));
console.log(typeof addTax);
Expected output:
118
function
Introduction to Type Conversion in JavaScript
- Implicit conversion (coercion) = JavaScript changes the type by itself.
- Explicit conversion = you change it on purpose, with
Number(),String()orBoolean().
Implicit Type Conversion (Coercion)
String with Number (Concatenation)
If either side of + is a string, + joins. Other maths signs turn text into numbers.
The same + adds numbers and joins text
console.log(250 + 120);
console.log("250" + 120);
console.log("250" - 120);
console.log("5" * "2");
Expected output:
370
250120
130
10
+ works left to right, so order matters:
The order matters, because + works from left to right
console.log(1 + 2 + "3");
console.log("1" + 2 + 3);
Expected output:
33
123
Boolean to Number
In maths, true is 1 and false is 0.
true counts as 1, and false counts as 0
const gift = true;
const express = false;
console.log(gift + express);
console.log(true + true + true);
Expected output:
1
3
Automatic Conversion in Logical Operations
if turns any value into true or false.
- Falsy:
false,0,"",null,undefined,NaN. - Truthy: everything else, even
"0"and[].
An if statement converts the value to true or false
const itemsInCart = 0;
if (itemsInCart) {
console.log("Show checkout button");
} else {
console.log("Cart is empty");
}
Expected output:
Cart is empty
|| uses this rule to pick a fallback:
|| picks a fallback when the first value is falsy
const typedName = "";
const displayName = typedName || "Guest";
console.log(displayName);
Expected output:
Guest
Explicit Type Conversion
Converting to String
Numbers, booleans and null turned into text
console.log(String(349), typeof String(349));
console.log(String(true));
console.log((99.5).toFixed(2));
Expected output:
349 string
true
99.50
toFixed(2)gives text with two decimals. Good for prices.value.toString()also gives text, butnullandundefinedhave no methods, so useString()for them.
Converting to Number
Three ways to turn text into a number
console.log(Number("42"));
console.log(Number("42px"));
console.log(parseInt("42px", 10));
console.log(parseFloat("3.75 kg"));
Expected output:
42
NaN
42
3.75
Number()needs clean text. Anything extra givesNaN(Not a Number).parseInt()andparseFloat()read the number at the start and stop.
Fixing a price that arrived as text
const priceText = "249";
const quantity = 2;
console.log(priceText * quantity);
console.log(Number(priceText) + 50);
Expected output:
498
299
Converting to Boolean
Boolean() uses the same truthy and falsy rules.
Boolean() applies the truthy and falsy rules
console.log(Boolean(0), Boolean(""), Boolean(null));
console.log(Boolean(5), Boolean("0"), Boolean([]));
Expected output:
false false false
true true true
Data Types on a Web Page
Everything you read from a page is a string, even a number in an input box. Fill the card with values of each type.
Showing a number, a string and a boolean on a product card
const name = "Lunch box";
const price = 349;
const inStock = true;
document.querySelector("#name").textContent = name;
document.querySelector("#price").textContent = "₹" + price.toFixed(2);
document.querySelector("#stock").textContent = inStock ? "In stock" : "Sold out";
const shown = document.querySelector("#price").textContent;
console.log(typeof price, "->", typeof shown, shown);
The number 349 became the text ₹349.00 on the page. Change inStock to false and watch the card.
Easy way to remember: + with any text joins. To add, make both sides numbers first.
TL;DR
- Use
constby default,letwhen the value changes, and avoidvar. - Primitives: number, string, boolean, undefined, null, symbol, bigint.
- Objects, arrays and functions hold many values or code.
"5" + 3is"53", but"5" - 3is2.- Falsy:
false,0,"",null,undefined,NaN. All else is truthy.
Try this
Predict "10" + 5 - 2, then type it in any box. You get 100: "10" + 5 is "105", then - turns it into a number.
Check Yourself
Common mistakes
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
const total = 0; total = 5; | const can change later | const keeps its first value | TypeError: Assignment to constant variable. |
"249" + 50 | + always adds | + joins when one side is text | 24950 instead of 299 |
typeof value === "null" | typeof null is "null" | It is "object" | The check is never true |
if ([]) to test an empty list | Empty means falsy | [] is truthy | The empty branch never runs |
Number("42px") | It reads the 42 | It needs clean text | NaN |
Quick reference
| Syntax | Meaning |
|---|---|
const name = value; | declare a name that cannot be given a new value |
let name = value; | declare a name whose value can change |
var name = value; | the older way to declare, which ignores block braces |
typeof value | the type of a value, as a string such as "number" |
42, "Asha", true | a number, a string and a boolean |
undefined, null | no value yet, and no value on purpose |
Symbol("id"), 10n | a unique symbol, and a BigInt |
{ key: value }, [a, b] | an object and an array |
String(value) | change to text |
Number(value), parseInt(text, 10), parseFloat(text) | change to a number |
Boolean(value) | change to true or false |
Exercises
What to Remember
- A variable is a named box; the type is the kind of value inside.
constfirst,letwhen it must change.- Text from a page is a string. Convert it before maths.
Next: Operators. Do maths, compare values and combine conditions.