Arrow functions don't allow ifs inside their bodies. So, the only condition testing allowed is using a ternary operator. But ternary operators must have two statements (one if the condition is true and another if it is false). Consider I have an array and want to log only the numbers greater than 5 using a forEach. This will throw an error:
var array = [1, 7, 2, 9, 8, 0];
array.forEach(n => (if(n > 5) console.log(n)));
And using a ternary operator will require to put a dummy code in the section where I don't want to do anything like this:
var array = [1, 7, 2, 9, 8, 0];
var dummyCodePlaceholder;
array.forEach(n => n > 5? console.log(n): dummyCodePlaceholder);
// because this will throw an error if I leave it empty
//forEach(n => n > 5? console.log(n): );
So is there another way (a solid way) to mimic ifs (alone) inside arrow functions?
Note: the example provided (log numbers greater than 5) is not the main issue here.
Aucun commentaire:
Enregistrer un commentaire