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

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'

As you've probably found, the body of an arrow function without braces can only be a single expression, so if statements are not allowed.

Statements are allowed in arrow functions with braces though, like this:

const func = () => {
    if (...) ...
}

for a single 'if' condition you may use a shortcut syntax.

Imagine you need to execute a doThis() function only if a > 10 :

a => a > 10 && doThis()

Tags:

Javascript