The Syntax error in the JavaScript code is very common error type when your write the code. Generally when you write the wrong structure of the JavaScript code , browser will give the syntax error at the time of interpretation. Small syntax error in the JavaScript code on a Web page can stop the script from working correctly.
Consider the following JavaScript code block:
<script type="text/javascript"> function CalculateArea(){ alert(""; } </script>
In the above code, alert statement causes a syntax error because it is missing a closing parenthesis.
In the below I am describing the several things from which you can avoid the syntax errors in your code.
1. Every open parenthesis has its closing parenthesis. This is the common syntax error during writing the script(mostly in jQuery).
2. Make sure the break keyword writes inside an loop or switch statement. See the Picture 1.2
Error cause: Uncaught SyntaxError: Illegal break statement
3. Make sure the continue statement should place within the body of a loop (same as 2).
4. Always remember that the all regular expression pattern should enclosed with the pair of the slash(/) just like string with quotation mark. generally developer lose the last slash in the string pattern for regular expression (see the Picture 1.3).
Error Cause: Uncaught SyntaxError: Invalid Regular Expression: missing /
5. String vale should be initialize with pair of single or double quotation marks(enclosing with starting and ending quotation mark). Consider the following line of wrong script:
Error Cause: Uncaught SyntaxError: Unexpected token ILLEGAL
var str = "Welcome to authorcode; // Uncaught SyntaxError: Unexpected token ILLEGAL
6. Working with array : Any expression that contains the an array element must include both opening and closing brackets. There are many ways to define the array object. If you have little confusion to write the expression that refers the array or array element, You can do some practice on the paper.
Consider the lines, some have syntax errors:
var arr=new Array(); arr[0] = "Welcom"; arr[1] = "to"; // Syntax error: Missing ']' arr[2] = "Author"; var name=arr[0]; // Syntax error: Missing ']' // Syntax error: Unexpected String var arr2 = new Array("welcome""to","AuthorCode");
So you need to good practice on array initialization and how to access an array element.
You can look at the below for creating the array in different ways:
Simple way to create the array object
var Arr = new Array(); Arr[0]="Welcome"; Arr[1]="to"; Arr[2]="AuthorCode";
–Or–
var Arr = new Array("Welcome","to","AuthorCode");
–Or–
var Arr = ["Welcome","to","AuthorCode"];
7. Missing Catch block with Try: Always use the catch or finally block with the try. In error handling there must be a block that should execute in cause of error. If possible use the finally block instead of a catch block.
Error Cause: Uncaught SyntaxError: Missing catch or finally after try
(Continue…..)