Javascript set const variable inside try block

Is it possible in ES6 to set a variable inside 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 does not work because configPath is defined out of scope. The only way this works with is to do:

 'use strict'; const path = require('path'); let configPath; try { configPath = path.resolve(process.cwd(), config); } catch(error) { //..... } console.log(configPath); 

Basically, is there anyway to use const instead of let ?

+8
source share
4 answers

Declaring a variable as const requires an immediate indication of its value, and this reference cannot be changed.

So you cannot define it in one place (outside of try ) and assign it a value somewhere else (inside try ).

 const test; // Syntax Error try { test = 5; } catch(err) {} 

On the other hand, creating and creating a value in a try block is great.

 try { const test = 5; // this is fine } catch(err) {} 

However, const is a block cloud, such as let , so if you create it and assign it a value in your try block, it will exist only within this area.

 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 try , you should use let :

 let configPath; try { configPath = path.resolve(process.cwd(), config); } catch(error) { //..... } console.log(configPath); 

Alternatively, although probably more obscurely, you can use var to create a variable in try and use it outside it, because var has a scope within a function, not a block (and gets hoisted ):

 try { var configPath = path.resolve(process.cwd(), config); } catch(error) { //..... } console.log(configPath); 
+31
source

Use let . You cannot use const . const does not allow reassigning a declared constant. Although it is generally recommended that you declare objects like yours with const , the whole task is to resolve mutations of objects without the possibility of reassigning them. You are reassigning the object (thus defeating the const target), so use let instead.

 let path = require('path'); // Good to go! 
+1
source

I would try to use a temporary variable with let and assign it to const var after try / catch and "delete" temp var.

 'use strict'; let temp; try { temp = path.resolve(process.cwd(), config); } catch (error) { //..... } const configPath = temp; temp = undefined; console.log(configPath); 
0
source
 'use strict'; const path = require('path'); const configPath = (function() { try { return path.resolve(process.cwd(), config); } catch (error) { //..... } })() console.log(configPath); 
0
source

Source: https://habr.com/ru/post/1260682/


All Articles