Skip to content Skip to sidebar Skip to footer

How To Use Let Declarations As Expressions?

I want to use let expressions, but the following code doesn't work: true ? (let x=1, let y=2, x+y) : (let x=3, let y=4, x-y); // SyntaxError How am I supposed to do this?

Solution 1:

The following is a kind of sugar...

let x = 1console.log(x)

Without var, const, or let, we could use functions to bind variables

// let x = 1; console.log(x);
(x =>console.log(x)) (1)

Of course this works if you have multiple variables too

(x =>
  (y =>console.log(x + y))) (1) (2)

And because JavaScript functions can have more then 1 parameter, you could bind multiple variables using a single function, if desired

((x,y) =>console.log(x + y)) (1,2)

As for your ternary expression

true
  ? ((x,y) =>console.log(x + y)) (1,2)
  : ((x,y) =>console.log(x - y)) (1,2)
// 3false
  ? ((x,y) =>console.log(x + y)) (1,2)
  : ((x,y) =>console.log(x - y)) (1,2)
// -1

None of this requires any fanciful syntax or language features either – the following would work on pretty much any implementation of JS that I can think of

true
  ? (function (x,y) { console.log(x + y) }) (1,2)
  : (function (x,y) { console.log(x - y) }) (1,2)
// 3false
  ? (function (x,y) { console.log(x + y) }) (1,2)
  : (function (x,y) { console.log(x - y) }) (1,2)
// -1

Post a Comment for "How To Use Let Declarations As Expressions?"