In JavaScript, data types can be broadly classified into two categories: primitive
and non-primitive
data types. Understanding these data types is crucial for writing effective and efficient code. In this article, we will explore primitive
and non-primitive
data types in JavaScript, along with examples.
Primitive Data Types
Primitive data types in JavaScript are simple data types that are not objects and do not have methods. They are immutable, which means that their values cannot be changed once they are created. There are six primitive data types in JavaScript.
1. String: A string is a collection of characters that are enclosed within single or double quotes. For example:
let name = 'John Doe';
2. Number: A number is a numerical value, which can be either positive, negative, or with decimal points. For example:
let age = 25;
let salary = 50000.50;
3. Boolean: A boolean data type can have only two values - true or false. For example:
let isMarried = true;
4. Null: Null represents a null or empty value. For example:
let address = null;
5. Undefined: Undefined represents a variable that has not been assigned a value. For example:
let gender;
6. Symbol: A symbol is a unique and immutable data type that is used to identify object properties. For example:
const mySymbol = Symbol('mySymbol');
Non-Primitive Data Types
Non-primitive data types in JavaScript are complex data types that are objects and can have methods. They are mutable, which means that their values can be changed. There are three non-primitive data types in JavaScript:
1. Object: An object is a collection of key-value pairs, where the key is a string and the value can be any data type. For example:
const person = {
name: 'John Doe',
age: 25,
isMarried: true
};
2. Array: An array is a collection of elements, which can be of any data type. The elements are indexed and can be accessed using the index number. For example:
const numbers = [1, 2, 3, 4, 5];
3. Function: A function is a block of code that can be invoked or called to perform a specific task. It can accept parameters and return a value. For example:
function addNumbers(num1, num2) {
return num1 + num2;
}
Top comments (0)