Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert var to const javascript

Is it possible to convert a var to a const?

Say in a scenario like this:

var appname = ''

function setAppName(name) {
   appname = name  // can I convert this to const now?
}

Basically, this is for a parameter level. Parameter needs to be accessible throughout the file and I want to make it const after first assignment. Is this possible?

To add: If there is any other way besides creating an object with to contain this parameter, it would be better (for a more straightforward solution). I will be working on multiple parameters like this and freezing an object will cause the entire object to freeze. I am hoping to do this on the parameter level.

So either change the parameter to become const. OR (this one I dont think is possible) change the scope of the paramter to global:

function setAppName(name) {
   const appname = name  // can I change the scope and make this global?
}

Thanks.

like image 301
kzaiwo Avatar asked Dec 06 '22 08:12

kzaiwo


2 Answers

Put your app name in an object and freeze it.

let appSettings = { name: "" };
function setAppName(name) {
    appSettings.name = name;
    Object.freeze(appSettings);
}

Freezing prevents adding, removing and modifying the values of the properties in your object so you should call Object.freeze only once after all other settings (if there are more variables you want to make constant) have been set.

like image 187
Nikola Dimitroff Avatar answered Dec 07 '22 21:12

Nikola Dimitroff


You can do this using a object.

const globals = {
    appname: ''
}

function setAppName(name) {
    globals.appname = name;
    Object.freeze(globals)
    // After this point, value of appname cannot be modified
}
like image 21
Varun AP Avatar answered Dec 07 '22 22:12

Varun AP