Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 777
Justin Avatar asked Dec 02 '16 04:12

Justin


People also ask

Can we change const variable in JavaScript?

The property of a const object can be change but it cannot be change to reference to the new object.

What is const {} in JS?

Constants are block-scoped, much like variables declared using the let keyword. The value of a constant can't be changed through reassignment (i.e. by using the assignment operator), and it can't be redeclared (i.e. through a variable declaration).

What does const {} mean in node JS?

The curly braces around the variable name is called Destructuring assignment, and const {PI} = Math; will translate to const PI = Math.PI.


1 Answers

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); 
like image 192
nem035 Avatar answered Sep 22 '22 02:09

nem035