Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use if-else conditon in arrow function in javascript?

Tags:

javascript

Is it possible to use an if else condition in JavaScript using an arrow function?

like image 716
avadhoot Avatar asked Jun 04 '16 07:06

avadhoot


People also ask

Can you use if with 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.

How do you write IF and ELSE condition in JavaScript?

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.

What does () => mean in JavaScript?

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.

How do you pass parameters in arrow 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.


1 Answers

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' 
like image 198
Matt Way Avatar answered Sep 26 '22 10:09

Matt Way