Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
326 views
Welcome To Ask or Share your Answers For Others

1 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) {}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...