Search code examples
javascriptecmascript-6for-of-loop

js looping over a string


can anyone, please, tell me why this code does not work?

var newbie  = [];

for ( var c of "greetings"){
  var newbie += c;
};

I am trying to put characters of "greetings" to an array newbie.


Solution

  • You can't use += to add elements to array. You need to use Array.prototype.push

    Note: Don't use var or let to declare arrays and objects. Use const.

    Reason: We usually don't reassign the arrays and objects using = operator. We generally modify them. So to prevent them from reassigning use const. In a special case when you know that you need to change object's value using = then you may use let

    const newbie  = [];
    
    for (let c of "greetings"){
      newbie.push(c);
    };
    console.log(newbie)

    You can also use split() to convert string into array.

    let str = "greetings";
    const newbie  = str.split('');
    console.log(newbie)