JavaScript: If, Else, and User Input

Now we know how to store values in variables, it's probably worth learning about how to get user input and store this in variables, and also how we can control the logic of our script depending on the contents of certain variables (which is extremely powerful).

User Input

Firstly: user input. There are a lot of ways to take input from the user on the web, ranging from textboxes to pop-up boxes, and in this lesson we are just going to use a very simple command to get input from the user (which isn't really used very much in the web these days, but it's good for while we're learning).

The function we are going to use is called prompt, and it does exactly what it sounds like it does. When we call the function we simply pass it a string and it will present the user with the string we entered and a textbox to enter a value in. The prompt function returns whatever value the user has inputted -we'll learn more about returning values later on when we learn about functions, but basically it just means that if we treat the function as a value, it will give us the value that it's been told to return (in the case of the 'prompt' function, it will give us what the user has entered if we treat the function like a regular value). So let's just prompt the user for their name, and store it in a variable called 'name':

1
var name = prompt('What is your name?');

If you want to check if this works, we could simply alert 'name' after we get it. If you want to quickly test this, I've put the code in a JSFiddle frame below.

We could also prepend values to this if we wanted, by simply sticking two strings together - this is done using the '+' operator like so:

1
2
var name = prompt('What is your name?');
alert('Hi, ' + name + '. Welcome to my awesome website!');

If and Else Statements

So now we know how to get input from our user - let's introduce the extremely important concept of 'if' statements to do certain things depending on the contents of variables. For now, we're just going to be checking if two values are exactly equal - we can check other conditions (greater than, less than etc.) too, but that's for a later tutorial.

So whenever we want to start a chain of comparison, we start with the keyword: if. We then specify whatever we want our condition to be in some regular brackets (we'll learn how to formulate conditions in just a sec), and then we specify the code we want to be executed if the condition is true in curly brackets. So at the moment we have a concept that looks something like this:

1
2
3
4
if(ConditionGoesHere)
{
	//Code to execute if condition is true here.
}

Just as a quick side-note, the "//" I've put in is what's called a comment. It doesn't make a difference to the actual JavaScript code when it's run and is just to help explain pieces of code and leave little notes (this is especially useful if your working in a team - you can find plenty of advantages of commenting code with a simple Google search). The comment has to go after, and on the same line as the "//" though - if you want to do multi-line comments, you start the comment with "/*" and end it with "*/". Like so:

1
2
3
4
5
6
7
if(ConditionGoesHere)
{
	/*
	Notice how this comment takes up
	multiple lines?
	*/
}

But anyway, let's get back to what we were doing. The simplest way to formulate a condition for our 'if' statement is to have the value we want to compare to something, then a comparison operator (so in our simple example, we'll want the "is equal to" operator) and then the value we want to compare the first value to. The only comparison operator we will use in this tutorial, is the "is equal to" operator, which is expressed with two equals signs next to each other: ==.

To trigger the code inside the 'if' statement, our condition must be true. This either means that we used a comparison operator such as "==", or we've got some kind of an expression (e.g. a function) which returns a value -- if you put a function in the "condition" area that returns true, then the code inside the 'if' statement will execute.

So as a basic example, let's compare '5' to '2' (rather pointless as 5 will never equal 2, but nevertheless it's an OK example):

1
2
3
4
if(5==2)
{
	//Do stuff here if 5==2 (which it never will)
}

This shouldn't be too difficult to wrap your head around, and so let's move on from merge with the code we created earlier to check if the user's name is a certain value:

1
2
3
4
5
var name = prompt('What is your name?');
if(name=='Joe') //If the name is 'Joe'
{
	//Do something special here.
}

So in the case that the user's name is Joe, we might want to display a special 'alert' box. We could do this by simply calling the alert function inside the curly brackets that specify the code segment which will only be triggered if name=='Joe':

1
2
3
4
5
var name = prompt('What is your name?');
if(name=='Joe') //If the name is 'Joe'
{
	alert('Wow, cool - my name is Joe too!');
}

And it's as simple as that! If we run that code, it should all work as we intended! But what if we wanted to do something else if the user's name matched another case? Well we could simply write another 'if' statement under the one we already have, but that isn't the best way to do things...

1
2
3
4
5
6
7
8
9
var name = prompt('What is your name?');
if(name=='Joe') //If the name is 'Joe'
{
	alert('Wow, cool - my name is Joe too!');
}
if(name=='Fred') //If the name is 'Fred'
{
	alert('Fred is a pretty generic name...');
}

The above code is reasonably inefficient as it's going to check if the user's name is 'Fred', even if their name has already been matched as 'Joe', and there is a better way to accomplish what it's trying to do. It's called 'else if'.

This allows us to link this 'if' statement, with our previous one - therefore wiping out the inefficiency problem that we had! All we have to do is write else if after the ending curly bracket of the last 'if' statement, and then follow the same format we used for the first if. So in this example:

1
2
3
4
5
6
7
8
9
var name = prompt('What is your name?');
if(name=='Joe') //If the name is 'Joe'
{
	alert('Wow, cool - my name is Joe too!');
}
else if(name=='Fred') //If the name is 'Fred'
{
	alert('Fred is a pretty generic name...');
}

The code is now much more efficient, as well as being much cleaner! Note that we can add as many else ifs as we like (as long as we have an initial 'if' to start the chain off of course), so let's add a few more cases:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var name = prompt('What is your name?');
if(name=='Joe') //If the name is 'Joe'
{
	alert('Wow, cool - my name is Joe too!');
}
else if(name=='Fred') //If the name is 'Fred'
{
	alert('Fred is a pretty generic name...');
}
else if(name=='John') //If the name is 'John'
{
	alert('Alright, John?');
}
else if(name=='George') //If the name is 'George'
{
	alert('George is a pretty decent name.');
}

So now we can make all of these comparisons, however there might be one other core thing that we want to accomplish in all this comparison - something that executes if none of the conditions are met. Luckily there is an easy way to do this -- we can simply write else after the last else if (or just after the initial if if you don't have any else ifs in the chain) and then specifying the code that will get executed if none of the conditions are met in curly brackets, for example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var name = prompt('What is your name?');
if(name=='Joe') //If the name is 'Joe'
{
	alert('Wow, cool - my name is Joe too!');
}
else if(name=='Fred') //If the name is 'Fred'
{
	alert('Fred is a pretty generic name...');
}
else if(name=='John') //If the name is 'John'
{
	alert('Alright, John?');
}
else if(name=='George') //If the name is 'George'
{
	alert('George is a pretty decent name.');
}
else
{
	alert('I have no opinion on your name.');
}

And now we have our fully functional name checker code, and hopefully now know how to get basic input from the user, and how to use 'if' statements and basic conditions to compare two values! To test it out, you can either put this code into the 'script.js' file inside your project folder that we setup in previous tutorials (and then open up index.html), or use the JSFiddle below.