Happy Learn JavaScript Tutorial Vol 1

Buy now at Leanpub

Please Buy now at Leanpub

Written and illustrated by GetContented.

Published on 2016-05-22.


Contents

Main Table of Contents
Previous chapter: 2. Display a Message
3. ChatterBot Mark 1
... 3.1. The prompt Function
... 3.2. Strings and Characters
... 3.3. Programming from Files
... 3.4. String Concatenation
... 3.5. Some Input
... 3.6. Variables
... 3.7. Our Final Program
... 3.8. Homework
Next chapter: 4. Guess the Number

3. ChatterBot Mark 1 🔗

Welcome back. You’ve seen some simple code, so using a silly little talky program, we’re now going to show you how to write code in files, get input from the user, join text together, do some simple math, and introduce variables, too!

The ChatterBot program’s purpose is to ask a few questions and give a reply.

It may surprise you to find out that computers can only perform four main basic tasks: input, processing, storage and output. Whatever it appears they’re doing from moment to moment, however complex it is, it will just be a combination of these four tasks. We already saw some output, ChatterBot will use the remaining three, too.

We’re going to use a text editor — an application for editing unformatted text — to make our source code. We can’t use a word processor because its saved format is incorrect. Download the one we’ll use so it’ll be ready when we need it from the website https://atom.io — just use the download button on the front page.

Meantime, we’ll play with some new functions, so open the JavaScript console again. It’s normal to not remember how, just go back and remind yourself.

Take a look at the code below. It’s a statement with a function call again. This one is named prompt. As before, the semi-colon marks the end of the statement, and the parentheses show that we’re calling the function.

3.1. The prompt Function 🔗


prompt();

When you hit return, a box comes up with a field, an area to type into. Type "jelly", and press OK. The console prints your entered string "jelly" as its response.

3.2. Strings and Characters 🔗

We’ve seen strings before. The quotes tell JavaScript what’s inside is text data; a series of characters. If you don’t know, a character is any unit of written data, such as the letter "F", and even non-textual ones, like the character for new-line, or the space that appears between words.

This prompt function is like alert: we can call it with or without an argument. If you give it one, it’ll use the argument in the window to prompt for input.

Of course the main difference compared to alert is that prompt lets the user input some text. On pressing OK, that input becomes the string value returned. If cancel is pressed instead, a null value is returned rather than a string — this is an intentionally empty value. By contrast, we saw that JavaScript uses undefined when the alert function returned because it didn’t actually return a value at all. Don’t worry too much about this, it will become clearer when we see it more.

Try running this again a few times, pressing cancel or OK, and using different string values in the prompt dialog box.

What about when we call prompt with a string as its argument?


prompt("Your name?");

As expected, the string appears in the dialog box above the field. We can see prompt is one way to have the computer collect input from the user into our programs. We’ll see how we can use these responses shortly.

By now Atom should have downloaded, so install and open it.

3.3. Programming from Files 🔗

We’ll use it to create a web page to hold our ChatterBot program because it’ll be larger than just a few lines entered into the browser.

Make a new file, and save it as chatterbot.html in a location you’ll be able to find later.

Now type the following HTML. We’re not going to explain the HTML, but It contains an embedded program in JavaScript. You’ll probably recognise what this program does: it displays an alert on the screen.


<html>
  <body>
    <script>
      alert("Hi");
    </script>
  </body>
</html>

To load this into our browser, save it, go to the browser and choose Open File from the File menu. Choose the file you just saved. When you choose it, the page will load and the JavaScript will run immediately. To re-run it, simply reload the page (either with the button, or from the View menu).

Well done on creating your first file-based JavaScript program and running it. Next we’ll modify it to ask your name using the prompt function.


<html>
  <body>
    <script>
      prompt("What's your name?");
    </script>
  </body>
</html>

If you save this, then use reload in the browser, it will load the new program in and run it, and so ask for your name.

When you do that and press OK, what happens to the return value from prompt? We didn’t tell JavaScript to use it, so it just disappeared. On the console it would print out the result, but when we’re inside a program the result is just thrown away. Soon we’ll find out how to capture it instead.

We’d like our ChatterBot to produce a greeting alert after asking for the name of the user.


<html>
  <body>
    <script>
      prompt("What's your name?");
      alert("Hello, ");
    </script>
  </body>
</html>

When you run this, it does what we’d expect: asks for a name, and gives you a message "Hello, ".

However, we’d really like it to actually put the entered name into the greeting. Let’s put a dummy name in first, then change it out for the actual one. We could just put it into the existing string argument to the alert, but let’s do something else instead:


<html>
  <body>
    <script>
      prompt("What's your name?");
      alert("Hello, " + "Penelope");
    </script>
  </body>
</html>

3.4. String Concatenation 🔗

We used an operator called + here to show how to join our dummy-name "Penelope" to the greeting. Operators are symbols used with values to form expressions that produce other values. Try this program out.

An expression is any JavaScript code that the computer can work out a value for. Joining two strings with + is an expression. Function calls are expressions, too. Operators can be used to help make expressions. All expressions can be used as statements (we call them expression statements when they are), and can also be part of a statement, but not all statements are expressions. This will become clearer when you see more. Don’t worry about it.

