Explanation of Unexpected Tokens
An “unexpected token” error usually occurs when the JavaScript engine encounters a character or symbol that does not fit the expected syntax rules. The error message suggests using ‘;’ to separate expressions on the same line, which means adding semicolons at appropriate places.
Example 1:
Let’s consider the following code:
let x = 5
let y = 10
In this example, the JavaScript engine encounters the second line without a semicolon at the end, which leads to the unexpected token error. To fix this, we can add a semicolon:
let x = 5;
let y = 10;
Example 2:
Another scenario could be using a period (.) instead of a comma (,) to separate object properties:
let person = {
name: 'John'
age: 25
}
In this case, the JavaScript engine expects a comma after the ‘name’ property but finds the unexpected token ‘age’. To resolve this issue, we should use a comma instead:
let person = {
name: 'John',
age: 25
}
Remember to carefully check your code for missing or misplaced punctuation, as they can often cause unexpected token errors.