const is a block level variable so when i try suspect code
try{
const foo = bar[global.name].foofoo[global.name2];
}catch (err){
console.log(error(err.message));
}
const is hide in the {}
but
const foo ;
try{
foo = bar[global.name].foofoo[global.name2];
}catch (err){
console.log(error(err.message));
}
not working either because const
must be init on declaration.
So how should I using const
in try..catch
block ?
You've hit the nail on the head, because of block scoping you can't declare a
const
in a try catch block and use it outside the block.You have
23 options:Use
let
:Or if there is very little code to come after the try catch block, and it all depends on the success of the
try
, you can put the rest of the code in thetry
:EDIT
Option 3 inspired by @Yury Tarabanko's comment: if possible modularise the try catch part into its own function, the output of which should be the value of the new
const
: