Javascript

Introduction to Arrays and the Math Object

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

js
const fruits = ["apple", "banana", "cherry"];
  • Arrays use square brackets [ ].

  • Items inside are called elements.

  • Elements have a zero-based index (first element is at index 0).

Accessing Array Elements

js
console.log(fruits[0]); // Output: apple
console.log(fruits[2]); // Output: cherry

Common Array Operations

  • Add elements:

js
fruits.push("date"); // adds to the end
fruits.unshift("kiwi"); // adds to the beginning
  • Remove elements:

js
fruits.pop(); // removes last element
fruits.shift(); // removes first element
  • Loop through arrays:

js
for(let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}

Or using forEach:

js
fruits.forEach(fruit => console.log(fruit));

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

js
console.log(Math.round(4.7)); // 5
console.log(Math.floor(4.7)); // 4
console.log(Math.ceil(4.2)); // 5

console.log(Math.max(10, 5, 20)); // 20
console.log(Math.min(10, 5, 20)); // 5

console.log(Math.random()); // e.g., 0.573849


Combining Arrays and Math: Random Choice Example

Pick a random fruit from the array:

js
const randomIndex = Math.floor(Math.random() * fruits.length);
console.log(fruits[randomIndex]);

Recap

Concept Description Example
Array Ordered list of values const arr = [1, 2, 3]
Math Object Math constants & functions Math.round(2.5) // 3

Leave a Reply

Your email address will not be published. Required fields are marked *