Home > Blockchain >  Using && operator in javascript return statement
Using && operator in javascript return statement

Time:12-12

I am learning javascript and I was applying the filters in javascript code, In below code, is there any possibility to improvise this code ? i was hoping if someone could tell me to how to use only one variable to store result of ages which are greater than 18 and less than 18. is there possibilty to use && operator in single return statement ? So that in final result I can show the data as

Voters under 18,21,24,30,32 category can vote. Voters under 10,15 category cannot vote

//Code

const ages = [10, 15, 18, 21, 24, 30, 32];
const ageResultabove = ages.filter((ageabove) => {
  return ageabove >= 18;
});
const ageResultbelow = ages.filter((ageabelow) => {
  return ageabelow < 18;
});
console.log(`Voters under ${ageResultabove} category can vote`);
console.log(`Voters under ${ageResultbelow} category cannot vote`);

Result should be like this Voters under 18,21,24,30,32 category can vote. Voters under 10,15 category cannot vote

CodePudding user response:

You could take a function for checking adult ages and group by this result with true and false in a single loop.

const
    ages = [10, 15, 18, 21, 24, 30, 32],
    isAdult = age => age >= 18,
    result = ages.reduce((accumulator, age) => {
        accumulator[isAdult(age)].push(age);
        return accumulator
    }, { true: [], false: [] });

console.log(`Voters under ${result.true.join(', ')} category can vote`);
console.log(`Voters under ${result.false.join(', ')} category cannot vote`);

CodePudding user response:

Firstly, you are trying to compare string datatype with a number datatype to resolve this issue, either change your items inside array to plain number e.g. [10, 12, 18, ...] or use parseInt() function inside filter condition.

parseInt(ageabove, 10) >= 18

and yes, parseInt function is built-in inside javascript.

Then in ageResultAbove add join.

e.g.

console.log(`Voters under ${ageResultabove.join(", ")} category can vote`);

full code would be:

const ages = [10, 15, 18, 21, 24, 30, 32];

const ageResultabove = ages.filter((a) => a >= 18);
const ageResultbelow = ages.filter((a) => a < 18);

console.log(`Voters under ${ageResultabove.join(", ")} category can vote`);
console.log(`Voters under ${ageResultbelow.join(", ")} category cannot vote`);

CodePudding user response:

Why don't you just concatenate the two strings? Like:

console.log(`Voters under ${ageResultabove} category can vote. Voters under ${ageResultbelow} category cannot vote`);

The && operator is used for logical comparison, therefore if you use it the result would be a boolean (True or False).

  • Related