Thursday, March 28, 2024

JavaScript Basics Part 2


This is the second in a 10-part series that will introduce you to the JavaScript language. In the last article, we wrote a simple script that involved variables, alerts, prompts, string concatenation and some basic arithmatic operators. To test the script we wrote, you can click here. If you don’t fully understand any of these concepts, you should read, or re-read the first article.

If you tested the script we wrote in the last article, you might have noticed that the result you got from the prompt needs some validation. When the script asks you how many apples you would like to eat, you could enter a number greater than 5, a number less than 0, or something that isn’t even a number at all. In each of these cases we would like to inform our user that what they entered is not valid.

Since there are only 5 apples in our script, that is the most apples that our user can take. So we will start by checking to see if the number they entered is greater than 5.

var apples = 5;
alert('There are currently ' + apples + ' apples!');

var eat    = prompt('How many apples would you like to eat?', '1');

var eaten  = parseInt(eat);
if(eaten > 5){
	alert('Sorry, but there are only 5 apples.  You can not eat ' + eaten + ' apples!');
} else {
	apples    -= eaten;
	alert('Now there are only ' + apples + ' apples!');
}

The main concepts that we are introducing here are the “if” and “else” statements. If and Else statements are fairly simple to understand. If you look at the code above, you could say “If the user selected more than 5 apples to eat, tell them that there are not that many apples. Otherwise, let them eat as many apples as they entered”.

The basic syntax for an if / else statement is:

if(condition){
	// code to execute if condition is true
} else {
	// code to execute if condition is false
}

You should notice the open and close brackets, { and } in the above code. The open bracket tells the code where to start a certain block of code, and the close bracket tells the code where to end. So anything between { and } is executed as part of your if statement. You should notice that the close bracket for the if statement is immediately before the keyword “else”. The else statement then has its own set of brackets and thus its own block of code to execute.

The slashes, //, in the above example tell our code that we have a comment. A comment is part of your code that is not executed. It is generally used to describe functionality of the actual code so that you do not have to read through code to figure out what it is doing. If, for example, you had a very lengthy piece of code that validated inputs on a form, it would be a good idea to place a comment saying something like “The following code validates the user input for the contact form”. This way if anyone else looks at your code, or if you yourself look at your code several months down the line, you know what it does right away.

There are two ways to write a comment in JavaScript. The first, as you have already seen, is with //. Anything following a // on a line is considered to be a comment, and is thus ignored when your code is executing. The other way is with /* and */. If you place these in your code, anything between them is ignored.

// this is a one line comment.

/*
if you need a longer comment, as is often the case,
it is usually a good idea to use a "block comment".

This comment is a block comment, and the entire
thing is ignored when your code is executed.
*/

For shorter scripts, comments are not always necessary. When your code gets longer, however, they become a necessity. Programmers will very often have to look through thousands of lines of code trying to find one bit of functionality to fix. If the code is well commented, it is fairly easy to figure out almost exactly where the code you are looking for is located.

Going back to our original if statement,

if(eaten > 5){
	alert('Sorry, but there are only 5 apples.  You can not eat ' + eaten + ' apples!');
} else {
	apples    -= eaten;
	alert('Now there are only ' + apples + ' apples!');
}

You will notice that our condition is “eaten > 5”. The > sign means “greater than”, so this condition means “if eaten is greater than 5”. Similarily, < stands for “less than”. There are two other symbols along these lines, >= and <=, that stand for “greater than or equal to” and “less than or equal to” respectively. You will notice in the above code that if the user selected more than 5 apples to eat, we tell them this. Now only if they selected less than 5 apples, we subtract this number from the current number of apples and then tell them how many are left.

There are two other cases that we discussed, however. What if the user enters a number less than 0? What if they enter a value that is not a number? The first case you should now be able to work out for yourself. The second case requires the addition of another built-in function, “isNaN”. When you are trying to convert something to a number, as the parseInt function does, a value of “NaN” is returned if the function fails. NaN stands for “Not a Number”. If you called parseInt on the value “apple”, for example, you would get NaN back because the word “apple” is not a number.

var apples = 5;
alert('There are currently ' + apples + ' apples!');

var eat    = prompt('How many apples would you like to eat?', '1');

var eaten  = parseInt(eat);
if(isNaN(eaten)){
	alert('You must enter a valid number of apples!');
} else if(eaten > apples){
	alert('Sorry, but there are only ' + apples + ' apples.  You can not eat ' + eaten + ' apples!');
} else if(eaten < 0){
	alert('Sorry, but you can not eat less than 0 apples!');
} else {
	apples -= eaten;
	alert('Now there are only ' + apples + ' apples!');
}

