Is it possible in ES6 to set a variable inside of a try{}
using const
in strict mode?
\'use strict\';
const path
I would try to use a temp variable with let
and assign that to a const
var after the try
/catch
and 'delete' the temp var.
'use strict';
let temp;
try {
temp = path.resolve(process.cwd(), config);
} catch (error) {
//.....
}
const configPath = temp;
temp = undefined;
console.log(configPath);
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);
'use strict';
const path = require('path');
const configPath = (function() {
try {
return path.resolve(process.cwd(), config);
} catch (error) {
//.....
}
})()
console.log(configPath);
Use let
. You cannot use const
. const
does not allow you to reassign the declared constant. While it is generally good practice to declare objects like yours with const
, the entire point of doing so is to allow objects to be mutated without allowing them to be reassigned. You are reassigning the object (thus, defeating the purpose of const
), so use let
instead.
let path = require('path');
// Good to go!