Scope at let to a if statement
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
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);
});