Reputation: 904
http://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/ In this link, there are some codes that access to a variable in try catch but when I try this in my server It doesn't work because It's out of scope. how can I do this?
try {
const foo = "bar"
} catch (e) {
console.log(e)
}
try {
console.log(foo) -> is not defined
} catch (e) {
console.log(e)
}
Upvotes: 14
Views: 21453
Reputation: 113435
The author of that post clearly did a mistake there––it happens to all of us.
So, the const
declarations are block-scoped, like the docs say:
Constants are block-scoped, much like variables defined using the let statement. The value of a constant cannot change through re-assignment, and it can't be redeclared.
That's why you cannot access it outside of the try-catch block.
To solve the problem:
Either use var
instead of const:
try {
// When declared via `var`, the variable will
// be declared outside of the block
var foo = "bar"
} catch (e) {
console.log(e)
}
try {
console.log(foo)
} catch (e) {
console.log(e)
}
Or you can declare the variable outside of the try-catch
, using let
:
// Maybe it's clearer to declare it with let and
// assign the value in the first try-catch
let foo;
try {
foo = "bar"
} catch (e) {
console.log(e)
}
try {
console.log(foo)
} catch (e) {
console.log(e)
}
Upvotes: 32