Javascript set const variable inside of a try block
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);