Search code examples
javascriptvariablesassign

How to assign same value in multiple times


I have multiple times in my script, when I need to assign some long value to target variable. For example:

var longVar;

// Now some switch´s case
case:
    longVar = "Some value, which is very, very long";
    break;

// Another case in another switch, so cannot be used writing cases side by side
case:
    longVar = "Some value, which is very, very long";
    break;

But it is not too practic. I am currently setting value with function:

case:
    setVariable();
    break;

function setVariable() {
    longVar = "Some value, which is very, very long";
}

which is (in my opinion) better than writing the value every time. Is it good, or is better, for example, this?:

var valueOfLongVar1 = "Some value, which is very, very long";

// Then in cases
case:
    longVar = valueOfLongVar1;
    break;

Please, is better function() solution, second variable solution, or another one? Thanks for reply


Solution

  • If you assign variables multiple times it's the best to assign the variable's trough constants.

    You shouldn't use methods like you described it.

    Updated: Code Snippet

    const staticText = 'hello world'
    
    let variableText = staticText