Like any language, JavaScript needs to be written in a specific manner in order to be understood. There’s a certain “syntax” that’s required. And like any language, if the syntax gets sloppy or is written incorrectly, you end up with either inefficient code or even worse, code that doesn’t work.
In this post, I’m going to go over some of the syntax JavaScript uses. I’ll also discuss a few golden pieces of information you need to remember while coding in JavaScript.
Nuggets of Information
First, JavaScript is an interpreted language, meaning its instructions are executed on the fly. They don’t need to be compiled into something else first, in order to operate.
Many of the languages you’ll write today are interpreted languages, so this isn’t something you really need to concern yourself with, especially if you’re like me, who is dabbling in some of the more popular web programming languages. It’s good to know though.
Next, JavaScript is case sensitive. It matters what case you code things in. For example:
var x = 5; var y = 6;
is not the same as:
var X = 5; var Y = 6;
Notice how I capitalized the “X” and the “Y” in the latter two variables. Since one set of variables is lowercase and the other is uppercase, they can be used in the same program, but will apply to different things. Also, if you’re using one of the built-in functions of JavaScript and you alter the case of the function, it will not work.
I mentioned this in my previous post about PHP and the idea is similar to the one in JavaScript – Many programming languages, such as JavaScript, use statements, which are instructions to be executed by the web browser. These statements do things and are obviously necessary.
JavaScript statements end in a semicolon. Here is an example of that:
a = 20; b = 40; c = a + b;
When it comes to whitespace, the same rules that I wrote about in my PHP post apply to JavaScript. And to go over them once more, I’ll tell you that JavaScript doesn’t care about whitespace in its statements, but it does within its strings. Here is an example of whitespace use in JavaScript:
var name = "Jay Gaulard";
The above example is the same as this one below.
var name="Jay Gaulard";
But, both of those examples are different than this one:
var name = "Jay Gaulard";
Notice the space usage around the equal sign in the first two examples and then in between my first and last name in the final example.
Commenting JavaScript is very similar to commenting in PHP. I’ll give you a few examples here:
// this is my name var name = "Jay Gaulard";
It’s common to comment directly above a statement. Or, in the example below, you can comment directly after a statement.
var name = "Jay Gaulard"; // this is my name
Or, you can use multi-line comments.
/* in the line below, you will see my name */ var name = "Jay Gaulard";
Writing JavaScript
When writing JavaScript, you can either write it inline, in between your HTML code or write it in an external file and call it into your HTML. Generally speaking, it’s standard practice you write your code in an external file, but there is some disagreement with that. I’m going to write some pros and cons for each method below.
Inline
– Reduces the number of HTTP requests because no extra file is called.
– Performance may be better if inline JavaScript is short.
– Easier to write inline if testing code.
Here is an example of inline JavaScript:
<script> alert("My name is Jay."); </script>
External
– Greater performance because external file can be easily cached by browsers.
– Easier to maintain because all JavaScript is in one file as opposed to the same code being spread out across multiple HTML files.
– Special characters in JavaScript can cause issues if run inline with HTML.
– If the same JavaScript runs across multiple HTML pages, you have duplicate code.
And here is how you would include a JavaScript file into an HTML page:
<script src="javascript-file.js"></script>
When including your external JavaScript file into your HTML page, you have a choice of whether to place your code at the top of the page or at the bottom. I remember years ago, all I would see is the inclusion of JavaScript at the top of the page, in the head section. Now though, I am seeing it at the bottom more and more. The reason for this is because of the way JavaScript code is parsed. If you include it at the top of the page, your JavaScript will run before the entire page is loaded. If there’s an error somewhere, your page won’t load at all. And as far as where you can place your script tags at the bottom – they generally go right above your closing body tag.
Variables
JavaScript variables are simply containers for data. The way to define a variable is actually quite simple. Here’s an example of a variable:
var name;
Like PHP, there are a number of rules to follow when defining a variable. You can either follow this link to read more about JavaScript variables or read on below. I’ll list those rules here:
All JavaScript variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y), or more descriptive names (age, sum, totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
– Names can contain letters, digits, underscores, and dollar signs.
– Names must begin with a letter.
– Names can also begin with $ and _ (underscore).
– Names are case sensitive (y and Y are different variables).
– Reserved words (like JavaScript keywords) cannot be used as names.
Identifying a variable by itself is simply reserving a space for data to reside. It’s only when you assign your variable a value is it equal to something. Otherwise, your variable is left undefined.
If you’d like to assign a value to your variable, you need to set it with an equal sign (the assignment operator). Please be aware that while this looks like the same equal sign that we’re all used to from math class, it isn’t. This equal sign assigns a value to a variable, it doesn’t make the value equal to the variable. Those are two very different things.
There are two ways to assign a value to a variable:
var name; name = "Jay";
or
var name = "Jay";
In the first example above, I first defined the variable (reserving a space for data to reside) and then I set some data to it. In the second example, I defined the variable and set the value of “Jay” to it all in one line. Either way is fine, but the second is more common.
When setting data to variable, there are a few things to watch out for. First, you are allowed to set integers to a variable, such as:
var number = 200;
You are also allowed to set boolean (true or false) values to a variable, such as:
var question = true;
var question = false;
You may also set a string to a variable, such as:
var name = "Jay";
var name = 'Jay';
It is up to you whether or not you want to use single or double quotes when using a string. The rule is, don’t mix them. Choose one or the other.
Conditional Statements
Asking questions using JavaScript can be fairly straightforward. If you’d like to know if one number is greater than another, you can do that. You can also discover whether one number is greater than or equal to another number. If you’d like one section of code to run if one condition is met, that’s cool – and if you’d like another section of code to run if that same condition isn’t met, that’s cool too.
Below, I’m going to discuss some conditional statements that you can use in JavaScript. If you’ve programmed at all, you’ve most likely heard of these, but if you haven’t, they aren’t too challenging to pick up on.
if Statement
This is, very simply put, a statement that allows a block of code to run if a condition is true.
if (condition) { code that is executed if condition is found to return a true value }
I’ll give you an example of what it looks like:
if (age > 18) { response = "Wow, you are older than I am."; }
In the code above, you’re asking if someone’s age is greater than 18 years. If it is, a response will be generated that says, “Wow, you are older than I am.” If their age is less than 18, nothing will happen because no code will be executed.
else Statement
Let’s say that, instead of nothing happening if someone’s age is not greater than 18, you wanted a response to be generated. In that case, you’d have to use the else statement.
if (condition) { code that is executed if condition is found to return a true value } else { code that is executed if condition is found to return a false value }
Here’s an example of what that looks like:
if (age > 18) { response = "Wow, you are older than I am."; } else { response = "Wow, you are the same age or younger than I am."; }
Now, if the person’s age is anything other than greater than 18, a response will be generated that says, “Wow, you are the same age or younger than I am.”
else if Statement
Here’s a question – What if the person’s age is equal to 18 and you wanted to generate a response for just that? In the examples above, the first generated response was returned only if the age was greater than 18. The second generated response would return if the age was less than or equal to 18. We have yet to program the ability to generate a response for the age being equal to 18 years.
In order to generate a response for a third condition, we’ll need to use the else if statement.
if (condition) { code that is executed if the first condition is found to return a true value } else if { code that is executed if the first condition is found to return a false value and the second condition is found to return a true value } else { code that is executed if both the first and second conditions are found to return false values }
Here’s a simple example of an else if statement, building off the first two examples:
if (age > 18) { response = "Wow, you are older than I am."; } else if (age < 18) { response = "Wow, you are younger than I am."; } else { response = "Hey, we are the same age!"; }
Now, if someone’s age is the same as ours, a response will be generated that says, “Hey, we are the same age!”
Operators
Operator are the tools, or symbols, we use to manipulate values in JavaScript. The values we use operators to manipulate are called operands. An easy example of an operator is the plus (+) symbol. This symbol will add two operands together. Another easy one might be the less than (<) symbol. This symbol performs a check to see if the value of the left operand is less than that of the right. JavaScript supports many types of operators. I'll link to a few websites that have excellent pages that go into decent depth regarding JavaScript operators. - JavaScript Operators at W3Schools
– JavaScript Operators at Tutorials Point
The reason I link to the above sites is because they’ve already compiled everything I would have written here. I actually began writing it and then discovered that I would have been duplicating everything they already have.
Besides simply being aware of the existence of JavaScript operators, you also need to be aware of the precedence they follow in relation to each other.
result = 5 + 5 * 10;
In the example above, the multiplication operator takes precedence over the addition operator, so, in this case, the numbers 5 and 10 will be multiplied before the first 5 will be added to anything. A nice reference for operator precedence can be found here. by the way, the above result is 55.
Now, if you wanted to add the two 5 values together before the 10 was multiplied like it was above, you would add parenthesis around the addition operands.
result = (5 + 5) * 10;
This would change the order of operations and give you a result of 100.
Loops
In JavaScript, a loop can execute a block of code a number of times. This is especially helpful when there is something you need automated, such as a counter or when you’re working with arrays. In order to create loops, you’ll need to utilize a variety of statements. These statements are the driving force behind loops and are:
– for – loops through a block of code a number of times (reference)
– for/in – loops through the properties of an object (reference)
– while – loops through a block of code while a specified condition is true (reference)
– do/while – also loops through a block of code while a specified condition is true (reference)
I’ll go over each type of loop and then give an example of each.
for Loop
You can include three expressions in this loop. They are enclosed in parentheses and separated by semicolons (;). The expressions are followed by a code block that includes a statement or statements to run.
for ([initialization]; [condition]; [final-expression]) statement
for (var i = 0; i < 9; i++) { console.log(i); }
for/in Loop
This loop iterates over the enumerable properties of an object, in random order. For each distinct property, statements can be executed.
for (variable in object) {... }
var obj = {a:1, b:2, c:3}; for (var prop in obj) { console.log("o." + prop + " = " + obj[prop]); } // Output: // "o.a = 1" // "o.b = 2" // "o.c = 3"
while Loop
Creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before the loop is run.
while (condition) { statement }
var n = 0; var x = 0; while (n < 3) { n++; x += n; }
do-while Loop
This loop executes a statement until the condition it’s looping returns a false value. The loop has to occur at least once for the condition to be evaluated.
do statement while (condition);
var i = 0; do { i += 1; console.log(i); } while (i < 5);
Beyond the statements I explained above, there are two others that are worth mentioning. They are break and continue.
break – jumps out of a loop (reference)
continue – jumps over one iteration in the loop (reference)
break
for (i = 0; i < 10; i++) { if (i === 3) { break; } text += "The number is " + i + "<br>"; }
continue
for (i = 0; i < 10; i++) { if (i === 3) { continue; } text += "The number is " + i + "<br>"; }
Functions
The final area of JavaScript I’m going to discuss today is functions, which are a series of statements that have been grouped together to perform a specific task. When you call a function, you execute it.
I’m going to give you an example of what a function looks like and then I’ll go through its parts.
function exampleFunction (number1, number2) { return number1 + number2; }
In the above example, “exampleFunction” is the name of the function. When naming a function, there are some rules to follow. Luckily, the rules are the same as when naming variables, so if you’re interested in what those are, please see the top of this post.
The parts of a function are the “function” keyword, then the name (exampleFunction), the two parentheses. Within these parenthesis, you can hold parameters (number1, number2). Those parameters are separated by a comma. Lastly, the code you’d like to run is placed within two curly braces. In the case of the example above, the code we would like to execute is “return number1 + number2;.”
Now, it’s important to remember that functions don’t need to have data passed into them. You can keep those parenthesis empty, unlike the example above. If you create your function this way, it’ll simply run without any arguments.
Let’s say we have a similar function to the one above, but we don’t have any parameters. It’ll look something like this:
function exampleFunction () { // code i'd like to run }
By itself, this function wouldn’t do anything. It’s not until you call it that it would execute the code inside it. To call a function, you use its name, the parenthesis and end your line with a semicolon.
exampleFunction ();
If we did want to pass in the parameters to make the first example work, we would call it like this:
exampleFunction ( 2, 5 );
The output of that first function when called with those arguments would be “7.” All we’re doing is saying, “I’m giving you the parameters you are asking for as arguments in a function call and you are running the function code block and giving me back the result.
—–
I’m going to stop there. In my next JavaScript post, I’m going to talk about Objects and Data Types. Until next time!
Howdy! I’m at work browsing your blog from my new iphone 3gs! Just wanted to say I love reading your blog and look forward to all your posts! Keep up the fantastic work!