Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of if-else in JavaScript ES6

I am learning ES6 and following is my ES5 code which is running fine -

var myArr = [34,45,67,34,2,67,1,5,90];
var evenArr = [];
var oddArr = [];

myArr.map(function(x){
  if(x%2==0) evenArr.push(x);
  else oddArr.push(x);
});

Now if I am converting this to ES6 I am getting errors of Unexpected token near if, let me know what I am doing wrong here -

My ES6 code -

var myArr = [34,45,67,34,2,67,1,5,90];
var evenArr = [];
var oddArr = [];
myArr.map( x => if(x%2==0) evenArr.push(x) else oddArr.push(x) )
like image 534
Nesh Avatar asked Apr 04 '16 06:04

Nesh


People also ask

Why do we use if...else statements in JavaScript?

Definition and Usage. The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed. The if/else statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions.

Which is faster if or else?

Conclusion: If only is faster than If-Else construct. Just use the one that's most readable (presumably the if/else one).

What is the difference between if statement and if...else statement?

With the if statement, a program will execute the true code block or do nothing. With the if/else statement, the program will execute either the true code block or the false code block so something is always executed with an if/else statement.

What is if...else operators?

if..else statements In an if...else statement, if the code in the parenthesis of the if statement is true, the code inside its brackets is executed. But if the statement inside the parenthesis is false, all the code within the else statement's brackets is executed instead. Output: Statement is False!


1 Answers

That's because the arrow functions accept expressions while you're passing a statement.

Your code is misleading: Array.prototype.map implies you would use the result somehow, while you are not.

If you wanted to improve the semantics of your code you would use Array.prototype.forEach that is designed specifically to iterate over an array and not return anything:

var myArr = [34,45,67,34,2,67,1,5,90];
var evenArr = [];
var oddArr = [];
myArr.forEach(x => {
    if (x % 2 === 0) {
        evenArr.push(x);
    } else {
        oddArr.push(x);
    }
});

References:

  • Array.prototype.forEach()
  • Arrow functions
like image 158
zerkms Avatar answered Sep 23 '22 19:09

zerkms