Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how use const in try catch block [duplicate]

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 ?

like image 670
pery mimon Avatar asked Mar 29 '17 10:03

pery mimon


1 Answers

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 2 3 options:

Use let:

let foo;
try{
    foo = bar[global.name].foofoo[global.name2];
}catch (err){
    console.log(error(err.message));
}

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 the try:

try{
    const foo = bar[global.name].foofoo[global.name2];
    return foo;
}catch (err){
    console.log(error(err.message));
}

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:

function trycatch() {
    try {
        return bar[global.name].foofoo[global.name2];
    } catch (err) {
        console.log(error(err.message));
        return undefined; // or whatever you want
    }
}

const foo = trycatch(); // === bar[global.name]... if succeeded, otherwise === the return value from the catch block
like image 195
Aron Avatar answered Nov 10 '22 15:11

Aron