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?
The property of a const object can be change but it cannot be change to reference to the new object.
Constants are block-scoped, much like variables declared using the let keyword. The value of a constant can't be changed through reassignment (i.e. by using the assignment operator), and it can't be redeclared (i.e. through a variable declaration).
The curly braces around the variable name is called Destructuring assignment, and const {PI} = Math; will translate to const PI = Math.PI.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With