Monday, July 12, 2021

Junior Developer Central JS Practice Exercise - 12

 
Question: 

Write a Javascript program to find the number of even values up to a given number. 




Answer: 

function evenValue (num) {

let evenNum = num;
let allVal = []; 
let totalEven; 

for (let i = 1; i < evenNum; i++) {

allVal.push(i);
totalEven = allVal.filter(i => i % 2 === 0).length;

}; 
console.log(totalEven);
}




> we declare a function 'evenValue'
> it has one parameter 'num'; which is a number
> we have to find out all the even values up to the number provided in 'num' 
> so first we create an array of all numbers from 1 to n (or 'num')  
>> we declare a variable 'allVal' which is an array
>> we use a for loop to push all the numbers up to n (or 'num')
> secondly we use the filter method on 'allVal' to create an array of even numbers
>> we declare another variable 'totalEven' 
>> it is initialized with a value we get by using the filter method on 'allVal' 
>> in order to get the even numbers, we use the modulo operator 
>> if the number is even then the remainder will always be '0' if number is divided by 2
>> since we do not need an array of even numbers but we only need the total number of even digits, we use the length method after the filter method on 'allVal' 
>> so 'totalEven' will have the total number of even digits
> we console.log it to get our answer

No comments:

Post a Comment