user9151444
user9151444

Reputation: 19

About Arrays in Javascript

What is the difference between using:

function random(array){
    return array[Math.floor(Math.random()*array.length)];
}

(vs)

function random(array){
    return Math.floor(Math.random()*array.length);
}

Why are we adding return array[] in front ??

I came through Silly Story Generator in MDN example https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Silly_story_generator

here's my source code - https://codepen.io/ranjanrnj44/pen/abzNQYg

Upvotes: -1

Views: 111

Answers (2)

symlink
symlink

Reputation: 12209

The first function returns the value of the array at index ran, the second returns the index itself.

There's no difference between what the two functions return, if your array is made up of ordinal numbers [0...x]. For example:

[0,1,2,3,4]

because random1() returns the value of the nth index of the array:

array[0] = 0
array[1] = 1
array[2] = 2
array[3] = 3
array[4] = 4

If the array is structured in any other way, the functions will operate differently. For example, with the array:

Examples

First:

array: [1,2,3,4,5]
funcs:      random1()   random2()
results:    1           0
            2           1
            3           2
            4           3
            5           4

Second:

array: ["a","b","c","d","e"]
funcs:      random1()   random2()
results:    "a"         0
            "b"         1
            "c"         2
            "d"         3
            "e"         4

function random1(array){
    const num = Math.random()*array.length
    const flooredNum = Math.floor(num)
    return array[flooredNum]
}


function random2(array){
    const num = Math.random()*array.length
    return Math.floor(num)
}

let arr = [0,1,2,3,4]

console.log("random1", random1(arr))
console.log("random2", random2(arr))

arr = ["a","b","c","d","e"]

console.log("random1", random1(arr))
console.log("random2", random2(arr))

Upvotes: 0

Shiny
Shiny

Reputation: 5055

This is just returning a Random number between 0 and array.length - 1

function random(array) {
  return Math.floor(Math.random() * array.length);
}

console.log(random([50,30,100]));


This is getting a random element in the Array, by using the random number as the index

function random(array) {
  return array[Math.floor(Math.random() * array.length)];
}

console.log(random([50,30,100]));

Upvotes: 3

Related Questions