So we now know that the + operator used with two strings joins them into one. This joining together operation is called concatenation, a word originating from Latin that means “chain on to”.

3.5. Some Input 🔗

This doesn’t do what we want yet, though. We want the actual return value from the call to prompt to be concatenated to the greeting, not just "Penelope" every time. Let’s see an adjusted program that does this in a simple way.


<html>
  <body>
    <script>
      alert("Hello, " + prompt("What's your name?"));
    </script>
  </body>
</html>

Ok this is kind of crazy. We’ve embedded the call to prompt into the call to alert! We know prompt returns its field contents as a string, so we just inserted the whole call to prompt into the alert function’s argument concatenating it to the end of "Hello, ". When you run this, you’ll see it does what we want.

When evaluating a function call, JavaScript looks at its arguments and evaluates them first, then feeds that result into the function. In the case of alert, that means prompt is evaluated to get its return value so we can concatenate that to "Hello, " and then feed that whole string into alert. So prompt happens first, and then alert displays its window with the greeting string!

This does work, but it’s not very elegant. We programmers tend to prefer when code is clear, and this isn’t very clear.

3.6. Variables 🔗

It would be nicer if we had some kind of temporary named storage location we could put the result of prompt into, then pass that to the call to alert so it would be clearer what our intention is, and what sequence things happen in.

Well, JavaScript definitely has something like this. It’s called a variable. This is a named value that can change: a value that is able to be varied! You can assign values to it, and if you refer to it, its value evaluates to whatever you last put in it.

Let’s take a step backward and see another program that says hello to someone named Stella, but uses a variable.


<html>
  <body>
    <script>
      var name = "Stella";
      alert("Hello, " + name);
    </script>
  </body>
</html>

Ok the first statement declares and assigns a variable named name. Declaration is when we use the var keyword to indicate that we’re going to use the word name as a variable in our program. Assignment is when you use the = operator to assign a value to a variable. We’re doing both at once, putting the value "Stella" into name. Here, we’re using the name name as a variable identifier. This means it is used by Javascript to identify the variable.

This means later on when we refer to the identifier name, JavaScript looks up the value stored for it, and uses that. As you can imagine, this is incredibly useful.

On the next line, we have our old friend the alert function, in a statement that uses the value from the variable, the string concatenation operator +, and the string "Hello, " to produce a greeting alert.

Obviously again, we’d prefer if the variable’s contents are the result of prompting the user for their name rather than just "Stella":


<html>
  <body>
    <script>
      var name = prompt("What's your name?");
      alert("Hello, " + name);
    </script>
  </body>
</html>

3.7. Our Final Program 🔗

Finally, we’ll see a program that also asks for your age and does some simple math on it.


<html>
  <body>
    <script>
      var name = prompt("What's your name?"),
          age  = prompt("What's your age?");
      alert("Hello, " + name +
            ". Half of your age is " + age / 2 +
            ". Triple your age is " + age * 3);
    </script>
  </body>
</html>

Notice that we have one single variable assignment statement that is declaring and defining two variables as the result of prompting the user? We can split a statement across lines like this if we need to. Notice the use of the comma to separate out definitions. We could have used two separate statements. Either is fine.

Next, we’ve split the statements with the alert on it across three lines, and we’re making extensive use of the string concatenation operator to join some response string together into the one alert, and using some math operators on the age value to tell the user some things about their age. We use the / operator to divide one number by another, and the * operator to multiply two numbers.

Now we’ll see a program that does exactly the same thing, but goes about it slightly differently. Use this to compare to the previous one.


<html>
  <body>
    <script>
      var name, age, alert_value;
      name = prompt("What's your name?");
      age = prompt("What's your age?");
      alert_value = "Hello, " + name + ". " +
                    "Half of your age is " + age / 2 ". " +
                    "Triple your age is " + age * 3);
      alert(alert_value);
    </script>
  </body>
</html>

We notice that we’re declaring three variables by using the var keyword. This simply tells JavaScript that we want to set these names aside as variables that we’ll assign values to them later. Then, in separate statements we’re assigning values to these variables. These are similar values to the program before, but we’re using a variable for the call to alert this time instead of putting the expression directly into alert as an argument.

3.8. Homework 🔗

Your homework is to try adjusting the strings of either of the final programs and seeing what effect this has on the program. Don’t try to do anything tricky, though. We’ll see more things in good time. We don’t want you to get confused or frustrated. Make sure you try inputting each of the programs in this chapter and try them all out at least once.


If you’ve enjoyed reading this, please consider purchasing a copy at Leanpub today

Please follow us, and check out our videos Follow @HappyLearnTutes


Main Table of Contents
Previous chapter: 2. Display a Message
3. ChatterBot Mark 1
... 3.1. The prompt Function
... 3.2. Strings and Characters
... 3.3. Programming from Files
... 3.4. String Concatenation
... 3.5. Some Input
... 3.6. Variables
... 3.7. Our Final Program
... 3.8. Homework
Next chapter: 4. Guess the Number