Javascript Syntax
October 3rd, 2008Before you can start writing javascript, you must understand javascript syntax. The best way to learn javascript syntax thoroughly is to just begin coding javascript. But, in order to begin, you need a starting point, so I’ll give you a few ground rules.
Javascript Syntax Ground Rules:
1) Locations: You can write javascript in several different locations, but you can only write in these locations. If you write javascript anywhere else, it will not work. Four locations–in a .js file (referenced from your HTML page), between <script type=”text/javascript”>*javascript here without stars*</script> tags, in event handlers, and in functions (which are already in a .js file or between the script tags).
2) Commands: End all javascript commands with a semicolon. Most programmers write new commands on new lines like so:
alert(’hi’);
alert(’hello’);
But you can also write commands on the same line (separated by a semicolon) like so:
alert(’hi’); alert(’hello’);
3) Variables: My own experience has taught me that you should declare variables (let’s say ‘x’) like this:
var x = ‘this equals x’;
Prefix your variable with a var declaration. My experience has been that some browsers require the declaration. When you refer to the same variable later, you can just use the variable by itself, like this:
var john = x;
The above command would set a new variable equal to x or in this case specifically ‘this equals x’. So, if you alerted john like this–alert(john);–the alert would say ‘this equals x’. Notice that the x has no quotes around it. Which leads us into our next ground rule.
4) Strings: Quotes should surround strings not variables. Often, we set variables to a certain string value. Example:
‘this is a string’
var x = ‘this is a string’;
Quotes should not surround variables. Example:
x <== x is a variable (if this were on the same page as the above script, x would be equal to ‘this is a string’)
var another_var = x; <== another_var is set to x (again, assuming this were on the same page as the above script, now another_var would be equal to ‘this is a string’)
Now, you have a little groundwork, start coding!
Did I leave something out? Leave a comment.