Introduction to Arrays and the Math Object in JavaScript
JavaScript offers powerful built-in features to handle collections of data and perform mathematical calculations. Two important concepts you’ll use frequently are Arrays and the Math object.
1. What is an Array?
An array is a special type of object used to store ordered lists of values — like numbers, strings, or even other objects.
Creating an Array
-
Arrays use square brackets
[ ]. -
Items inside are called elements.
-
Elements have a zero-based index (first element is at index 0).
Accessing Array Elements
Common Array Operations
-
Add elements:
-
Remove elements:
-
Loop through arrays:
Or using forEach:
2. What is the Math Object?
The Math object provides properties and methods for mathematical constants and functions. It’s not a constructor, so you use it directly.
Useful Math Methods
-
Math.round(x)— rounds to nearest integer -
Math.floor(x)— rounds down -
Math.ceil(x)— rounds up -
Math.max(a, b, c, ...)— returns largest value -
Math.min(a, b, c, ...)— returns smallest value -
Math.random()— returns a random decimal between 0 (inclusive) and 1 (exclusive) -
Math.sqrt(x)— square root
Examples Using Math
Combining Arrays and Math: Random Choice Example
Pick a random fruit from the array:
Recap
| Concept | Description | Example |
|---|---|---|
| Array | Ordered list of values | const arr = [1, 2, 3] |
| Math Object | Math constants & functions | Math.round(2.5) // 3 |
