Primitive and Reference value in JavaScript
In JavaScript, there are two types of data types: primitive and reference values.
Primitive values are immutable and are directly stored in memory. There are six primitive data types in JavaScript:
- String: represents a sequence of characters, enclosed in single or double quotes.
Example:
let name = 'John';
- Number: represents a numeric value, including integers and floating-point numbers.
Example:
let age = 25;
- Boolean: represents a logical value, either true or false.
Example:
let isStudent = true;
- Undefined: represents a variable that has been declared but has not been assigned a value.
Example:
let city;
- Null: represents a deliberate non-value or absence of any object value.
Example:
let car = null;
- Symbol: represents a unique identifier.
Example:
let id = Symbol('id');
Reference values are objects that are stored in memory and accessed by reference. There are three reference data types in JavaScript:
- Object: represents a collection of properties and methods.
Example:
let person = {
name: 'John',
age: 25,
isStudent: true
};
- Array: represents a collection of elements, enclosed in square brackets.
Example:
let numbers = [1, 2, 3, 4, 5];
- Function: represents a reusable block of code that performs a specific task.
Example:
function greet(name) {
console.log(`Hello, ${name}!`);
}
To differentiate between primitive and reference values, we can use the typeof
operator. For example:
typeof 'John'; // "string"
typeof 25; // "number"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object"
typeof Symbol('id'); // "symbol"
typeof { name: 'John', age: 25 }; // "object"
typeof [1, 2, 3, 4, 5]; // "object"
typeof function() {}; // "function"