Random page redirect

I need a JS code that will do the following:

  1. Generate a random number from 1 to 3
  2. If the number is 1, go to google.com
  3. If the number is 2, go to glitch.com
  4. If the number is 3, go to support.glitch.com

I reckon you can figure it out.

First, front-end or backend? You can probably do it from either.

Find out how to randomise a number from 1 to 3 (or 0 to 2) and find out how to redirect. In front-end you can change window.location to do that.

If back-end, and the redirect happens in response to a GET to an Express route, you can use response.redirect (off the top of my head)

Let us know how you get on… :slight_smile:

function getrandom(min, max) {
  return Math.floor(max - min);

How am i supposed to make it select a number between the min & max values?

function redirect()

    var number = Math.floor((Math.random() * 3) + 1);
    if(number == 1){ window.location = "https://www.google.com" }
    else if(number == 2) { window.location = "https://glitch.com" } // and so on


not to be mean, but isn’t that spoonfeeding code?

Oh come on, it’s a little bit of code. @RiversideRocks can give them code if they want. I’m kinda fed up with this “spoon-feeding” thing. It was OK when I was just used to describe how some choose not to give code to different people, but it’s starting to be a thing where a bunch of people are using in in a context where it isn’t necessary or where people won’t understand (not many people would be accustomed to being told “we won’t spoonfeed you”, you need to explain what it means and why)


If you’re going to run the function multiple times, switch statements might be more optimal, however in the case you are running it around 3 to 5 times you will recieve no noticeable speed increase by using switch statements. The reason for their optimization when run multiple times is that js can generate a hashtable of code, and use the number to tell where to jump to in the hash table which is the kind of thing computers are good at.

I guess I did a bit. However, I didn’t finish the code, I just got OP started.

1 Like

Prettiered it:

function redirect() {
    let number = Math.floor((Math.random() * 3) + 1);
    if (number == 1) { 
      window.location = "https://www.google.com";
    } else if (number == 2) { 
      window.location = "https://glitch.com";
    } else if (number == 3) {
      window.location = "https://support.glitch.com"; // and so on

I guess @RiversideRocks wrote this piece of JS code like how PHP is written - without indentation lol

[ Insert joke here ]


echo $joke;

1 Like