[prev]Types[next]

Variables can store different types of data. You've already seen the difference between strings and numbers.

Example: Adding Strings And Numbers

We've seen what happens when you + two numbers together, but what happens if you + a string with a string, or a string with a number?

 
1
2
3
4
5
6
var a = "AppJet"
var x = 2

printp(a + a)
printp(a + x)
printp(x + x)

Click to run the code.

As we see in this example, when a string is involved at all in a + operation, it joins the two operands together as strings instead of computing a mathematical sum.

Example: The Largest Number in the World

This app asks the user for a number, then displays a larger one.

 
1
2
3
4
5
6
7
8
9
10
11
if (request.path == "/") {
  printp("What is the largest number in the world?")
  printp(form("/larger", "n"))
}
if (request.path == "/larger") {
  printp(html("<b>That's not the largest number!</b>"))
  printp("Here is an even larger one:")
  var largerNumber = request.param("n") + 1
  printp(largerNumber)
  print(link("/", "back"))
}

Click to run the code.

The request.param command always returns a string, which means that on line 8 when we compute request.param("n") + 1, we end up joining two strings instead of a mathematical sum. (Coincidentally, the example program still correctly calculates a larger number.)

To do math with user input, you need to convert a string into a number using the Number command, as in printp(30 + Number("45")).

Exercise: fix the bug! Can you fix the example above so it increments the input number by 1 instead of joining two strings? If you enter "2", for example, it should print "3" instead of "21".

Dates

Another type of data is a Date.

 
1
2
var rightNow = new Date()
printp(rightNow)

Click to run the code.

Don't worry about the use of the new keyword. It's a tricky part of JavaScript that we'll learn about later.

For more info on dates, check out The Mozilla JavaScript Reference on Dates.

Previous Lesson: Naming Variables Next Lesson: Loops