user2693928
user2693928

Reputation:

Remove ifs from Javascript code

Can i program without if statements in functional programming in JS?

In Haskell you can do pattern matching: sign x | x > 0 = 1 | x == 0 = 0 in js:

sing = x => {
  if (x > 0) return 1;
  else if (x == 0) return 0
}

I can do shorthand if operator something like this:

sign = x => x > 0 ? 1 (x == 0 ? 0 : x)

Can I make the code shorter without library and ?: operator above ?

Upvotes: 1

Views: 217

Answers (1)

Joel Harkes
Joel Harkes

Reputation: 11661

This might not be the answer your looking for but the shortest way to write this code is:

return !!x+0; 

explanation

  • !!x casts x to a boolean: x>0 == true x = 0 == false;
  • +0 casts to integer: true = 1, false = 0.

But no there is no other style than using ?: operator.

javascript shorthand usefullness

In javascript you have other helpful tricks like:

  • Automatically casting things to thruties or falsies. (when boolean required)
  • Or operator returning the value, easy for null coalescing: var name = null || 'joel' // name = 'joel'

Upvotes: 1

Related Questions