javascript - checking array length in switch statement -


i looking @ using switch statement check if array's length greater 0. using if/else statement want more comfortable using switch statements , baffled why following doesn't work.

given array of numbers, function determines whether sum of of numbers odd or even.

here looks like:

function oddoreven(array) {     switch(array) {      case array.length === 0:         throw 'error';        break;      case array.length > 0:        answer = array.reduce((a, b)=>{          return + b;        }) % 2 === 0 ? 'even' :  'odd';         break;    } } 

examples

oddoreven([0]) returns "even" oddoreven([2, 5, 34, 6]) returns "odd" oddoreven([0, -1, -5]) returns "even" 

i know can if(array.length > 0)... said want used using switch statements , thought should work.

with switch, compare expression values, doing action each one. in case, switch array.length that:

function oddoreven(array) {     switch(array.length) {      case 0:         throw 'error';        break;       default: // in case, array.length != 0, not > 0        answer = array.reduce((a, b)=>{          return + b;        }) % 2 === 0 ? 'even' :  'odd';         break;    } } 

however, in opinion, if/else right 1 used here. worth take @ mdn documentation switch understand best scenarios in can used.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -