Open In App

JavaScript Error Handling: Unexpected Token

Like other programming languages, JavaScript has define some proper programming rules. Not follow them throws an error.An unexpected token occurs if JavaScript code has a missing or extra character { like, ) + – var if-else var etc}. Unexpected token is similar to syntax error but more specific.Semicolon(;) in JavaScript plays a vital role while writing a programme.
Usage: To understand this we should know JavaScript also has a particular syntax like in JavaScript are concluded by a semi-colon(;) and there are many rules like all spaces/tabs/newlines are considered whitespace. JavaScript code are parsed from left to right, it is a process in which the parser converts the statements and whitespace into unique elements.
 

Therefore JavaScript code is very sensitive to any typo error. These examples given below explain the ways that unexpected token can occur.
Example 1: It was either expecting a parameter in myFunc(mycar, ) or not, .So it was enable to execute this code. 
 






<script>
function multiple(number1, number2) {
    function myFunc(theObject) {
        theObject.make = 'Toyota';
    }
    var mycar = {
        make: 'BMW',
        model: 'Q8-7',
        year: 2005
    };
    var x, y;
    x = mycar.make;
    myFunc(mycar, );
    y = mycar.make;
</script>

Output: 
 

Unexpected end of input

Example 2: An unexpected token ‘, ‘occurs after i=0 which javascript cannot recognize.We can remove error here by removing extra. 
 






<script>
for(i=0, ;i<10;i++)
{
  document.writeln(i);
}
</script>

Output: 
 

expected expression, got ', '

Example 3: An unexpected token ‘)’ occur after i++ which JavaScript cannot recognize.We can remove error here by removing extra ). 
 




<script>
for(i=0;i<10;i++))
{
  console.log(i);
}
</script>

Output 
 

expected expression, got ')'

Example 4: At end of if’s body JavaScript was expecting braces “}” but instead it got an unexpected token else.If we put } at the end of the body of if. 
 




<script>
var n = 10;
if (n == 10) {
    console.log("TRUE");
    else {
        console.log("FALSE");
    }
</script>

Output 
 

expected expression, got keyword 'else'

Similarly, unnecessary use of any token will throw this type of error. We can remove this error by binding by following the programming rules of JavaScript.
 


Article Tags :