2
var array = [1, 2, 3, 4, 5, 6];

//print the reverse of an array

function printReverse(array){
    for(i = array.length - 1, i >= 0, i--){
        console.log(array[i])
    }
}
printReverse(array);

The code above is supposed to take an array and print it to the console in the reverse order. It throws me an error and I can't figure out why.

Seth Harlaar
  • 124
  • 2
  • 2
  • 13

1 Answers1

5

You're using commas , instead of semi-colons : in your for loop. It should be:

for(i = array.length - 1; i >= 0; i--) {

You're getting the Unexpected Token error because the compiler was expecting there to be three expressions, separated by semi-colons. When you write it with commas it thinks the whole line is one expression, since a comma is not a delimiter in that case.

As was mentioned in a comment, using a javascript linter such as JSHint is a good idea, especially if you're new to the language. A linter will inspect your code and point out any issues with tidiness, consistency, compatibility and common mistakes. Linters can be installed as build tools or directly into many code editors to catch errors as you write.

Soviut
  • 88,194
  • 49
  • 192
  • 260
  • alternatively you can install eslint/other static checks for your editor to catch these types of syntatical errors – teaflavored Jan 21 '17 at 23:03