Sunday, July 11, 2021

Junior Developer Central JS Practice Exercise - 07

 
Question: 

Write a Javascript program to extract the first half of a string of even length. 




Answer: 

function extHalf (str) {

let str001 = str; 
if (str001.length % 2 === 0) { 
return str001.slice(0, str001.length/2); 
} else {
return str001
}
}




> we declare a function 'extHalf'
> it has one parameter 'str'
> we create a variable 'str001'
> we initialize it with a value of our argument 'str' 
> we then open if/else statements to check if the length of 'str001' is even
> we use the modulo / remainder operator to check if the length is even
> if it is even then the modulo operator would have '0' as remainder
> if it is odd then the modulo operator would have '1' as remainder
> if 'str001' is even then we want to return the first half 
> we do that by using the slice method on 'str001' 
> our start parameter is 0 as we want to slice the first half
> we use str001.length / 2, which will give us the half of the total length of the string
> so our end parameter is the half of the total length of the string
> if 'str001' is an odd number then we want to return the same string without any extraction

No comments:

Post a Comment