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.
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.
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.
In JavaScript (ES5), an if statement does not create a local scope when declaring with var . Local scope is created with a function.
let is block-scoped. var is function scoped. let does not allow to redeclare variables. var allows to redeclare variables.
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);
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With