Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Create random integers in a given range

    Basarat Ali SyedBasarat Ali Syed

    In this lesson, using TypeScript / Javascript, we learn how to solve a common problem given to new developers in interviews, generate a random number between two integers.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Javascript math.random function provides you with a random floating point number in the range 0inclusive and 1 exclusive.

    Let's go ahead and look for a hundred times, and look at the result for math at random. You can easily scale this 0to less than 1 result to an upper limit by simple multiplication. For example, if you go ahead and multiply the result of 100, we get random values in the range 0inclusive all the way up to less than 100.

    You can limit this value to an integer if you wanted by simply using math.flow. Values in the range 0to less than 1 get chopped to 0The range 1 to less than 2 get chopped to 1, and so on till 99 to less than 100 gets chopped to 99.

    A common challenge presented to beginning developers in an interview is to go ahead and create a function that should return an integer between a given start and end value. We start off by creating a function that accepts a start value and a before value.

    We simply add start to the result that at least start is included. Next, we flow the value returned by math.random after scaling it up to the length of the start before range. As a demonstration, let's go ahead and run this function 100 times, and we can use a different start value if you wanted.