javascriptprimitive-types

Why do String methods like `.toLowerCase()` not change the value of the variable?


Why does the following code work shouldn't title be set to lowercase causing the second if statement to fail?

var title = 'RANDOM_LETTERS';
if(title.toLowerCase() == 'random_letters')
{
     //This will fire
}

if(title == 'RANDOM_LETTERS')
{
      //This will still fire as the variable was not saved to lowercase
}

Solution

  • You aren't changing the value of the variable. You can prove it by printing out the value of the variable at each step.

    var title = 'RANDOM_LETTERS';
    
    console.log(title);
    // Here, title is "RANDOM_LETTERS"
    
    if(title.toLowerCase() == 'random_letters')
    {
        console.log(title);
        // Here, title is still "RANDOM_LETTERS"
    }
    
    console.log(title);
    // Here, title is "RANDOM_LETTERS"
    
    if(title == 'RANDOM_LETTERS')
    {
        //We get to this line, our title is still "RANDOM_LETTERS"
    }
    

    According to the docs (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase), the value of the string using this method is not affected.