-1

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.

3 Answers3

1

Your code does not work because you need to use push() for adding an element to the last index of the array.

var newbie  = [];
for ( var c of "greetings"){
  newbie.push(c);
};

console.log(newbie);

Alternatively, you can use split() as a short hand to get that same output:

var text = 'greetings';
var res = text.split('');
console.log(res);
Ankita Kuchhadiya
  • 1,255
  • 6
  • 16
1

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)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
  • 1
    Re: "*Don't use var or let to declare arrays and objects. Use const.*" Why? How is declaring a variable as *const* then immediately modifying it consistent with the concept of a constant? – RobG Dec 26 '19 at 11:50
  • @RobG Updated. Please check. – Maheer Ali Dec 26 '19 at 11:54
  • _How is declaring a variable as const then immediately modifying it consistent with the concept of a constant?_ declaring array or object using `const` makes sense because whole point of declaring something with `const` is that variable won't be reassigned. Array or object declared with `const` doesn't means array or object itself can't be modified – Yousaf Dec 26 '19 at 11:57
  • @Yousaf—constants have been used in mathematics for a very long time for values that will not be changed (i.e. held constant), such as pi and Planck's constant, or factors for converting from say miles to kilometres. Using *const* for objects that **will** change is not consistent with the concept of a constant, devaluing its ability to signify a value that doesn't change. You might as well just use *var* for everything. – RobG Dec 27 '19 at 03:35
0

In the loop avoid this statement var newbie += c; and use newbie.push(c).

Reason : A var newbie has already been created as a global variable , you need not create it again in the loop. Use the existing newbie array

kooskoos
  • 4,622
  • 1
  • 12
  • 29
Gopi krishna
  • 308
  • 1
  • 9