Thomas C
Thomas C

Reputation: 75

Javascript Issue with function

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;
}

Upvotes: 0

Views: 68

Answers (4)

Sami Ahmed Siddiqui
Sami Ahmed Siddiqui

Reputation: 2386

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?

Upvotes: 0

Sirmyself
Sirmyself

Reputation: 1564

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

Upvotes: 1

Doğancan Arabacı
Doğancan Arabacı

Reputation: 3992

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;
}

Upvotes: 0

Carcigenicate
Carcigenicate

Reputation: 45826

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.

Upvotes: 2

Related Questions