Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope at let to a if statement

Tags:

javascript

Lots of times I am needing to delcare 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.

like image 895
Noitidart Avatar asked Feb 20 '17 15:02

Noitidart


People also ask

What is the scope of an if statement?

if is a conditional statement, which returns true or false based on the condition that is passed in it's expression. By default, if-statement is implemented on only one line, that follows it. But if we put block after the if-statement, it will be implemented on the whole block.

What is the scope of let keyword?

Description. let allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used, unlike the var keyword, which declares a variable globally, or locally to an entire function regardless of block scope.

Does an if statement create a new scope?

In JavaScript (ES5), an if statement does not create a local scope when declaring with var . Local scope is created with a function.

What is the scope of LET and VAR?

let is block-scoped. var is function scoped. let does not allow to redeclare variables. var allows to redeclare variables.


2 Answers

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);
});
like image 95
Carcigenicate Avatar answered Sep 30 '22 08:09

Carcigenicate


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
like image 20
koninos Avatar answered Sep 30 '22 07:09

koninos