DEV Community

P Mukila
P Mukila

Posted on

I Learned Today-Understanding Arrays, Variables, Length, and Random Math in JavaScript

Whether you're just starting with JavaScript or need a refresher, understanding arrays, variables, and JavaScript's math functions like Math.random() and Math.floor() is essential. These core concepts are used in everything from basic scripts to full-scale applications. Let’s explore them with simple examples.

What is a Variable?

A variable is like a container that stores data. You can create variables using let, const, or var.

let name = "Alice";
const age = 25;
Enter fullscreen mode Exit fullscreen mode
let and const are block-scoped (modern JavaScript).

var is function-scoped (older usage).
Enter fullscreen mode Exit fullscreen mode

What is an Array?

An array is a list-like object that stores multiple values in a single variable.

let fruits = ["apple", "banana", "cherry"];

Enter fullscreen mode Exit fullscreen mode

Each item in an array has an index, starting from 0. So fruits[0] is "apple".

Getting the Length of an Array

You can find out how many items are in an array using the .length property.

console.log(fruits.length); // Output: 3

Enter fullscreen mode Exit fullscreen mode

This is useful when looping through arrays or picking a random item.

Generating Random Numbers with Math.random()

Math.random() returns a random number between 0 (inclusive) and 1 (exclusive).

let randomNum = Math.random();
console.log(randomNum); // Example output: 0.47284632

Enter fullscreen mode Exit fullscreen mode

Rounding Down with Math.floor()

Math.floor() rounds a number down to the nearest integer.

let num = Math.floor(4.7);
console.log(num); // Output: 4
Enter fullscreen mode Exit fullscreen mode

Combining Math.random() and Math.floor() to Pick a Random Array Item

Here's a common use case: picking a random item from an array.

let colors = ["red", "blue", "green", "yellow"];
let randomIndex = Math.floor(Math.random() * colors.length);
let randomColor = colors[randomIndex];

console.log(randomColor);

Enter fullscreen mode Exit fullscreen mode

Breakdown:

Math.random() generates a decimal between 0 and 1.

Multiply it by colors.length to scale it to the array size.

Math.floor() turns it into a whole number (an index).

Use th
Enter fullscreen mode Exit fullscreen mode

Top comments (0)