var apples = 5;
Okay, so your code knows that you have 5 apples. Now what? Well your code might know that you have 5 apples, but nobody else does. Let’s tell them! One of the most common methods to display a simple message to a user is by sending them an alert:
var apples = 5; alert('There are currently ' + apples + ' apples!');
So what we have is the string ‘There are currently ‘ followed by our apples variable (which is 5) followed by another string, ‘ apples!’. Put them together and we get “There are currently 5 apples!”. Our “alert” takes whatever is passed to it (whatever is between the parenthesis) and simply opens a window with that text.
What if we want to let our user eat an apple? One way to do that would be to prompt them for how many apples they would like to eat:
var apples = 5; alert('There are currently ' + apples + ' apples!'); var eat = prompt('How many apples would you like to eat?', '1');
“prompt” is another built-in function, similiar to “alert”. Instead of just showing information, however, it also takes input from the user. In this case we are asking our user how many apples they want to eat. The ‘1’ in our code tells the “prompt” function that our default value for how many apples to eat is 1. So people usually only eat one apple at a time. The user can change this, however, to any number they want. Once the user clicks the “OK” button to the prompt, the “eat” variable gets set to their response. So if they type in that they want to eat 2 apples, eat now equals “2”.
So if our user has eaten 2 apples, there are 3 left, right? Well let’s do some basic math and show this.
var apples = 5; alert('There are currently ' + apples + ' apples!'); var eat = prompt('How many apples would you like to eat?', '1'); apples -= parseInt(eat); alert('Now there are only ' + apples + ' apples!');
Two new things here. First, we have a call to “parseInt”. parseInt takes in a string and returns a number. Since we have to have a number to do math, what this does is help to gaurantee that we have a number. If our user entered “2 apples” in the box, parseInt turns this into the number 2.
Next, we have the “-=” operator. “-=” means that you want to subtract whatever is on the right of the operator from whatever is on the left of it. So we are subtracting our “eat” variable from our “apples” variable. You could also write this line as:
apples = apples - parseInt(eat);
This would do exactly the same thing and might be a bit easier to understand. Now that we know how many apples are left we once again let our user know this information.
There are other operators like -= that do similiar things. In total, there are 8 common arithmatic operators that you will use:
+ - / * += -= /= *=
That’s it for this lesson. Next time we will continue by adding some validation to our code, we will introduce the if and else statements, and briefly introduce you to functions.