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;
let and const are block-scoped (modern JavaScript).
var is function-scoped (older usage).
What is an Array?
An array is a list-like object that stores multiple values in a single variable.
let fruits = ["apple", "banana", "cherry"];
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
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
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
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);
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
Top comments (0)