Skip to main content

Built-in objects in java script

In JavaScript, built-in objects are pre-defined objects that provide functionality commonly needed in web development. These objects are part of the JavaScript language and can be used without any need to define them yourself. They include objects for working with data types, performing mathematical computations, handling dates and times, manipulating strings, and more.

Here's an overview of the most commonly used built-in objects in JavaScript, along with examples:

1. Object

The Object class is the base class for all JavaScript objects. It provides methods to work with all objects, including creating new objects, manipulating properties, and inheriting properties.

Example:

const obj = {
name: 'Alice',
age: 30
};

console.log(Object.keys(obj)); // Outputs: ['name', 'age']
console.log(Object.values(obj)); // Outputs: ['Alice', 30]
console.log(Object.entries(obj)); // Outputs: [['name', 'Alice'], ['age', 30]]

2. Array

The Array class provides methods for creating, manipulating, and querying arrays of data.

Example:

const arr = [1, 2, 3, 4, 5];

console.log(arr.length); // Outputs: 5
console.log(arr.push(6)); // Adds 6 to the end of the array and outputs: 6
console.log(arr.pop()); // Removes the last element (6) and outputs: 6
console.log(arr.map(x => x * 2)); // Outputs: [2, 4, 6, 8, 10]

3. String

The String class provides methods for creating and manipulating string values.

Example:

const str = 'Hello, World!';

console.log(str.length); // Outputs: 13
console.log(str.toUpperCase()); // Outputs: 'HELLO, WORLD!'
console.log(str.substring(0, 5)); // Outputs: 'Hello'
console.log(str.split(', ')); // Outputs: ['Hello', 'World!']

4. Number

The Number class provides methods for creating and manipulating numerical values.

Example:

const num = 42;

console.log(num.toString()); // Outputs: '42'
console.log(Number.isInteger(num)); // Outputs: true
console.log(Number.parseFloat('42.42')); // Outputs: 42.42
console.log(Number.isNaN(NaN)); // Outputs: true

5. Math

The Math class provides mathematical constants and functions.

Example:

console.log(Math.PI); // Outputs: 3.141592653589793
console.log(Math.sqrt(16)); // Outputs: 4
console.log(Math.random()); // Outputs a random number between 0 and 1
console.log(Math.max(1, 2, 3)); // Outputs: 3

6. Date

The Date class provides methods for working with dates and times.

Example:

const now = new Date();

console.log(now); // Outputs the current date and time
console.log(now.getFullYear()); // Outputs the current year
console.log(now.getMonth()); // Outputs the current month (0-11)
console.log(now.getDate()); // Outputs the current day of the month

7. RegExp

The RegExp class provides methods for working with regular expressions, which are patterns used to match character combinations in strings.

Example:

const regex = /hello/i;
const str = 'Hello, World!';

console.log(regex.test(str)); // Outputs: true
console.log(str.match(regex)); // Outputs: ['Hello']

8. Function

The Function class allows you to create new functions dynamically.

Example:

const add = new Function('a', 'b', 'return a + b');
console.log(add(2, 3)); // Outputs: 5

9. Promise

The Promise class represents an asynchronous operation that may complete successfully or fail.

Example:

const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('Done!'), 1000);
});

promise.then(result => console.log(result)); // Outputs: 'Done!' after 1 second

10. Map

The Map class is a collection of key-value pairs where keys can be of any type.

Example:

const map = new Map();

map.set('name', 'Alice');
map.set('age', 30);

console.log(map.get('name')); // Outputs: 'Alice'
console.log(map.has('age')); // Outputs: true
console.log(map.size); // Outputs: 2

11. Set

The Set class is a collection of unique values.

Example:

const set = new Set();

set.add(1);
set.add(2);
set.add(2); // Duplicate value will not be added

console.log(set.has(1)); // Outputs: true
console.log(set.size); // Outputs: 2

12. JSON

The JSON class provides methods for parsing and stringifying JSON data.

Example:

const obj = { name: 'Alice', age: 30 };
const jsonString = JSON.stringify(obj);

console.log(jsonString); // Outputs: '{"name":"Alice","age":30}'
console.log(JSON.parse(jsonString)); // Outputs: { name: 'Alice', age: 30 }

Sure! Continuing from where we left off, here are some additional built-in objects and their usage in JavaScript:

13. Symbol

The Symbol class provides a way to create unique identifiers. Symbols are often used as unique property keys in objects to avoid property name collisions.

Example:

const sym1 = Symbol('description');
const sym2 = Symbol('description');

console.log(sym1 === sym2); // Outputs: false, symbols are always unique

const obj = {
[sym1]: 'value1',
[sym2]: 'value2'
};

console.log(obj[sym1]); // Outputs: 'value1'
console.log(obj[sym2]); // Outputs: 'value2'

