Welcome to the JavaScript Data Types tutorial for beginners! This guide is designed to help you understand the different data types available in JavaScript. We’ll cover the basics, provide coding examples, and include quiz questions to test your understanding. By the end of this tutorial, you’ll have a solid foundation of JavaScript data types and how to use them effectively in your programs. Let’s get started!
Introduction to Data Types
In programming, data types specify the type of data that can be stored and manipulated within a program. JavaScript is a dynamically typed language, which means variables can hold values of any data type without strict type enforcement.
Understanding data types is essential because it helps you:
- Write more reliable and error-free code.
- Choose appropriate operations for different types of data.
- Debug and fix issues related to incorrect data usage.
Primitive Data Types
Primitive data types are the most basic data types in JavaScript. They are immutable, meaning their values cannot be changed once created.
JavaScript has seven primitive data types:
- String
- Number
- Boolean
- Undefined
- Null
- Symbol (introduced in ES6)
- BigInt (introduced in ES2020)
Let’s explore each of them.
1. String
- Represents textual data.
- Enclosed within single quotes ‘ ‘, double quotes ” “, or backticks ` `.
Example:
let name = “Alice”;
let greeting = ‘Hello, World!’;
let templateLiteral = `My name is ${name}.`;
console.log(name); // Outputs: Alice
console.log(greeting); // Outputs: Hello, World!
console.log(templateLiteral); // Outputs: My name is Alice.
Note: Template literals (using backticks) allow for embedded expressions using ${expression}.
2. Number
- Represents numeric values.
- Can be integers or floating-point numbers.
Example:
let age = 25;
let price = 19.99;
let negativeNumber = -5;
console.log(age); // Outputs: 25
console.log(price); // Outputs: 19.99
console.log(negativeNumber); // Outputs: -5
Special Numeric Values:
- Infinity: Represents infinity.
- -Infinity: Represents negative infinity.
- NaN: Stands for “Not-a-Number”, a result of invalid or undefined mathematical operations.
Example:
console.log(1 / 0); // Outputs: Infinity
console.log(-1 / 0); // Outputs: -Infinity
console.log(“abc” * 2); // Outputs: NaN
3. Boolean
- Represents logical values: true or false.
Example:
let isOnline = true;
let isAdult = false;
console.log(isOnline); // Outputs: true
console.log(isAdult); // Outputs: false
4. Undefined
- A variable that has been declared but not assigned a value has the value undefined.
Example:
let x;
console.log(x); // Outputs: undefined
5. Null
- Represents the intentional absence of any object value.
- It’s a primitive value that represents “nothing” or “empty”.
Example:
let y = null;
console.log(y); // Outputs: null
6. Symbol
- Represents a unique and immutable identifier.
- Often used as object property keys to avoid property name collisions.
Example:
let symbol1 = Symbol(‘description’);
let symbol2 = Symbol(‘description’);
console.log(symbol1 === symbol2); // Outputs: false
Note: Even if two symbols have the same description, they are unique.
7. BigInt
- Represents integers with arbitrary precision.
- Used for numbers larger than Number.MAX_SAFE_INTEGER (2^53 – 1).
Example:
let bigNumber = 9007199254740991n; // Note the ‘n’ at the end
let anotherBigNumber = BigInt(9007199254740991);
console.log(bigNumber); // Outputs: 9007199254740991n
console.log(bigNumber + 1n); // Outputs: 9007199254740992n
Note: Operations between BigInt and Number types are not allowed.
Non-Primitive Data Types
Non-primitive data types are objects in JavaScript. Unlike primitive data types, they are mutable and can hold collections of values and more complex entities.
1. Objects
- Used to store collections of data and more complex entities.
- Created using curly braces {} with key-value pairs.
Example:
let person = {
firstName: ‘John’,
lastName: ‘Doe’,
age: 30
};
console.log(person.firstName); // Outputs: John
console.log(person[‘lastName’]); // Outputs: Doe
2. Arrays
- Special type of object used for storing ordered collections.
- Elements are accessed using index numbers starting from 0.
Example:
let colors = [‘red’, ‘green’, ‘blue’];
console.log(colors[0]); // Outputs: red
console.log(colors.length); // Outputs: 3
3. Functions
- First-class objects in JavaScript.
- Can be assigned to variables, passed as arguments, and returned from other functions.
Example:
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet(‘Alice’)); // Outputs: Hello, Alice!
Type Conversion
JavaScript can convert values from one data type to another.
Implicit Conversion
Also known as type coercion, where JavaScript automatically converts data types.
Example:
let result = ‘5’ – 2;
console.log(result); // Outputs: 3 (string ‘5’ is converted to number 5)
let sum = ‘5’ + 2;
console.log(sum); // Outputs: ’52’ (number 2 is converted to string ‘2’)
Explanation:
- Subtraction – triggers numeric conversion.
- Addition + with a string triggers string concatenation.
Explicit Conversion
You can explicitly convert data types using built-in functions.
String Conversion
let num = 100;
let strNum = String(num);
console.log(typeof strNum); // Outputs: string
Number Conversion
let str = ’50’;
let numStr = Number(str);
console.log(typeof numStr); // Outputs: number
Boolean Conversion
- Truthy values convert to true.
- Falsy values (0, ”, null, undefined, NaN) convert to false.
console.log(Boolean(1)); // Outputs: true
console.log(Boolean(0)); // Outputs: false
console.log(Boolean(‘hello’)); // Outputs: true
console.log(Boolean(”)); // Outputs: false
Checking Data Types
Use the typeof operator to check the data type of a value.
Example:
console.log(typeof ‘Hello’); // Outputs: string
console.log(typeof 42); // Outputs: number
console.log(typeof true); // Outputs: boolean
console.log(typeof undefined); // Outputs: undefined
console.log(typeof null); // Outputs: object (this is a known quirk in JavaScript)
console.log(typeof {}); // Outputs: object
console.log(typeof []); // Outputs: object
console.log(typeof function(){}); // Outputs: function
console.log(typeof Symbol(‘id’)); // Outputs: symbol
console.log(typeof 123n); // Outputs: bigint
Note: The typeof operator returns ‘object’ for null, which is a historical bug in JavaScript.
Quiz Questions
Q1: What is the output of the following code?
let x;
console.log(typeof x);
A. ‘null’
B. ‘undefined’
C. ‘object’
D. ‘string’
Answer: B. ‘undefined’
Q2: Which of the following is NOT a primitive data type in JavaScript?
A. string
B. number
C. object
D. boolean
Answer: C. object
Q3: What will be the result of ‘5’ + 3?
A. 8
B. 53
C. NaN
D. Error
Answer: B. ’53’
Explanation: The number 3 is converted to a string ‘3’, and concatenated with ‘5’ resulting in ’53’.
Q4: How do you declare a BigInt value?
A. let bigNumber = 1234567890;
B. let bigNumber = BigInt(1234567890);
C. let bigNumber = 1234567890n;
D. Both B and C
Answer: D. Both B and C
Q5: What is the output of typeof null in JavaScript?
A. ‘null’
B. ‘undefined’
C. ‘object’
D. ‘boolean’
Answer: C. ‘object’
Explanation: Due to a historical bug, typeof null returns ‘object’.
Q6: Which method can be used to convert a string to a number in JavaScript?
A. Number()
B. String()
C. Boolean()
D. toString()
Answer: A. Number()
Q7: What will be the output of console.log(Boolean(”))?
A. true
B. false
C. undefined
D. Error
Answer: B. false
Explanation: An empty string is a falsy value in JavaScript.
Q8: Which of the following is a valid way to create a Symbol?
A. let sym = Symbol(‘description’);
B. let sym = new Symbol(‘description’);
C. let sym = Symbol.create(‘description’);
D. let sym = symbol(‘description’);
Answer: A. let sym = Symbol(‘description’);
Q9: What will be the result of the following code?
let a = [1, 2, 3];
console.log(typeof a);
A. ‘array’
B. ‘object’
C. ‘number’
D. ‘undefined’
Answer: B. ‘object’
Explanation: In JavaScript, arrays are objects.
Q10: Which of the following values is NOT considered falsy in JavaScript?
A. 0
B. ‘0’
C. null
D. undefined
Answer: B. ‘0’
Explanation: The string ‘0’ is a non-empty string and is considered truthy.
Conclusion
Congratulations! You’ve learned about the different data types in JavaScript, including primitive and non-primitive types. Understanding data types is crucial for writing robust and error-free JavaScript code. Keep practicing by experimenting with different data types and operations to reinforce your learning.