Chapter 3 of Javascript Novice to Ninja Array Concatenation

Has anyone else been looking following along with the examples in the Array section of chapter 3?

It declares a const variable and then in the examples and then teaches you how to concatenate multiple items on the array.

Declared Array:
const avengers = [Captain America,Iron Man,Thor];

Array concat() Method
avengers = avengers.concat([Hulk,Hawkeye,Black Widow]);

I get the error message:

Thrown:
TypeError: Assignment to constant variable.

Is the book incorrect or just mistaken by not using a variable declared with let instead of const? Am I making a mistake somewhere? I tried declaring another variable and using the same method above and it worked as the book explains.

Any help is appreciated! Newbie here :slight_smile:

Well i’m surprised you managed to declare the first line, considering your array is missing all of the quotation marks that would be required.

You can concat a const, but you cant assign the result to an already-declared constant.

const avengers2 = avengers.concat(["A","New","Array"]) would have worked.

Hi @BrentjFranklin, yes spot on, the reassignment to avengers is indeed a bug in the book; both using let instead and assigning to a new variable are valid fixes (although personally I would avoid reassignments and use const wherever possible).

Another option would be using push() instead which does modify the array it is called on:

avengers.push(...myOtherArray)
1 Like

That’s what I was thinking. The book didn’t specify that you couldn’t concat a variable declared with ‘const’ and just explained how to do it with the variable it already declared with ‘const’ up the page in the examples. It was just a little unclear, so thank you!

Oops, in the example I put here I forgot the quotes, but I actually have them in the code I ran. It didn’t work when I used ‘const’, but it did concat when I declared the variable using ‘let’.

Thanks again!

This is very helpful :slight_smile: much appreciated!

Thanks for the clarification of the book as well!

1 Like

Hey, thanks for pointing this out. I passed it on to HQ, so they can get it fixed.

2 Likes

Thanks for letting us know @BrentjFranklin, I’ve added it to the errata to get fixed.

2 Likes