14. Error

The Error class and its subtypes represent different kinds of errors that can occur in a program. Errors can be thrown using the throw statement and caught using try...catch.

Example:

try {
throw new Error('Something went wrong!');
} catch (e) {
console.log(e.message); // Outputs: 'Something went wrong!'
}

try {
throw new TypeError('This is a type error.');
} catch (e) {
console.log(e instanceof TypeError); // Outputs: true
console.log(e.message); // Outputs: 'This is a type error.'
}

15. Intl

The Intl object provides language-sensitive string comparison, number formatting, and date and time formatting.

Example:

const number = 1234567.89;

const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
});

console.log(formatter.format(number)); // Outputs: $1,234,567.89

const date = new Date(Date.UTC(2021, 11, 24, 10, 33, 30));

const dateFormatter = new Intl.DateTimeFormat('en-GB', {
year: 'numeric',
month: 'long',
day: '2-digit'
});

console.log(dateFormatter.format(date)); // Outputs: 24 December 2021

16. WeakMap

The WeakMap class is a collection of key-value pairs where the keys are weakly referenced. This means that the keys can be garbage collected if there are no other references to them.

Example:

const weakMap = new WeakMap();

const obj = {};
weakMap.set(obj, 'value');

console.log(weakMap.get(obj)); // Outputs: 'value'
console.log(weakMap.has(obj)); // Outputs: true

// When `obj` is garbage collected, the entry in the `WeakMap` will also be removed.

17. WeakSet

The WeakSet class is a collection of objects where the objects are weakly referenced. This means that objects can be garbage collected if there are no other references to them.

Example:

const weakSet = new WeakSet();

const obj1 = {};
const obj2 = {};

weakSet.add(obj1);
weakSet.add(obj2);

console.log(weakSet.has(obj1)); // Outputs: true
console.log(weakSet.has(obj2)); // Outputs: true

// When `obj1` and `obj2` are garbage collected, they will also be removed from the `WeakSet`.

18. Proxy

The Proxy class allows you to create a proxy object that can intercept and redefine operations for another object.

Example:

const target = {
message1: 'hello',
message2: 'world'
};

const handler = {
get: function(obj, prop) {
if (prop === 'message1') {
return 'hi';
}
return obj[prop];
}
};

const proxy = new Proxy(target, handler);

console.log(proxy.message1); // Outputs: 'hi'
console.log(proxy.message2); // Outputs: 'world'

19. Reflect

The Reflect object provides methods for interceptable JavaScript operations. These methods are the same as those of the proxy handlers and provide a simpler and more predictable way to perform default operations.

Example:

const obj = { x: 1, y: 2 };

console.log(Reflect.get(obj, 'x')); // Outputs: 1
Reflect.set(obj, 'x', 42);
console.log(obj.x); // Outputs: 42

const descriptor = Reflect.getOwnPropertyDescriptor(obj, 'y');
console.log(descriptor); // Outputs: { value: 2, writable: true, enumerable: true, configurable: true }

20. TypedArray

TypedArray objects provide a mechanism for accessing raw binary data in memory buffers. There are several types of typed arrays, including Int8Array, Uint8Array, Float32Array, etc.

Example:

const buffer = new ArrayBuffer(16);
const int32View = new Int32Array(buffer);

int32View[0] = 42;
console.log(int32View[0]); // Outputs: 42

const float32View = new Float32Array(buffer);
float32View[0] = 3.14;
console.log(float32View[0]); // Outputs: 3.14

Certainly! Here are more built-in objects in JavaScript along with their usage and examples:

21. ArrayBuffer

The ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. You cannot directly manipulate the contents of an ArrayBuffer; instead, you create one of the typed array or DataView objects to manipulate the buffer.

Example:

const buffer = new ArrayBuffer(16);
console.log(buffer.byteLength); // Outputs: 16

22. DataView

The DataView object provides a low-level interface for reading and writing multiple number types in an ArrayBuffer irrespective of the platform's endianness.

Example:

const buffer = new ArrayBuffer(16);
const view = new DataView(buffer);

view.setInt8(0, 42);
console.log(view.getInt8(0)); // Outputs: 42

23. BigInt

The BigInt object is a built-in object that provides a way to represent whole numbers larger than 2^53 - 1, which is the largest number JavaScript can reliably represent with the Number primitive.

Example:

const bigInt = BigInt(123456789012345678901234567890);
console.log(bigInt); // Outputs: 123456789012345678901234567890n

const sum = bigInt + BigInt(10);
console.log(sum); // Outputs: 123456789012345678901234567900n

24. Promise

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises are used to handle asynchronous operations in a more readable and manageable way than using callbacks.

Example:

const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('Done!'), 1000);
});

promise.then(result => console.log(result)); // Outputs: 'Done!' after 1 second

