Solution To Unexpected Token Switch Javascript Error

Posted on the 19 March 2016 by Pro Webguru @prowebguru

I was working on a project which involved a good amount of Javascript Work. After writing some switch case, I ran into problem where I was getting "Uncaught SyntaxError: Unexpected token switch" error in Google Chrome console.

Then I started scanning my switch case, line by line. I found the cause of the problem.

While typing I missed out colons (:) in front of the condition.

Just out of curiosity I thought of creating error conditions on the switch case. Just to understand, in which all scenarios we get "Unexpected Token" javascript error related to switch case.

Following are the scenarios in which we get "Uncaught SyntaxError: Unexpected token" javascript switch case related errors.

  1. If colons (:) are missing for the first conditon, then we get "Uncaught SyntaxError: Unexpected identifier" error.
  2. If colons (:) are missing, from 2nd condition onwards, then we get "Uncaught SyntaxError: Unexpected token switch" error.
  3. If there is spelling mistake in "case" keyword, then we get "Uncaught SyntaxError: Unexpected identifier" error.
  4. If the "case" keyword is missing for 1st condition, then we get "Uncaught SyntaxError: Unexpected string" error.
  5. If the "case" keyword is missing after first condition, then we get "Uncaught SyntaxError: Unexpected token :" error.
  6. If the starting curly bracket of the switch condition is missing, then we get "Uncaught SyntaxError: Unexpected token case" error.
  7. If the ending curly bracket of the switch condition is missing, then we get "Uncaught SyntaxError: Unexpected token )" error.
  8. If the starting round bracket of the switch condition is missing, then we get "Uncaught SyntaxError: Unexpected identifier" error.
  9. If the ending round bracket of the switch condition is missing, then we get "Uncaught SyntaxError: Unexpected token {" error.
  10. If both starting and ending curly brackets of the switch condition is missing, then we get "Uncaught SyntaxError: Unexpected token case" error.

I tested all the above code changes in one of the existing codes I was working on.

It was inspected in Google Chrome browser console. Even in other browsers, it might be giving similar kind of errors. I have not tested in other browsers.

Please let me know if I am missing something or if something is wrong.

If you get time to do some testing on switch statement then do let me know the results.

Share with your friends, if you find it useful.