how use const in try catch block

16,097

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
Share:
16,097
pery mimon
Author by

pery mimon

in Days: senior web client developer. Expert in javascript and Angular, Vue, React in Night: Still web client developer. Expert in javascript & CSS. writing my secret project and manage my life Some of my useful answers ( by content, not vote ) Record and export Canvas as video file Saving and Restoring caret position for contentEditable div Simple recursive deep cloning object | array How to set DOM element as the first child? JavaScript - How do I get the URL of the script being called? React Js conditionally applying class attributes How to compare software version number using js? (only number) Replace element contents with document fragment javascript

Updated on June 14, 2022

Comments

  • pery mimon
    pery mimon about 2 years

    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 ?