user3501825
user3501825

Reputation: 11

Unexpected token error in for loop, why?

var ccode = ['EUR', 'BRL', 'RUB', 'KRW', 'RON', 'CHF'];
  var i;
  for (var i = 0; i < ccode.length; i++) {
     var ccode[i] = fx.convert(amount, {to: 'ccode[i]'});
  }

The bit above var ccode[i] is causing an error

SyntaxError: Unexpected token '['. Expected ';' after variable declaration.

I am still new to JS so please bear with me.

I am editing my question here since people asked why I was re-declaring var ccode[i] and its because I need to output this:

var EUR = fx.convert(amount, {to: "EUR"});

Upvotes: 0

Views: 2929

Answers (3)

JackDev
JackDev

Reputation: 5062

I would suggest using an array map:

var ccode = ['EUR', 'BRL', 'RUB', 'KRW', 'RON', 'CHF'];
ccode = ccode.map(function(code) {
  return fx.convert(amount, {to: code})
})

Upvotes: 0

Jagdish Idhate
Jagdish Idhate

Reputation: 7742

Its not about declaring ccode twice, as variable declaration syntax is wrong

var ccode[i]; should not be array, see for reference

You should remove var.

var ccode = ['EUR', 'BRL', 'RUB', 'KRW', 'RON', 'CHF'];
  var i;
  for (var i = 0; i < ccode.length; i++) {
     ccode[i] = fx.convert(amount, {to: 'ccode[i]'});
  }

Upvotes: 0

Machigatta
Machigatta

Reputation: 118

var ccode = ['EUR', 'BRL', 'RUB', 'KRW', 'RON', 'CHF'];
var i;
  for (i = 0; i < ccode.length; i++) {
     ccode[i] = fx.convert(amount, {to: 'ccode[i]'});
  }

ccode is already declared.. no need to use var

Upvotes: 1

Related Questions