0

I have a function that is returning an "Unexpected Token New" error at line 3. I am not sure why this is happening. It seems correct to me.

function flat_array(array){

 var new = [];

  for(var i = 0; i < array.length; i++)
  {
      new = new.concat(array[i]);
  }

  return new;
}
Thomas C
  • 75
  • 1
  • 1
  • 5
  • 5
    new is a reserved keyword.. change the variable name and it will work.. – Jaydeep Jul 31 '19 at 14:18
  • Sidenote: `Array.flat()` and `Array.flatMap()` are being implemented in modern browsers, so depending on which browsers you support, you might want to use the native `.flat()` method. – Shilly Jul 31 '19 at 14:22

4 Answers4

2

new is a reserved word for constructing objects (note the highlighting here even):

obj = new Object()

It can't be used as a name for variables. Change it to something else.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
1

you can't name a variable called new as the word is reserved (like in most programming languages)

I'd suggest calling your variable "newObj" or something like that if you really want the "new" part, but you can't call a variable with a reserved word. Here's a list of keywords in JavaScript

Sirmyself
  • 1,464
  • 1
  • 14
  • 29
0

new is a reserved word. You cannot use it as a name of a variable. Changing your code to below should work fine:

function flat_array(arr){
  var result = [];

  for(var i = 0; i < arr.length; i++) {
      result = result.concat(arr[i]);
  }

  return result;
}
Doğancan Arabacı
  • 3,934
  • 2
  • 17
  • 25
0

new is the reserved word in JS. You can't use it as a variable name. Here is the list of the JS reserved words: https://www.w3schools.com/js/js_reserved.asp

You can find what's the purpose of new here: What is the 'new' keyword in JavaScript?

Sami Ahmed Siddiqui
  • 2,328
  • 1
  • 16
  • 29