Search code examples
javascriptvariables

How to change a variable


How to change a variable once it is set like this:

const myVar = 'test';

I have tried the following:

myVar = 'test2';

const myVar = 'test3';


Solution

  • Const are constants. They are not intended to be changed once they are set with their initial value. Simply use a standard variable type without specifying const.

    var myVar = 'test';
    myVar = 'another';
    
    const site = 'Stackoverflow';
    site = 'Google'; // this will throw an error in Firefox and Chrome (but does not fail in Safari)
    
    const site = 'fb';// trying to redeclare a constant throws an error
    
    console.log(myVar); //outputs another
    console.log(site); //Stackoverflow
    

    Reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/const