JavaScript has a number of built-in objects that extend the flexibility of the language. These objects are:
- Array – An array is a collection of elements that can be accessed by index.
- Date – A date object represents a specific point in time.
- Math – The Math object provides a number of mathematical functions, such as sin(), cos(), and sqrt().
- String – A string object represents a sequence of characters.
- Object – The Object object is the base class for all other objects in JavaScript.
In addition to these objects, JavaScript also has a number of built-in constructors, such as:
- Boolean – The Boolean constructor creates a Boolean object.
- Function – The Function constructor creates a function object.
- Number – The Number constructor creates a Number object.
- Symbol – The Symbol constructor creates a Symbol object.
These objects and constructors can be used to create and manipulate data in JavaScript. For example, the following code creates an array of numbers and then calculates the average of the numbers:
Code snippet
var numbers = [1, 2, 3, 4, 5];
var average = numbers.reduce((a, b) => a + b) / numbers.length;
console.log(average); // 3
This code uses the Array object’s reduce() method to calculate the average of the numbers in the numbers array. The reduce() method takes two arguments: a starting value and a function. The function is called once for each element in the array, and the starting value is used as the argument to the function the first time it is called. The function returns the value that is used as the argument to the function the next time it is called. In this case, the function simply adds the current element of the array to the starting value. The reduce() method returns the final value after all of the elements of the array have been processed.
The JavaScript built-in objects and constructors provide a powerful foundation for creating and manipulating data. By learning how to use these objects, you can write JavaScript code that is both efficient and effective.