Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does this variable not change?

Tags:

javascript

in this piece of code:

function change(s)
{
  var number = s.replace(/\s+/g, '');
  for(var i = 0; i < number.length ; i++)
  {
    console.log(number[i]); //Line1
    number[i] = '1';
    console.log(number[i]); //Line2
  }
}

the results of Line1 and Line2 are both the same(they return "2") ! what is going on here?!

like image 488
Pooya Avatar asked Dec 12 '22 12:12

Pooya


1 Answers

Strings in JavaScript are immutable. You can't change them so this line does nothing

number[i] = '1';
like image 75
Denys Séguret Avatar answered Dec 27 '22 01:12

Denys Séguret