JavaScript Data Types
Every value in JavaScript has a type, such as text, a number or true/false.
The Data Types
| Type | Example | Used for |
|---|---|---|
| String | "Karachi" | Text |
| Number | 42, 3.75 | Whole and decimal numbers |
| BigInt | 9007199254740993n | Very large whole numbers |
| Boolean | true, false | Yes or no values |
| Undefined | undefined | A variable with no value yet |
| Null | null | "Empty on purpose" |
| Symbol | Symbol("id") | Unique keys (advanced) |
| Object | { name: "Ali" }, [1, 2, 3] | Groups of values |
The first seven are called primitive types. Objects (including arrays) can hold many values.
Strings
A string is text inside quotes. You can use double quotes, single quotes or backticks.
Example
let shop = "Saddar Mobile Centre";
let owner = 'Bilal';
let note = `Open till 10 PM`;Use one kind of quote inside the other: "It's open" works fine.
Numbers
JavaScript has one number type for both whole numbers and decimals.
Example
let students = 35;
let petrolPrice = 272.89;
let big = 25e6; // 25000000Booleans
A boolean is either true or false. Comparisons create booleans.
Example
let isOpen = true;
let passed = 45 >= 50; // falseUndefined and Null
A variable with no value is undefined. null means you have set it to "nothing" on purpose.
Example
let phone; // undefined
let discount = null; // no discount for nowChecking the Type with typeof
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
let results = [
typeof "Ayesha",
typeof 19,
typeof true,
typeof undefined,
typeof { city: "Karachi" },
typeof [10, 20]
];
document.getElementById("demo").innerHTML = results.join("<br>");
</script>
</body>
</html>Try it Yourself »string number boolean undefined object object
Notice that an array also shows "object". To check for an array, use Array.isArray(value).
typeof null gives "object". This is an old mistake in the language that can never be fixed without breaking websites. Just remember it.
Dynamic Types
In JavaScript, the same variable can hold different types at different times. This is called dynamic typing.
Example
let x = 10; // number
x = "ten"; // now a string
x = false; // now a boolean
console.log(typeof x);boolean
This is flexible but can cause mistakes. TypeScript adds fixed types on top of JavaScript to catch them.
Type Conversion
Values from input boxes are always strings. Convert them before doing maths:
Example
let a = "20";
let b = "30";
console.log(a + b); // "2030"
console.log(Number(a) + Number(b)); // 50
console.log(String(99)); // "99"Exercise
Exercise
What does typeof "45" return?
