Noitidart
Noitidart

Reputation: 37238

Does JS have "if (let foo ...) {...}"? / How can I scope a variable declaration to inside an if statement including the condition part?

Lots of times I am needing to declare a variable just for a truthy if statement. For example:

let entry;
entry = entries.find(....);
if (entry) {
   // use entry
}

// i dont need entry here

I tried combintations similar to for (let i=0; ...) like this:

if (let entry = entries.find(....)) {
   // user entry
}

But it's not working. If I use var instead of let it works but the variable it hoisted so its not limited to that if statement block.

Upvotes: 21

Views: 19800

Answers (3)

starball
starball

Reputation: 50484

At the time being, you can work around this by declaring the variable before the if statement, and wrapping that declaration and the if statement in a block. Ex.

{
  let foo = getValue();
  if (foo) {
    // ...
  }
}

See also https://github.com/tc39/proposal-Declarations-in-Conditionals, which proposes syntax allowing this:

if (let foo = getValue()) {
  // ...
}

Upvotes: 4

Carcigenicate
Carcigenicate

Reputation: 45750

This is probably an idiom that was never made for JS, but just for kicks, here's a helper that could be used, although the other answer is probably more correct.

This was inspired by Clojure's when-let that does exactly what you're looking for, but doesn't require a function since it's a macro:

function ifDo (maybeTrueVal, doF) {
    if (maybeTrueVal) {
        doF(maybeTrueVal);
    }
}

ifDo(entries.find(....), (truthyVal) => {
    console.log(truthyVal);
});

Upvotes: 9

koninos
koninos

Reputation: 5337

Since let creates a block scope, you need to create another block around it to limit its scope.

A block statement is used to group zero or more statements. The block is delimited by a pair of curly brackets.

let x = 1;
{
  let x = 2;
}
console.log(x); // logs 1

Alternatively you can use an Immediately Invoked Function Expression:

(function () {
    let entry = 6;

    if (entry) {
        console.log(entry);
    }
 })()
// Variable entry is not accessible from the outside scope

Upvotes: 10

Related Questions