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.
- If colons (:) are missing for the first conditon, then we get "Uncaught SyntaxError: Unexpected identifier" error.
- If colons (:) are missing, from 2nd condition onwards, then we get "Uncaught SyntaxError: Unexpected token switch" error.
- If there is spelling mistake in "case" keyword, then we get "Uncaught SyntaxError: Unexpected identifier" error.
- If the "case" keyword is missing for 1st condition, then we get "Uncaught SyntaxError: Unexpected string" error.
- If the "case" keyword is missing after first condition, then we get "Uncaught SyntaxError: Unexpected token :" error.
- If the starting curly bracket of the switch condition is missing, then we get "Uncaught SyntaxError: Unexpected token case" error.
- If the ending curly bracket of the switch condition is missing, then we get "Uncaught SyntaxError: Unexpected token )" error.
- If the starting round bracket of the switch condition is missing, then we get "Uncaught SyntaxError: Unexpected identifier" error.
- If the ending round bracket of the switch condition is missing, then we get "Uncaught SyntaxError: Unexpected token {" error.
- 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.