# Data Types

Course: [JavaScript](https://www.devtutorials.ai/learn/javascript) · Section: Basics
Source: https://www.devtutorials.ai/learn/javascript/basics/data-types

> 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.

- `349` is a **number**.
- `"Lunch box"` is a **string** (text).
- `true` is 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`.

<figure className="ts-fig">
  <svg viewBox="0 0 560 170" role="img" aria-label="Three labelled boxes. A number box holds 349, a string box holds Lunch box, a boolean box holds true. A value drops into each box." width="100%">
    <rect x="0" y="0" width="560" height="170" rx="12" fill="#f8fafc" stroke="#e2e8f0" />
    <rect x="30" y="70" width="150" height="70" rx="8" fill="#eff6ff" stroke="#2563eb" />
    <text x="105" y="160" textAnchor="middle" fontSize="12" fill="#1e40af">number: price</text>
    <rect x="205" y="70" width="150" height="70" rx="8" fill="#f0fdf4" stroke="#16a34a" />
    <text x="280" y="160" textAnchor="middle" fontSize="12" fill="#166534">string: name</text>
    <rect x="380" y="70" width="150" height="70" rx="8" fill="#fefce8" stroke="#ca8a04" />
    <text x="455" y="160" textAnchor="middle" fontSize="12" fill="#854d0e">boolean: inStock</text>
    <text x="105" y="40" textAnchor="middle" fontSize="16" fontFamily="monospace" fill="#1e40af">349<animate attributeName="y" values="30;110;110" keyTimes="0;0.4;1" dur="3s" repeatCount="indefinite" /></text>
    <text x="280" y="40" textAnchor="middle" fontSize="15" fontFamily="monospace" fill="#166534">"Lunch box"<animate attributeName="y" values="30;110;110" keyTimes="0;0.4;1" dur="3s" begin="0.3s" repeatCount="indefinite" /></text>
    <text x="455" y="40" textAnchor="middle" fontSize="16" fontFamily="monospace" fill="#854d0e">true<animate attributeName="y" values="30;110;110" keyTimes="0;0.4;1" dur="3s" begin="0.6s" repeatCount="indefinite" /></text>
  </svg>
  <figcaption>Each variable is a named box. The value inside has a type.</figcaption>
</figure>

Some boxes fail on purpose to show an error. Their title says so.

## What You Will Learn

1. How to make variables with `const`, `let` and `var`.
2. The seven primitive types.
3. Objects, arrays and functions.
4. How JavaScript changes types by itself (coercion).
5. How you change types on purpose (conversion).

## Introduction to Variables and Data Types

```js runnable title="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:

```text
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.

```js runnable expect-error title="Giving a const a new value is an error"
const shopName = "ShopEasy";
shopName = "ShopFast";
```

### `let`

Use `let` when the value must change.

```js runnable title="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:

```text
Start: 0
After two items: 370
```

### `var`

`var` is the old keyword. It leaks out of `{ }` blocks; `let` stays inside.

```js runnable title="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:

```text
visible outside
undefined
```

## Primitive Data Types

**Primitive** = a single, simple value. JavaScript has seven.

### Number

Whole numbers, decimals and negatives are all one type.

```js runnable title="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:

```text
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).

```js runnable title="Infinity and NaN are numbers too"
console.log(10 / 0, -10 / 0);
console.log("apple" * 2);
console.log(typeof NaN);
```

Expected output:

```text
Infinity -Infinity
NaN
number
```

### String

Text inside `"double"`, `'single'` or `` `backtick` `` quotes.
Backticks let you put a value inside with `${ }`.

```js runnable title="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:

```text
Asha bought a lunch box for ₹349
```

### Boolean

Only two values: `true` and `false`. Comparisons give booleans.

```js runnable title="A comparison produces a boolean"
const stock = 4;
const canBuy = stock > 0;
console.log(canBuy, typeof canBuy);
```

Expected output:

```text
true boolean
```

### Undefined

`undefined` = no value was given yet.

```js runnable title="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:

```text
undefined
undefined
```

### Null

`null` = "empty on purpose". You set it yourself.

```js runnable title="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:

```text
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.

```js runnable title="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:

```text
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.

```js runnable title="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:

```text
9007199254740991
9007199254740992
9007199254740993n
bigint
```

## Non-Primitive Data Types

These hold **many** values, or code.

### Object

Named values grouped together, as `key: value` pairs.

```js runnable title="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:

```text
Lunch box 349
object
```

### Array

An ordered list. Positions start at `0`.

```js runnable title="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:

```text
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.

```js runnable title="A function stored in a variable, then called"
const addTax = (price) => price * 1.18;
console.log(addTax(100));
console.log(typeof addTax);
```

Expected output:

```text
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()` or `Boolean()`.

## Implicit Type Conversion (Coercion)

### String with Number (Concatenation)

If either side of `+` is a string, `+` **joins**. Other maths signs turn text into numbers.

```js runnable title="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:

```text
370
250120
130
10
```

`+` works left to right, so order matters:

```js runnable title="The order matters, because + works from left to right"
console.log(1 + 2 + "3");
console.log("1" + 2 + 3);
```

Expected output:

```text
33
123
```

### Boolean to Number

In maths, `true` is `1` and `false` is `0`.

```js runnable title="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:

```text
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 `[]`.

```js runnable title="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:

```text
Cart is empty
```

`||` uses this rule to pick a fallback:

```js runnable title="|| picks a fallback when the first value is falsy"
const typedName = "";
const displayName = typedName || "Guest";
console.log(displayName);
```

Expected output:

```text
Guest
```

## Explicit Type Conversion

### Converting to String

```js runnable title="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:

```text
349 string
true
99.50
```

- `toFixed(2)` gives text with two decimals. Good for prices.
- `value.toString()` also gives text, but `null` and `undefined` have no methods, so use `String()` for them.

### Converting to Number

```js runnable title="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:

```text
42
NaN
42
3.75
```

- `Number()` needs clean text. Anything extra gives `NaN` (Not a Number).
- `parseInt()` and `parseFloat()` read the number at the start and stop.

```js runnable title="Fixing a price that arrived as text"
const priceText = "249";
const quantity = 2;
console.log(priceText * quantity);
console.log(Number(priceText) + 50);
```

Expected output:

```text
498
299
```

### Converting to Boolean

`Boolean()` uses the same truthy and falsy rules.

```js runnable title="Boolean() applies the truthy and falsy rules"
console.log(Boolean(0), Boolean(""), Boolean(null));
console.log(Boolean(5), Boolean("0"), Boolean([]));
```

Expected output:

```text
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.

```js runnable preview="price-card" title="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 `const` by default, `let` when the value changes, and avoid `var`.
- Primitives: number, string, boolean, undefined, null, symbol, bigint.
- Objects, arrays and functions hold many values or code.
- `"5" + 3` is `"53"`, but `"5" - 3` is `2`.
- 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

<div className="tscroll">

| 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` |

</div>

## Exercises

## What to Remember

- A variable is a named box; the type is the kind of value inside.
- `const` first, `let` when it must change.
- Text from a page is a string. Convert it before maths.

Next: **Operators**. Do maths, compare values and combine conditions.
