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

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

node.js - Javascript set const variable inside of a try block

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

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...