25. Map

The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.

Example:

const map = new Map();

map.set('name', 'Alice');
map.set('age', 30);

console.log(map.get('name')); // Outputs: 'Alice'
console.log(map.has('age')); // Outputs: true
console.log(map.size); // Outputs: 2

26. Set

The Set object lets you store unique values of any type, whether primitive values or object references.

Example:

const set = new Set();

set.add(1);
set.add(2);
set.add(2); // Duplicate value will not be added

console.log(set.has(1)); // Outputs: true
console.log(set.size); // Outputs: 2

27. WeakMap

The WeakMap object is a collection of key/value pairs in which the keys are weakly referenced. Keys must be objects, and values can be arbitrary values.

Example:

const weakMap = new WeakMap();

const obj = {};
weakMap.set(obj, 'value');

console.log(weakMap.get(obj)); // Outputs: 'value'
console.log(weakMap.has(obj)); // Outputs: true

// When `obj` is garbage collected, the entry in the `WeakMap` will also be removed.

28. WeakSet

The WeakSet object lets you store weakly held objects in a collection.

Example:

const weakSet = new WeakSet();

const obj1 = {};
const obj2 = {};

weakSet.add(obj1);
weakSet.add(obj2);

console.log(weakSet.has(obj1)); // Outputs: true
console.log(weakSet.has(obj2)); // Outputs: true

// When `obj1` and `obj2` are garbage collected, they will also be removed from the `WeakSet`.

29. Atomics

The Atomics object provides atomic operations as static methods. These operations are used with SharedArrayBuffer objects.

Example:

const buffer = new SharedArrayBuffer(1024);
const uint8 = new Uint8Array(buffer);

Atomics.store(uint8, 0, 123);
console.log(Atomics.load(uint8, 0)); // Outputs: 123

30. SharedArrayBuffer

The SharedArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer that can be used to create views on shared memory. Unlike ArrayBuffer, multiple threads can access and modify the contents of a SharedArrayBuffer.

Example:

const sab = new SharedArrayBuffer(1024);
console.log(sab.byteLength); // Outputs: 1024

31. Intl.DateTimeFormat

The Intl.DateTimeFormat object enables language-sensitive date and time formatting.

Example:

const date = new Date(Date.UTC(2021, 11, 24, 10, 33, 30));

const dateFormatter = new Intl.DateTimeFormat('en-GB', {
year: 'numeric',
month: 'long',
day: '2-digit'
});

console.log(dateFormatter.format(date)); // Outputs: 24 December 2021

32. Intl.NumberFormat

The Intl.NumberFormat object enables language-sensitive number formatting.

Example:

const number = 1234567.89;

const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
});

console.log(formatter.format(number)); // Outputs: $1,234,567.89

33. Intl.Collator

The Intl.Collator object enables language-sensitive string comparison.

Example:

const collator = new Intl.Collator('en', { sensitivity: 'base' });

console.log(collator.compare('a', 'A')); // Outputs: 0 (considered equal)

Summary

  • Object: Base class for all objects.

  • Array: Work with arrays of data.

  • String: Manipulate string values.

  • Number: Work with numerical values.

  • Math: Perform mathematical operations.

  • Date: Handle dates and times.

  • RegExp: Work with regular expressions.

  • Function: Create functions dynamically.

  • Promise: Represent asynchronous operations.

  • Map: Collection of key-value pairs.

  • Set: Collection of unique values.

  • JSON: Parse and stringify JSON data.

  • Symbol: Unique identifiers.

  • Error: Represent different kinds of errors.

  • Intl: Language-sensitive formatting and comparisons.

  • WeakMap: Weakly referenced key-value pairs.

  • WeakSet: Weakly referenced objects.

  • Proxy: Intercept and redefine operations for another object.

  • Reflect: Interceptable operations and default behavior.

  • TypedArray: Access raw binary data.

  • ArrayBuffer: Fixed-length raw binary data buffer.

  • DataView: Low-level interface for reading and writing multiple number types in an ArrayBuffer.

  • BigInt: Represents whole numbers larger than 2^53 - 1.

  • Promise: Represents the eventual completion or failure of an asynchronous operation.

  • Map: Holds key-value pairs and remembers the original insertion order of the keys.

  • Set: Stores unique values of any type.

  • WeakMap: Collection of key/value pairs in which the keys are weakly referenced.

  • WeakSet: Collection of objects that are weakly referenced.

  • Atomics: Provides atomic operations for shared memory.

  • SharedArrayBuffer: Fixed-length raw binary data buffer that can be used to create views on shared memory.

  • Intl.DateTimeFormat: Enables language-sensitive date and time formatting.

  • Intl.NumberFormat: Enables language-sensitive number formatting.

  • Intl.Collator: Enables language-sensitive string comparison.