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) )
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.
Conclusion: If only is faster than If-Else construct. Just use the one that's most readable (presumably the if/else one).
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.
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!
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With