Is it possible to use an if else
condition in JavaScript using an arrow function?
Is it possible to use an if else condition in JavaScript using an arrow function? Yes, there's nothing special about it. You use it exactly the same way as in an ordinary function. Arrow functions are just a shorthand, but the body can be normal.
In JavaScript we have the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.
It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.
The arrow function can be shortened: when it has one parameter you can omit the parentheses param => { ... } , and when it has one statement you can omit the curly braces param => statement . this and arguments inside of an arrow function are resolved lexically, meaning that they're taken from the outer function scope.
An arrow function can simply be seen as a concise version of a regular function, except that the return
is implied (among a few other subtle things you can read about here). One nice way to use an if/else is though a ternary. Take this regular function:
function(a){ if(a < 10){ return 'valid'; }else{ return 'invalid'; } }
The equivalent in an arrow function using a ternary is:
a => (a < 10) ? 'valid' : 'invalid'
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