Monday, July 19, 2021

Junior Developer Central JS Practice Exercise - 19

 
Question: 

Write a Javascript program to generate a random hexadecimal color code




Answer: 

function getRandomColor() {
        
        let letters = '0123456789ABCDEF'.split('');
        let color = '#';
        for (var i = 0; i < 6; i++ ) {
            color += letters[Math.round(Math.random() * 15)];
        }
        return color;
    }




> we declare a function 'getRandomColor' 
> it has no parameters
> we create a variable 'letters' 
> it is a string of 16 characters - '0123456789ABCDEF'
> we use the split () method to return an array with 16 array elements
> we declare another variable 'color' 
> its is a string with only the '#' character
> we then create a for loop 
>> initialization - before the loop starts we set our variable i = 0
>> condition - we define the condition for the loop to run ('i' must be less than 6)
>> final expression - at the end of each loop iteration we increment the counter variable
>> understanding the statement in the for loop
>> we want to generate a 6 digit hexadecimal color code with a '#' sign before it
>> that 6 digit hexadecimal code needs to be taken from the array we created 'letters' 
>> we use Math.random() to randomly select any of the 16 array elements
>> since array indexes start from 0, we want a random index number from 0 to 15
>> we use the Math.round() method with Math.random() to get a number with no decimals
>> we use both these methods to select a random index number from the 'letters' array
> we then concatenate the result of the 'for loop iteration' with the 'color' string variable
> the for loop will terminate after the 5th iteration and return the 'color' variable

No comments:

Post a Comment