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"]

🚀 I just relaunched my Vanilla JS Pocket Guides with new code examples and real projects to help tie everything you’ll learn together. Check it out.

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

Get Daily Developer Tips