DEV Community

Discussion on: 9 Extremely Powerful JavaScript Hacks

Collapse
 
hnnx profile image
Nejc • Edited

How exactly does this work?

var my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9];

console.log( my_list.sort(function() {
return Math.random() - 0.5 //why 0.5?
}));

also, aren't arrays fixed size like in Java?

Collapse
 
kh136 profile image
k

Math.random() returns a number between 0 and 1. -0.5 is so that the result is between -0.5 and 0.5. The end result is half the time the comparator will be negative and half the time it will be positive, basically a coin toss function. And no they're not, they're more like python lists.

Collapse
 
softmantk profile image
NIKHIL CM

Hi, Can you explain Why it is not like a coin toss function ? I thought it is...