Is it possible in ES6 to set a variable inside of a try{}
using const
in strict mode?
'use strict'; const path = require('path'); try { const configPath = path.resolve(process.cwd(), config); } catch(error) { //..... } console.log(configPath);
This fails to lint because configPath
is defined out of scope. The only way this seems to work is by doing:
'use strict'; const path = require('path'); let configPath; try { configPath = path.resolve(process.cwd(), config); } catch(error) { //..... } console.log(configPath);
Basically, is there any way to use const
instead of let
for this case?
Advertisement
Answer
Declaring a variable as const
requires you to immediately point it to a value and this reference cannot be changed.
Meaning you cannot define it at one place (outside of try
) and assign it a value somewhere else (inside of try
).
const test; // Syntax Error try { test = 5; } catch(err) {}
On the other hand, both creating it and giving it a value within the try
block is fine.
try { const test = 5; // this is fine } catch(err) {}
However, const
is block-scoped, like let
, so if you do create it and give it a value within your try
block, it will only exist within that scope.
try { const test = 5; // this is fine } catch(err) {} console.log(test); // test doesn't exist here
Therefore, if you need to access this variable outside of the try
, you must use let
:
let configPath; try { configPath = path.resolve(process.cwd(), config); } catch(error) { //..... } console.log(configPath);
Alternatively, although probably more confusingly, you can use var
to create a variable within the try
and use it outside of it because var
is scoped within the function, not the block (and gets hoisted):
try { var configPath = path.resolve(process.cwd(), config); } catch(error) { //..... } console.log(configPath);