Data Types
What is a Data Type?β
Think of data types as different categories of information, like how a library organizes books into categories: Fiction, Non-Fiction, Children's Books, etc.
Real-World Analogy πβ
Imagine sorting items in your house:
π¦ Numbers: TV (55 inch), Age (25), Price ($299.99)
π Strings: Name ("Alice"), Address ("123 Main St")
β
Booleans: Light Switch (ON/OFF), Door (OPEN/CLOSED)
π Arrays: Shopping List ["milk", "bread", "eggs"]
π Objects: Contact Card {name: "John", phone: "555-1234"}
In JavaScript, data types categorize the different kinds of values you can store and work with.
Why Do Data Types Matter?β
- Different Operations: You can add numbers (
5 + 3 = 8) but not booleans - Memory Management: Different types use different amounts of memory
- Prevent Errors: Helps JavaScript understand what you're trying to do
- Better Code: Makes your intentions clear to other developers
// Numbers: Can do math
const a = 10;
const b = 5;
console.log(a + b); // 15 β
Makes sense
// Strings: Can join text
const firstName = "John";
const lastName = "Doe";
console.log(firstName + " " + lastName); // "John Doe" β
Makes sense
// Don't mix types carelessly!
console.log("5" + 3); // "53" π Confusing! (not 8)
JavaScript's Flexibility π¨β
Unlike strict languages (C++, Java), JavaScript is dynamically typedβit figures out the type automatically:
// In Java - you must declare types
int age = 25; // Must say "int"
String name = "Alice"; // Must say "String"
// In JavaScript - types are automatic!
const age = 25; // Automatically knows it's a number
const name = "Alice"; // Automatically knows it's a string
This flexibility is powerful but requires understanding how types work!
JavaScript Data Types Overview πΊοΈβ
JavaScript has 8 main data types that fall into two categories:
Primitive Types (Simple Values)β
Basic, immutable values stored directly:
- Number - All numbers:
42,3.14,-5 - String - Text:
"Hello",'World' - Boolean - True/False:
true,false - Undefined - Variable declared but no value:
undefined - Null - Intentionally empty:
null - Symbol - Unique identifiers (advanced)
- BigInt - Very large numbers (advanced)
Non-Primitive Types (Complex Values)β
Complex structures that can hold multiple values:
- Object - Collections of data:
{ name: "Alice", age: 25 }- Arrays:
[1, 2, 3] - Functions:
function() {} - Dates:
new Date() - And more!
- Arrays:
// Primitive examples
const age = 25; // Number
const name = "Alice"; // String
const isStudent = true; // Boolean
const score = undefined; // Undefined
const emptyValue = null; // Null
// Non-primitive examples
const person = { name: "Bob", age: 30 }; // Object
const colors = ["red", "blue", "green"]; // Array (type of Object)
const greet = function() { console.log("Hi"); }; // Function (type of Object)
Dynamic Typing in Actionβ
JavaScript automatically determines the type based on the value:
let x = 5; // x is a number
console.log(typeof x); // "number"
x = "John"; // Now x is a string
console.log(typeof x); // "string"
x = true; // Now x is a boolean
console.log(typeof x); // "boolean"
x = { name: "Alice" }; // Now x is an object
console.log(typeof x); // "object"
typeofUse the typeof operator to check what type a value is:
console.log(typeof 42); // "number"
console.log(typeof "Hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof { name: "Alice" }); // "object"
TypeScript adds static typing to JavaScript, requiring you to declare types:
let x: number = 5; // x must be a number
x = "John"; // β Error! Can't assign string to number
let name: string = "Alice"; // name must be a string
name = 123; // β Error! Can't assign number to string
TypeScript helps catch type errors before running the code!
Simple version:
- Primitive = Simple, single values (numbers, text, true/false)
- Non-Primitive = Complex structures that can hold multiple values (objects, arrays)
Want to learn more about the difference? Check out the advanced section later!
Detailed Data Typesβ
Now let's explore each data type in detail with practical examples:
Number:β
JavaScript does not have different types of numbers like integers, short, long, floating-point, etc. It only has one type of number, and you can use it to store:
- integers (like
42,-137, or11321) - floating-point values (like
3.14or0.07) - infinity (like
Infinityor-Infinity) - NaN (not a number)
- hexadecimal values (like
0xFFor0x89) - octal values (like
0o77or0o10) - binary values (like
0b11or0b1001) - and more
You may not need to know about hexadecimal, octal, and binary values right now. For now, you can think of them as different ways to represent numbers.
You can use arithmetic operators like +, -, *, /, or % to perform calculations with numbers.
const i = 42; // Integer
const f = 3.14; // Float
const z = i + f; // z will be 45.14
const inf = Infinity; // Special value representing infinity
const n = NaN; // Special value representing NaN
const h = 0xff; // Hexadecimal
const o = 0o77; // Octal
const b = 0b11; // Binary
NAN?A number can also be a special value called NaN (not a number). This value is returned by mathematical operations that can't be performed, such as undefined + 1, Infinity / Infinity (infinity divided by infinity), or 0 / 0 (zero divided by zero).
To check if a value is NaN, you must use the isNaN() function.
isNaN(NaN); // true
isNaN(42); // false
isNaN("Hello"); // true
Number Methodsβ
There are a few methods that number data types have. Let's take a look at them.
toString()β
toString() method converts a number to a string.
const x = 42;
const y = x.toString(); // y will be "42"
toFixed()β
Converts a number to a string, keeping a specified number of decimals.
const x = 42.123;
const y = x.toFixed(2); // y will be "42.12"
toExponential()β
Converts a number to a string in exponential notation.
const x = 42.123;
const y = x.toExponential(2); // y will be "4.21e+1"
toPrecision()β
Converts a number to a string in exponential notation, with a specified length.
const x = 42.123;
const y = x.toPrecision(2); // y will be "4.2e+1"
String:β
Strings are sequences of characters, and they can be defined using single quotes '', double quotes "", or backticks ``. Strings can contain letters, numbers, and special characters.
const name = "Rizwan";
const surname = "Ashiq";
const message = `Hello, World!`;
What is a Template Literal?β
A template literal is a string-defining method that allows embedded expressions. You can use multi-line strings and string interpolation features with them. They were called "template strings" in prior editions of the ES2015 specification.
const name = `Rizwan`;
const greeting = `Hello, ${name}!`; // greeting will be "Hello, Rizwan!"
const x = 10;
const y = 20;
const message = `The sum of x and y is ${x + y}.`; // message will be "The sum of x and y is 30."
const multiline = `This is a
multiline string.`; // multiline will be "This is a\nmultiline string."
String Concatenationβ
You can use the + operator to concatenate (join) two strings together. If you try to concatenate a number with a string, the number will be converted to a string.
const x = 42;
const y = "Hello";
const z = x + y; // z will be "42Hello"
And if you try to concatenate a string number with a regular number, then there will be no conversion. The result will be a string.
const x = "42";
const y = 10;
const z = x + y; // z will be "4210"
Interestingly if you try to subtract, multiply, or divide a string number from a regular number, then the result will be a number.
const x = "42";
const y = 10;
const a = x - y; // a will be 32
const b = x * y; // b will be 420
const c = x / y; // c will be 4.2
String Methods and Propertiesβ
There are many methods available for strings.
length propertyβ
Returns the length of a string.
const name = "Rizwan";
const length = name.length; // length will be 6
toUpperCase() methodβ
Converts a string to uppercase.
const name = "Rizwan";
const upper = name.toUpperCase(); // upper will be "RIZWAN"
toLowerCase() methodβ
Converts a string to lowercase.
const name = "Rizwan";
const lower = name.toLowerCase(); // lower will be "rizwan"
charAt() methodβ
Returns the character at a specific index in a string.
const name = "Rizwan";
const char = name.charAt(0); // char will be "R"
indexOf() methodβ
Returns the index of the first occurrence of a substring in a string.
const name = "Rizwan";
const index = name.indexOf("z"); // index will be 2
lastIndexOf() methodβ
Returns the index of the last occurrence of a substring in a string.
const name = "Rizzwan";
const index = name.lastIndexOf("z"); // index will be 3
startsWith() methodβ
Checks if a string starts with a specific substring.
const name = "Rizwan";
const startsWith = name.startsWith("Riz"); // startsWith will be true
endsWith() methodβ
Checks if a string ends with a specific substring.
const name = "Rizwan";
const endsWith = name.endsWith("wan"); // endsWith will be true
includes() methodβ
Checks if a string contains a specific substring.
const name = "Rizwan";
const includes = name.includes("izw"); // includes will be true
slice() methodβ
Extracts a part of a string
const name = "Rizwan";
const slice = name.slice(1, 4); // slice will be "izw"
const slice2 = name.slice(-3); // slice2 will be "wan"
The first argument is the starting index, and the second argument is the ending index. If the second argument is not provided, then the substring will be extracted from the starting index to the end of the string. If the first argument is negative, then the starting index will be calculated from the end of the string. If the second argument is negative, then the ending index will be calculated from the end of the string.
substring() methodβ
Extracts a part of a string between two specified indices.
const name = "Rizwan";
const substring = name.substring(1, 4); // substring will be "izw"
slice() and substring()The slice() method can take negative indices, and can take indices greater than the length of the string. The substring() method can't take negative indices, and can't take indices greater than the length of the string.
split() methodβ
Splits a string into an array of substrings using a specific separator.
const name = "Rizwan";
const split = name.split(""); // split will be ["R", "i", "z", "w", "a", "n"]
const split2 = name.split("z"); // split2 will be ["Ri", "wan"]
trim() methodβ
Removes whitespace from both ends of a string.
const name = " Rizwan ";
const trimmed = name.trim(); // trimmed will be "Rizwan"
repeat() methodβ
Repeats a string a specified number of times.
const name = "Rizwan";
const repeated = name.repeat(3); // repeated will be "RizwanRizwanRizwan"
Boolean:β
Booleans represent true or false values. They are often used in conjunction with conditional statements to determine the flow of a program. You can use comparison operators like ==, !=, >, <, >=, and <= to compare values and return a boolean result.
const u = true; // Boolean representing true
const v = false; // Boolean representing false
const x = 10;
const y = 20;
const isGreater = x > y; // isGreater will be false
const password = "password";
const isCorrect = password === "password"; // isCorrect will be true
Null:β
The null data type represents the absence of a value or a null reference. It is not the same as an empty string or a zero. You can assign the value null to a variable to indicate that it has no value.
const x = null; // Null value
console.log(x); // Output: null
Undefined:β
The undefined data type indicates that a variable has been declared, but it has not been assigned a value. If you try to access the value of a variable that has not been assigned a value, it will return undefined.
let x;
console.log(x); // Output: undefined
Undefined is also the default value of a variable that has been declared, but not assigned a value. You can assign the value undefined to a variable to indicate that it has no value.
let x = undefined;
console.log(x); // Output: undefined
null vs undefinedThe null and undefined data types are similar in that they both represent the absence of a value. However, they are different in the following ways:
nullis an assignment value. It can be assigned to a variable as a representation of no value i.e.let x = null.undefinedis a type itself (undefined) that is assigned to variables that have not been assigned a value i.e.let x;.
let x; // x is undefined
let y = null; // y is null
Object:β
The Object data type represents a complex data structure that can store a collection of key-value pairs. You can use objects to store data in a more organized and structured way. An object can store any type of data, including numbers, strings, booleans, arrays, and even other objects.
Here is an example of how you can create an object in JavaScript:
const person = {
name: "Rizwan Ashiq",
age: 30,
isPakistani: true,
education: ["BS Information Technology", "MS Computer Science"],
dob: {
day: 10,
month: 7,
year: 1996,
},
};
In this example, person is an object with five properties: name, age, isPakistani, education, and dob. Each property has a key (a string) and a value (a number, a string, a boolean, or could be another object). The keys and values are separated by a colon :, and the key-value pairs are separated by commas ,.
You can access the properties of an object using dot notation (variable.key) or square bracket notation (variable['key']). For example:
console.log(person.name); // Output: 'Rizwan Ashiq'
console.log(person["age"]); // Output: 30
console.log(person.education[1]); // Output: "MS Computer Science"
console.log(person.dob.year); // Output: 1996
You can also add, modify, or delete properties of an object using the assignment operator (=) or the delete operator. For example:
person.height = 180; // Adding a new property height with value 180
person.name = "Jane"; // Modifying an existing property name with value "Jane"
delete person.isMarried; // Deleting a property isMarried
Objects are a powerful and flexible data type in JavaScript, and they are used to store and manipulate data in many contexts. You will learn more about objects in the next chapters.
Arrayβ
The data type of the array is object. An array is used to store a list of values. An array can store any type of data, including numbers, strings, booleans, objects, and even other arrays.
Here is an example of how you can create an array in JavaScript:
const numbers = [1, 2, 3, 4, 5];
const words = ["one", "two", "three"];
const mixed = [1, "two", true, null, { name: "Rizwan" }, [1, 2, 3]];
In this example, numbers are an array of numbers, words are an array of strings, and mixed is an array of mixed data types.
You can access the elements of an array using their index, which is the position of the element in the array. Array indices are zero-based, which means that the first element of an array has an index of 0, the second element has an index of 1, and so on.
You can access an element of an array using square brackets and the index of the element. For example:
const numbers = [1, 2, 3, 4, 5];
const words = ["one", "two", "three"];
console.log(numbers[0]); // Output: 1
console.log(words[1]); // Output: 'two'
You can also use the length property of an array to find out how many elements it has. For example:
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.length); // Output: 5
Complete example:
const numbers = [1, 2, 3, 4, 5];
// Accessing an element of the array using its index
console.log(numbers[0]); // Output: 1
// Modifying an element of the array using its index
numbers[0] = 10;
console.log(numbers[0]); // Output: 10
// Adding a new element to the array
numbers[5] = 6;
console.log(numbers); // Output: [10, 2, 3, 4, 5, 6]
// Finding the length of the array
console.log(numbers.length); // Output: 6
Arrays are a powerful and versatile data type in JavaScript, and they are used to store and manipulate data in many contexts. You will learn more about arrays in the next chapters.
Array constructor vs array literalβ
The array constructor is rarely used in modern JavaScript. It is better to use the array literal syntax to create an array.
const numbers = new Array(1, 2, 3, 4, 5); // Array constructor
const words = ["one", "two", "three"]; // Array literal
console.log(numbers); // Output: [1, 2, 3, 4, 5]
console.log(words); // Output: ["one", "two", "three"]
console.log(numbers.length); // Output: 5
console.log(words.length); // Output: 3
console.log(numbers[0]); // Output: 1
console.log(words[1]); // Output: "two"
numbers[0] = 10;
words[1] = "TWO";
Why array constructor is rarely used?
The array constructor is rarely used because it is not very flexible. It is better to use the array literal syntax to create an array. The array literal syntax is more concise and easier to read. It is also more flexible because you can use expressions to initialize the array elements.
const numbers = [1, 2, 3, 4, 5];
const words = ["one", "two", "three"];
const mixed = [1, "two", true, null];
const empty = [];
So, it is totally up to you which syntax you want to use to create an array. You can use the array constructor or the array literal syntax. Both are valid and work the same way. But, the array literal syntax is more commonly used. So, it is better to use the array literal syntax to create an array.
Function:β
Function is a data type that represents a block of code that can be executed. Functions are used to perform a specific task, and they are often used to perform the same task multiple times.
Here is an example of how you can create a function in JavaScript:
function add(a, b) {
return a + b;
}
In this example, add is a function that takes two parameters, a and b, and returns the sum of a and b.
You can call a function by using the function name followed by parentheses. For example:
add(1, 2); // Output: 3
You can also assign a function to a variable. For example:
const add = function (a, b) {
return a + b;
};
In this example, add is a variable that stores a function. You can call the function by using the variable name followed by parentheses. For example:
add(1, 2); // Output: 3
Functions are a powerful and versatile data type in JavaScript, and they are used to perform a specific task in many contexts. You will learn more about functions in the next chapters.
Symbol:β
Represents a unique and immutable identifier. Symbols are used to create unique object keys, and they are often used to ensure that object properties and methods do not conflict with each other.
Here is an example of how you can create a Symbol in JavaScript:
const symbol1 = Symbol();
const symbol2 = Symbol("some description");
In this example, symbol1 is a Symbol with no description, and symbol2 is a Symbol with the description 'some description'.
You can use Symbols as object keys to create unique properties that can't be accessed or modified using the usual dot notation or square bracket notation.
const person = {};
const nameKey = Symbol("name");
const ageKey = Symbol("age");
person[nameKey] = "Ali";
person[ageKey] = 30;
console.log(person[nameKey]); // Output: 'Ali'
console.log(person.name); // Output: undefined
Symbols are a relatively new data type in JavaScript, and they are not used as often as other data types like numbers, strings, and booleans. However, they can be very useful in certain situations, particularly when you need to create unique and immutable identifiers.
typeof operatorβ
The typeof operator is used to find the data type of value. It returns a string that represents the data type of the value.
Here is an example of how you can use the typeof operator:
console.log(typeof 1); // Output: 'number'
console.log(typeof "one"); // Output: 'string'
console.log(typeof true); // Output: 'boolean'
console.log(typeof null); // Output: 'object'
console.log(typeof undefined); // Output: 'undefined'
console.log(typeof Symbol()); // Output: 'symbol'
console.log(typeof function () {}); // Output: 'function'
In this example, the typeof operator is used to find the data type of different values.
typeof null returns 'object' instead of 'null'This is a well-known historical bug in JavaScript that was never fixed for backwards compatibility reasons. Use strict equality to check for null:
console.log(typeof null); // Output: 'object' β the bug
console.log(null === null); // Output: true β correct way to check
Note: typeof function(){} returning 'function' is not a bug β it is intentional and useful. Functions are a callable subtype of objects, and typeof correctly distinguishes them:
console.log(typeof function () {}); // Output: 'function' β by design
console.log(typeof {}); // Output: 'object'
instanceof operatorβ
The instanceof operator is used to check if an object is an instance of a constructor function. It returns true if the object is an instance of the constructor function, and it returns false if the object is not an instance of the constructor function.
Here is an example of how you can use the instanceof operator:
const numbers = [1, 2, 3, 4, 5];
const words = ["one", "two", "three"];
const person = { name: "Ali", age: 30 };
console.log(numbers instanceof Array); // Output: true
console.log(words instanceof Array); // Output: true
console.log(person instanceof Array); // Output: false
In this example, the instanceof operator is used to check if an object is an instance of the Array constructor function. The numbers and words objects are instances of the Array constructor function, and the person object is not an instance of the Array constructor function.
instanceof operator does not work with primitive valuesThe instanceof operator does not work with primitive values. It only works with objects.
console.log(1 instanceof Number); // Output: false
console.log("one" instanceof String); // Output: false
console.log(true instanceof Boolean); // Output: false
typeof and instanceof operatorsThe typeof operator is used to find the data type of a value, and the instanceof operator is used to check if an object is an instance of a constructor function.
console.log(typeof 1); // Output: 'number'
console.log(typeof "one"); // Output: 'string'
console.log(typeof true); // Output: 'boolean'
console.log(typeof null); // Output: 'object'
console.log(typeof undefined); // Output: 'undefined'
const numbers = [1, 2, 3, 4, 5];
const words = ["one", "two", "three"];
console.log(numbers instanceof Array); // Output: true
console.log(words instanceof Array); // Output: true