Javascript Data Types

RMAG news

JavaScript has two main categories of data types: Primitive and Non-Primitive (Reference) types.

1. Primitive Data Types
Primitive data types are the most basic types of data, and they include:

a. Number
The Number type represents both integer and floating-point numbers. JavaScript does not differentiate between integer and floating-point numbers.

let age = 25;
let price = 19.99;

b. String
The String type represents a sequence of characters. Strings can be enclosed in single quotes (‘), double quotes (“), or backticks (`) for template literals.

let greeting = “Hello, world!”;
let name = ‘John Doe’;
let message =Hello, ${name}!;

c. Boolean
The Boolean type has only two values: true or false. It is typically used in conditional statements.

let isVerified = true;
let hasAccess = false;

d. Undefined
A variable that has been declared but not assigned a value is of type undefined.

let x;
console.log(x); // undefined

e. Null
The null type represents the intentional absence of any object value. It is one of JavaScript’s primitive values.

let emptyValue = null;

f. Symbol (introduced in ES6)
A Symbol is a unique and immutable primitive value often used as the key of an object property.

let sym1 = Symbol(‘identifier’);
let sym2 = Symbol(‘identifier’);
console.log(sym1 === sym2); // false

g. BigInt (introduced in ES11)
The BigInt type is used for representing integers that are too large to be represented by the Number type.

`
let bigNumber = BigInt(1234567890123456789012345678901234567890n);

`
2. Non-Primitive (Reference) Data Types
Non-primitive data types can hold collections of values and more complex entities. These include:

a. Object
Objects are collections of key-value pairs. Keys are strings (or Symbols), and values can be any type.

let person = {
name: ‘Alice’,
age: 30,
greet: function() {
console.log(‘Hello!’);
}
};
console.log(person.name); // Alice
person.greet(); // Hello!

b. Array
Arrays are ordered collections of values. Arrays are objects, and their elements can be of any type.

let fruits = [‘Apple’, ‘Banana’, ‘Cherry’];
console.log(fruits[1]); // Banana

c. Function
Functions are objects that can be called to perform actions.

function add(a, b) {
return a + b;
}
let sum = add(5, 10);
console.log(sum); // 15

d. Date
The Date object represents a single moment in time. It is used to work with dates and times.

javascript
Copy code
let now = new Date();
console.log(now); // Current date and time

e. RegExp
The RegExp object represents regular expressions and is used for pattern matching in strings.

let pattern = /hello/;
let str = ‘hello world’;
console.log(pattern.test(str)); // true