JavaScript Tutorial menu

JavaScript Data Types

Every value in JavaScript has a type, such as text, a number or true/false.

The Data Types

TypeExampleUsed for
String"Karachi"Text
Number42, 3.75Whole and decimal numbers
BigInt9007199254740993nVery large whole numbers
Booleantrue, falseYes or no values
UndefinedundefinedA variable with no value yet
Nullnull"Empty on purpose"
SymbolSymbol("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

javascript
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

javascript
let students = 35;
let petrolPrice = 272.89;
let big = 25e6;    // 25000000

Booleans

A boolean is either true or false. Comparisons create booleans.

Example

javascript
let isOpen = true;
let passed = 45 >= 50;   // false

Undefined and Null

A variable with no value is undefined. null means you have set it to "nothing" on purpose.

Example

javascript
let phone;          // undefined
let discount = null; // no discount for now

Checking the Type with typeof

Example

html
<!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 »
Output
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

javascript
let x = 10;       // number
x = "ten";        // now a string
x = false;        // now a boolean
console.log(typeof x);
Output
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

javascript
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?

Learn JavaScript with a teacher

Join the Web Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp