Skip to main content Accessibility Feedback

Shuffling JavaScript array values

This tip comes from John Howard’s 12 Extremely Useful Hacks for JavaScript article.

If you ever need to randomly sort an array of items in JavaScript, here’s a simple function to help you do so:

var shuffle = function (arr) {
    // Create a clone of the array so that we don't shuffle the original one
    var arrClone = arr.slice(0);
    // Shuffle the array
    return arrClone.sort(function() {
        return Math.random() - 0.5

To use it, pass in any array.

var flavors = ['chocolate', 'vanilla', 'coffee', 'strawberry'];
var shuffledFlavors = shuffle( flavors );
// ex. return ["coffee", "vanilla", "strawberry", "chocolate"]

🚀 Make 2018 the year you master JavaScript! My pocket guides and mini courses are short, focused, and made for beginners. You can do this!

Have any questions or comments about this post? Email me at or contact me on Twitter at @ChrisFerdinandi.

Get Daily Developer Tips