By now, all of this should make sense to you. First we check to see if they entered an invalid value. If they did, we tell them. We then check to see if they entered more apples than exist, and then if they entered a number less than 0. If all of these checks pass, we let them eat as many apples as they entered. The one adjustment we made to our code was to change “if(eaten > 5)” to “if(eaten > apples)”. We did this so that if we later change the number of apples we have, “var apples = 5;”, we only have to change it in one place. Getting into a habit of always using variables in your code is a good idea. If you “hardcode” values, like we previously had in “if(eaten > 5)”, you will very often end up searching for those hard-coded values for hours making sure you have found and changed them all.

If the user entered an invalid value in any way, you might want to ask them again how many apples they want to eat. One way to do this would be to copy all of your code several times. This usually is not a good idea, however. What if the user enters an invalid value again, or again after that? You could keep copying your code but you can see how this would get very inefficient and make your code very difficult to maintain.

The proper direction to go in this case is to use what we call a function. A function contains a block of code that does a certain task. You have already seen functions in use. “alert”, “prompt”, “parseInt” and “isNaN” are all functions that are built into the JavaScript language. The advantage of using a function is that you can execute the same block of code again and again without having to copy your code. You execute a function by writing its name followed by a set of parenthesis, (), with any values sent to the function in between the parenthesis.

var apples = 5;

function eatApples(){
	alert('There are currently ' + apples + ' apples!');

	var eat    = prompt('How many apples would you like to eat?', '1');

	var eaten  = parseInt(eat);
	if(isNaN(eaten)){
		alert('You must enter a valid number of apples!');
		eatApples();
	} else if(eaten > apples){
		alert('Sorry, but there are only ' + apples + ' apples.  You can not eat ' + eaten + ' apples!');
		eatApples();
	} else if(eaten < 0){
		alert('Sorry, but you can not eat less than 0 apples!');
		eatApples();
	} else {
		apples -= eaten;
		alert('Now there are only ' + apples + ' apples!');
		if(apples > 0){
			if(confirm('Would you like to eat more apples?')){
				eatApples();
			}
		} else {
			alert('All of the apples are now gone!');
		}
	}
}

Here we wrap all of our code in a function called eatApples. You will notice that each time a user enters an invalid value, we re-call our eatApples function, “eatApples();”, so that they can enter a new value. Once they enter a valid number, we either let them eat more apples or if the apples are all gone, we tell them this. We introduce one new function here, “confirm”. The confirm function simply gives an “OK or Cancel” prompt to the user. If they click “OK”, it returns a value of true. If they click “Cancel” or just close the window, the confirm function returns a value of false. So in our example, the eatApples function is only called again if the user clicks “OK”.

One final thing to point out in this lesson is variable scope. You might have noticed that in our previous example, we moved our apples variable outside of our eatApples function. This makes our “apples” variable a “global variable”, meaning that the same variable is accessible from any function. The “eat” variable, on the other hand, is a local function and only exists inside of our eatApples function. In addition, each time we re-call the eatApples function, the eat variable no longer exists until we define it again with our prompt.

To see this concept in action, we will write two simple counting functions:

function counting1(){
	var count = 0;
	count++;

	alert(count);
}

var count = 0;
function counting2(){
	count++;

	alert(count);
}


If you click each button a few times you should notice that counting1 always gives you the same value, 1. counting2, on the other hand, gives you an incrementing number. Why does this happen? Well, let’s just look at counting1 first. You’ll notice that each time counting1 gets executed, the first thing that happens is that we create a count variable and set it equal to 0. Our next line adds 1 to our count variable.

The ++ operator is something we have not seen before. count++ simply adds 1 to count. In other words it is exactly the same as writing “count += 1” or “count = count + 1”. Since adding 1 to something is a very common action in programming, there is a method specifically for doing that. The — operator likewise subtracts 1 from a variable: “count–“.

Each time our counting1 function performs “alert(count)”, it is telling us the value of our new count value which has just been set to 0+1.

Now let’s look at counting2. You’ll notice that the count variable in this case is outside of our function. Even before we call the function, count is set to 0. When you call counting2, the first thing you do is add 1 to our count variable. Since we are not resetting count to 0 again, like we were with counting1, our count variable keeps going up and it works like we would expect it to.

That’s it for this lesson! You now have a basic understanding of some of the fundamentals of programming and of JavaScript in particular. Next time we will introduce loops and forms.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured