Chapter 3

Giving and Receiving Data

Programs come in many different sizes and have many different purposes. Here are three things all programs have in common:

  • A way to receive information from the user
  • A way to give information back to the user
  • A way to store and work with information in between giving and receiving

Information, or data, that a program receives from a user is called input. What the program gives back to the user is called output. In the time between when a program receives input and produces output, it needs some way to store and work with the various types of data that has been inputted, so it can produce output.

The question of whether it’s better to give or receive isn’t important! It’s all good. In this chapter, you learn how JavaScript can help you to get, receive, and just plain have data!

image

Mastering Variables

In the real world, when you want to store something, give something away (as a gift, for example), move something, or organize something, you often put it in a box.

JavaScript doesn’t care about heart-shaped boxes of chocolates or shoeboxes with the latest sneakers. What JavaScript loves is data. To store and move around data, JavaScript uses a special kind of box called a variable. A variable is a box you can assign a name to. This name will represent all the data contained in that box, or variable.

Variables make it possible for the same program to work with different input to produce different output.

Creating variables

Creating a variable in JavaScript is pretty simple. To create a variable, you use the var keyword, followed by the name of the variable, and then a semicolon, like this:

var book;

As a programmer, you have a lot of flexibility when naming your variables. You can be very creative in naming your variables, but you don’t want to get too crazy. Most important, your variable names should accurately describe the data that you store inside them.

Each of the following variable declarations creates a variable with a good and descriptive name. By looking at them, you can probably guess what the data stored inside them looks like.

var myFirstName;

var favoriteFood;

var birthday;

var timeOfDay;

Notice how we separate words in variable names by using capital letters for every word after the first one. Variable names can’t contain spaces, so programmers have created several other ways to separate words. This particular style is called camelCase. Can you guess why it has that name?

After looking at these examples, what would you name variables for storing the following pieces of data?

  • Your pet’s name
  • Your favorite school subject
  • The age of your best friend
  • Your street address

tip In addition to the rule that variable names must not contain spaces, there are several other rules that you must follow:

  • Variable names must begin with a letter, an underscore ( _ ), or a dollar sign ($).
  • Variable names can only contain letters, numbers, underscores, or dollar signs.
  • Variable names are case sensitive.
  • Certain words may not be used as variable names, because they have other meanings within JavaScript. These so-called reserved words are as follows:

    break

    case

    class

    catch

    const

    continue

    debugger

    default

    delete

    do

    else

    export

    extends

    finally

    for

    function

    if

    import

    in

    instanceof

    let

    new

    return

    super

    switch

    this

    throw

    try

    typeof

    var

    void

    while

    with

    yield

Storing data in variables

After you’ve created a variable, you can store any sort of data inside it. When the data is in there, you can recall it at any time. Let’s try it out!

  1. Open the JavaScript Console in Chrome.
  2. Create a new variable named book by typing the following and then pressing Return (Mac) or Enter (Windows):

    var book;

    You’ve created your container, or variable, and named it “book.”

    When you press Return or Enter, the JavaScript Console displays the word undefined. This is exactly what you want to happen. JavaScript is just telling you that your code ran correctly and that it doesn’t have anything to tell you.

    technicalstuff It may seem funny that JavaScript tells you that it has nothing to tell you. But, trust us, it’s way better that it says something, even if it’s just undefined than if it were to give you the cold shoulder and say nothing at all.

  3. Put a value into your new variable by typing the following code.

    book = "JavaScript For Kids For Dummies";

    You’ve now put data inside your variable, where it will be stored.

    When you press Return or Enter, JavaScript responds with the name of the book.

    remember You only need to type var when you first create and name your variable. When you want to change the data inside your variable, you only need to use the variable’s name.

  4. Now, temporarily forget the name of this book. Got it? Now, imagine that you need to recall the name of this book so that you can tell your friend about it! To recall the data, or value, in a variable, you can just type the name of the variable in the console. So, type the following:

    book

    The console recalls the string that was assigned to the book variable and prints it out, as shown in Figure 3-1.

    technicalstuff Notice that we didn’t use a semicolon (;) when typing — we just used a variable name in the JavaScript Console. The name of a variable isn’t a full JavaScript statement, so it doesn’t require a semicolon. We’re just asking JavaScript for the value of the variable, just as if we had asked it 1 + 1.

  5. Now try changing the value of the book variable by typing the following statement into the JavaScript Console:

    book = "The Call of the Wild";

  6. Type book into the JavaScript Console to retrieve its new value.

    The console prints out “The Call of the Wild” (or whatever you entered as the new value of book.

image

Figure 3-1: Printing out the value assigned to a variable.

In addition to text, variables can also hold several other different types of data. In the next section, we show you each of the basic (also known as primitive) data types that JavaScript understands.

tip The data inside a variable can also be called the value of a variable.

Understanding Data Types

JavaScript variables have just one job — to hold and store data — and they do this job quite well. Using and creating variables are easy. There are many different types of data in the world, such as numbers, letters, and dates. JavaScript makes some important distinctions between these and other different kinds of data that you, as a coder, need to be aware of.

Data types are how a program knows whether 03-20-2017 is a date (March 20, 2017) or a math problem (subtract 20 from 3 and then subtract 2017 from the result).

JavaScript recognizes three basic data types: string, number, and Boolean.

The string data type

The string data type holds text. We explain the basics of how strings work in Chapter 2, but there are a few other cool tricks that you can do with strings besides just storing and printing them.

One cool string trick is to count how many characters the string is made up of. The way you do that is to use .length after the string, or after a variable holding the string.

For example, to find out the length of the string held inside the book variable you create in the previous section, type book.length into the console. The console responds right away with a number, as shown in Figure 3-2.

image

Figure 3-2: Getting the length of a string.

Every string, even an empty string, has a length. The length of an empty string, of course, is 0. Because it’s something that describes a string, we call length a property of a string.

remember You see the word property used a lot when people talk about JavaScript. A property is something that describes or is a part of something. For example, a car’s color is a property of the car, a person’s name is a property of the person, and a string’s length is a property of the string.

In addition to finding out the length of a string stored in a variable, you can also just attach the length property to a string in quotes to find out its length:

"I am a string.".length

Count the letters in this sentence. There are 10 — 11 if you count the period at the end of the sentence. But when you enter this command into the JavaScript console, you get 14. Do you know why?

The spaces in a string count just as much as the letters, punctuation, symbols, and numbers in the string. To use the analogy we make in Chapter 2, it’s all just knots on the string (14 of them to be precise) to JavaScript.

In addition to properties, strings also have things that they can do, or that can be done to them. In programming, we call these things that can be done with or to something its methods.

The most commonly used string method is indexOf. The job of indexOf is to look at your string, find a certain character or group of characters inside it, and tell you what position they’re at. In the following statement, we look for the position of the word am in a string:

"I am a string.".indexOf("am");

When you run this statement in the console, the result is 2. Try retyping the command, but this time look for the capital I.

"I am a string.".indexOf("I");

The result is 0.

This brings us to a very important concept in JavaScript called zero-based numbering. Unlike people, who have ten fingers and generally start counting at the number one, JavaScript starts counting at zero. So, in the previous example, when JavaScript wants to tell you that I is the first character in the string, it says that I is at position 0.

remember If JavaScript were on a sports team, it would proudly wear a shirt that read “We’re number 0!”

The number data type

Another type of data that JavaScript understands is the number data type. Numbers can be positive or negative, as well as whole numbers or decimal numbers. Numbers are stored in variables without using quotation marks.

The range of possible numbers that can be used in JavaScript goes from very, very small to very, very large. We won’t bore you with a bunch of zeros right now, but the biggest number that you can use in JavaScript is far greater than the number of stars in the universe. It’s even bigger than the number of atoms in the universe! JavaScript can do any math problem or counting problem that you would want it to do.

warning One thing to watch out for, however, is what happens when you try to combine two different data types, such as strings and numbers.

JavaScript generally tries to be pretty clever. If you open the console and type “10” + 10, JavaScript will assume that you meant for both pieces of data to be strings, and will put them together and give you the result 1010.

On the other hand, if you type 10 * “10”, JavaScript will assume that you meant for the string "10" to actually be the number 10, and it will give you the result 100. JavaScript does this because it knows there is no way to multiply two strings together.

The Boolean data type

The Boolean data type can store one of two possible values: true or false.

Boolean values are the result when you do comparisons in JavaScript, which we cover in more detail in Part V of this book. If you ask JavaScript something like: “Is 3 equal to 30?,” it will respond with a Boolean value of false.

technicalstuff The Boolean data type is named after the mathematician George Boole, so it’s always capitalized.

Let’s do a few experiments with Booleans. Open the JavaScript Console and try typing each of the following statements, pressing Return or Enter after each one to see the result. Note that we’ve used a single-line comment after each statement to explain what it means. You don’t need to type these comments into the console, but you can if you want.

1 < 10 // Is 1 less than 10?

100 > 2000 // Is 100 greater than 2000?

2 === 2 // Is 2 exactly equal to 2?

false === false // Is false exactly equal to false?

40 >= 40 // Is 40 greater than or equal to 40?

Boolean (0) // What is the Boolean value of 0?

Boolean (false) // What is the Boolean value of false?

"apples" === "oranges" // Is "apples" exactly equal to "oranges"?

"apples" === "apples" // Is "apples" exactly equal to "apples"?

In addition to the statements you would expect to be false, JavaScript also considers the following values to be false:

0

null

undefined

"" (an empty string)

false

Prompting the User for Input

Now that you know how variables can hold different types of data, let’s explore the process of getting data from a user and storing it inside your variables.

One way to ask a user for data is by using the prompt command. To try out the prompt command, open the JavaScript console and type the following:

prompt("What is your name?");

After you press Return or Enter, a pop-up window appears in your browser window with a text field, as shown in Figure 3-3.

image

Figure 3-3: Prompting the user for input.

After you enter your name and click OK, the pop-up window disappears, and the value that you entered in the pop-up displays in the console, as shown in Figure 3-4.

image

Figure 3-4: Displaying your name.

That’s all well and good if all you want to do is capture data and immediately repeat it back like a parrot. But what if you want to do something with the user-entered data? To do that, you need to store it in a variable.

Storing user input

To store user-entered data in a variable, you create a new variable and then follow it with =. You then follow it with the prompt statement.

var username = prompt("What is your name?");

remember It’s important to note that a single equal sign (=) in JavaScript is called the assignment operator. Its job is to put the value on the right into the variable on the left. We talk more about operators in Chapter 9.

When you press Return or Enter, a pop-up window appears in your browser, just as before.

When you enter your name in the pop-up window and click OK, the JavaScript Console prints out undefined, indicating that the statement is finished and there’s nothing else for it to do.

To see the value you just entered, you can type the variable name into the console. JavaScript responds with the value of the variable, as shown in Figure 3-5.

image

Figure 3-5: Getting the value of a variable from a prompt.

Responding to Input

Now that you know how to get data from the user, and how to store that data, let’s take a look at two of the ways that you can use JavaScript to respond to the user.

Using alert()

The alert() command pops up a notification box in the user’s browser containing whatever data is between the parentheses.

If you want to display an alert with a simple string message, you can do so by enclosing a message within quotes between the ( and ) after alert. For example, type the following statement into your JavaScript Console:

alert("Good job!");

When you press Return or Enter, the browser displays an alert message containing the message “Good job!”

You display numbers in alerts by putting numbers without quotes between the parentheses. For example, try this statement:

alert(300);

The alert pop-up displays the number 300. You can even do math inside an alert. For example, try this one:

alert(37*37);

The alert displays the result of multiplying 37 and 37.

If you put a word between the parentheses in the alert statement without quotes, JavaScript treats the word as a variable. Try running the following two statements:

var myNameIs = "your name";

alert(myNameIs);

The browser pops up a window containing your name.

By combining different data types into one alert statement, you can start to do some really interesting and useful things. For example, try typing each of the following statements into the JavaScript Console, one at a time:

var firstName = "your name";

var yourScore = 30;

alert("Hi, " + firstName + ". Your current score is: " + yourScore);

As you can see, by using alert(), you can create all sorts of fun and interesting pop-ups to entertain and inform the user, such as the alert in Figure 3-6.

image

Figure 3-6: Creating interesting pop-ups.

Using document.write()

In JavaScript, a web page is called a document. When you change something on the current web page using JavaScript, you do so by telling JavaScript to change the document object.

One way to make changes to the current web page is by using the write method.

remember A method is something that can be done or that something can do.

Every document (or web page) has a write method that causes whatever you put between the parentheses after the method name to be inserted into the web page. You can use document.write() in the same ways that you used alert(). For example, open a new, blank browser window and try out the following statements in your JavaScript Console:

document.write("Hi, Mom!");

document.write(333 + 100);

Notice that statements after the first one are added right after the first statement, without a line break or space. You can add space after or before writing text with document.write by using the characters <br>. For example:

document.write("How are you?<br>");

document.write("I'm great! Thanks!<br>");

document.write("That's awesome!");

tip You can clear out the current contents of the browser window by typing chrome://newtab into the browser address bar or by opening a new browser tab.

The result of entering these three lines into the JavaScript Console is shown in Figure 3-7.

image

Figure 3-7: Three lines of text in a browser.

technicalstuff <br> is an HTML tag. We talk much more about HTML in Chapter 5.

Combining Input and Output

Now, let’s combine input and output to display customized output, based on input from a user. This is really the heart of what JavaScript can do for web pages!

Follow these steps in the JavaScript Console to create a letter to yourself in your web browser. Make sure to press Return or Enter after the end of each statement (after each semicolon).

  1. Type the following to create a variable containing your first name.

    var toName = "your name";

  2. Type the following to create a variable containing the person the letter is from:

    var fromName = "The Grammy Awards";

    You can change The Grammy Awards to anyone you’d like to get a letter from.

  3. Type the contents of your letter into a variable.

    remember Use <br> to insert line breaks and don’t press Return or Enter until after you type the semicolon.

    Here’s the letter we came up with:

    var letterBody = "We are pleased to inform you that your song, 'Can't Stop Coding!,' has been voted the Best Song of All Time by the awarding committee.";

  4. Write document.write() statements to output each of the three parts of your letter.

    For example:

    document.write("Dear " + toName + ",<br><br>");

    document.write(letterBody + "<br><br>");

    document.write("Sincerely,<br>");

    document.write(fromName);

    When your letter is done, it should resemble ours, shown in Figure 3-8.

image

Figure 3-8: A fully customized letter displayed in the browser.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.196.182