For diving deeper into JavaScript, please read Chapter: 1 of the book Head First Javascript Programming.
Today, we start learning one more of the three languages taught in this course: JavaScript. We will just begin talking about it, so don't worry if you don't understand everything immediately.
JavaScript is a programming language for making dynamic web pages, i.e., pages that can interact with the user and vary each time they are loaded. Although the names are similar, JavaScript is not the same language as Java.
We will begin our investigation of JavaScript by presenting a series of simple but working examples. We'll show you the code, but you should not try to completely understand it at this point. Instead, you should read it, make some guesses as to what various things might mean, and try to get the gist of what is happening without worrying about all the details. Later, after we have explained some of the notation and its meaning, we can go back to these examples and understand them more fully.
(This is a little like trying to learn a foreign language by walking around the country, listening to the words people say and observing what they do. You'll miss a lot, especially at first, but it's way more interesting than trying to start by reading a dictionary and memorizing vocabulary and syntax.)
Here, we gather data in the form of the user's name, then we compute a response string by gluing their name onto the end of a common greeting, and finally output the result with a popup window.
We would probably never do this greeting in a real website, but someone's name could be filled into a form, added to a roster, guest list or signup sheet, emailed to someone, ...
let your_name =
name
response
This is almost the same, but we tell them the length of their name.
Again, not useful in itself, but it's nice to know that we can find out the length of a string. For example, we can limit the length of people's posts in an application like a Facebook wall.
Here, we ask for a number and use it in a calculation.
How would you modify this code if you wanted to convert from inches to feet instead of from ounces to pounds? What if you wanted to convert from feet to inches? (hint: '/' means division, and '*' means multiplication)
Here, we ask for the person's name, quest, and favorite color. We then modify the box below, which was created with the following HTML:
<div id="grail" style="color: blue; border: 5px solid blue;"> Your name here </div>
OK, here is the javascript code that will change the box above: let name = prompt("What is your name?", "Arthur, King of the Britons"); let quest = prompt("What is your quest?", "To seek the grail"); let color = prompt("What is your favorite color?", "blue"); let text = name + ": " + quest; let box = document.querySelector("#grail"); box.innerHTML = text; box.style.borderColor = color; box.style.color = color;
Javascript is a different language from HTML. You might remember that HTML is responsible for defining the structure of a document; Javascript is responsible for defining the behavior of a page. Javascript can interact with a page in three ways:
Greet me
Here is the code:
<button id="greeter1" type="button" onclick="alert('hi there!');">Greet me</button>
Notice the JS code in the onclick attribute; there are also other attributes where JS code can be put.
onclick
<script>
<head>
<body>
body
<body> ... <button id="greeter2" type="button"">Greet me</button> ... <script> function sayHello() { alert('hello!!'); } $("#greeter2").click(sayHello); </script> </body>
In the preceding, you'll see that the button has no JavaScript code at all; the code is in the script tag. However, there's a slightly more elaborate mechanism for defining and attaching the code. We'll get to these later in the course.
script
<script src="myJScode.js"> </script>
We'll be using all three ways in our examples, but if you were creating a larger website, you should avoid inline JS. You should use mostly external JS (when shared across pages) and document-level JS.
In the following sections, we'll get a first look at various facets of the language. There's more to say about all of these, but this brief tour will help you see how these different aspects of the language fit together. After all, when you learn a natural language (e.g. French or Chinese), you don't try to learn all the verbs first, before tackling any of the nouns or adjectives.
Variables are just named storage locations for a program. We used them in the examples above to store stuff that we computed (such as weight in pounds) or stuff that came from the user (such as their name or the weight in ounces of an object). The technical name for stuff might be data or values.
stuff
data
values
You can put a value into a variable, using an assignment statement, like these examples:
let name = "Cherios"; let weight = 8.9;
Note that this use of the equals sign is very different from how it is used in mathematics. In math, the equals sign (=) is an assertion that two things have the same value.
In computer science, the equals sign means: Put the value that you see on the right of the equals sign into the storage location that is mentioned on the left of the equal sign.
Because the equals sign doesn't mean equality, we often pronounce it differently. Instead of saying weight equals 8.9, we say weight gets 8.9, short for gets assigned the value.
weight equals 8.9
weight gets 8.9,
gets assigned the value
After a variable has been assigned a value, the value can be retrieved and used just by giving the name of the variable. For example, the following two statements retrieve the values of name and weight, perform an operation on them, and then assign the new values to two new variables called len and pounds.
weight
len
pounds
let len = name.length; let pounds = weight/16;
We will return to the concept of variables in future lectures.
alert()
The first few examples accomplished the reporting of the response by use of the alert() function. It looked like this:
alert(response);
This built-in function will pop up a window that displays whatever value is supplied to the alert() function by placing it in the parentheses. In this case, it reported the value that was in the variable named response. In earlier examples, we saw alert() with an expression inside the parentheses. This expression is evaluated and then alert() reports the result.
Alerts are annoying in working code, but they are very useful when testing and developing code, because they stop the execution of the program until you acknowledge them:
Some terminology: A statement like alert("hello") is an example of a function call or function invocation, where alert is the name of a standard JavaScript function and the expression in parentheses (in this case, "hello") is the argument of (that is, input to) the function. We'll learn more about functions later, but knowing alert() is useful right away.
alert("hello")
alert
"hello"
input to
console.log()
Very similar to alert() but much less annoying is console.log(). It's used in almost exactly the same way: you put a value (or a variable containing a value) into the parentheses, and that value gets reported. However, the difference is that alert() demands that the user acknowledge it, while console.log writes it to a hidden place that only web developers know about, and keeps going, so the user is not annoyed or delayed by the message.
console.log
The console is also where the browser writes error messages. It writes them there so that the muggles won't see them and worry about them. As of this writing, here's how you can find them:
Try it! Click the button below to execute those two console.log statements and then look for them in the console of your current browser.
We will use console.log and alert a lot as a way of getting some insight into what our code is doing and to help understand it and debug it. So it's worth becoming comfortable with finding and looking at the console.
A comment is a bit of text that the computer ignores but the programmer can see. You should always add comments to your JavaScript code to explain its purpose. As shown in the example below, JavaScript supports two kinds of comments:
/*
*/
//
<script> /* (Block Comment) Pop up an alert box with a message making sure that you all are awake because at this time of day, you might be sleepy. Of course, a lot of it depends on what you were doing last night... */ alert("Hey you there -- wake up!"); // (Line Comment) The user must be awake if we reach this point! console.log("User has woken up"); </script>
In addition to explaining the code, we can use comments to comment out a line of code that we don't want to run (sometimes when we are debugging to find where the error lies).
comment out
JavaScript programs manipulate values. The two basic kinds of values we've seen today are:
floating point
"
'
"Harry Potter" 'grail'
An expression is a JavaScript phrase that denotes a value. The simplest numeric expression is a number itself. We can also create more complex numeric expressions using the numeric operators +, -, *, / and %:
+
-
*
/
%
27
27 + 10
37
27 - 10
17
27 * 10
270
27 / 10
2.7
27 % 10
7
The % operator is the remainder or modulus operator. Its value is the remainder when the first number is divided by the second. Here is an example of when it can be used. An average size woman might be 64 inches tall. To find the number of feet, we divide 64 by 12 and round down, to get 5. To get the number of leftover inches, we divide 64 by 12 and take the remainder, using the % operator. That gives us the 4. The remainder operator is more useful than you might think. But don't worry about it; you can think of it as a weird kind of division.
For the most part, JavaScript follows the algebraic precedence rules that you learned in school years ago.
JavaScript follows these rules, so your prior experience will serve as a good guide. There are a few new operators that you'll learn, such as the % or remainder operator, which has, unsurprisingly, the same precedence as division.
Try to guess what the following will evaluate to:
Literal strings can be denoted by either single or double quotes, which gives you some flexibility about how to handle awkward situations such as quotation marks inside a string:
"Let's play Tag!"
Let's play Tag!
'Not "it"!'
Not "it"!
These examples show that you can put a single quote inside double quotes and a double quote inside single quotes.
The main operation on strings is the concatenation operator, +:
"CS" + "115" + " rocks!"
CS115 rocks!
"Harry" + "Cho"
HarryCho
We saw this many times in the examples, as we created our response text out of literal strings, values supplied by the user, and computations from them. Concatenation is also useful for splitting strings across multiple lines. Let's say we want to display a string that represents a table. If we try to fit it in one line, it may look something like:
alert("id,name,age,height(ft),0,Amy,5,4,1,Ben,9,6,2,Cindy,5,5");
With all of those numbers, it can be hard to parse the information when reading the code. Unfortunately, we can't jump to the next line in the middle of a string, but we can use concatenation:
alert("id,name,age,height(ft)," + "0,Amy,5,4," + "1,Ben,9,6," + "2,Cindy,5,5");
parseInt()
parseFloat()
We'll see that there are many situations where it's necessary to convert from a string of digits to numbers. The parseInt() and parseFloat() functions are used for this purpose. The first one is used with integer numbers and the second one with numbers with a fractional part (after the decimal point).
The function takes an (optional) second parameter that says what number base to use. We'll typically use 10 for decimal numbers.
parseInt("243",10)
243
parseInt("cs115",10)
NaN (Not a Number)
parseInt("3.141",10)
3
parseFloat("3.141")
3.141
The second argument to parseInt is the radix or base that you want to use. It can be 10 for decimal number, 16 for hexadecimal numbers and 8 for octal numbers (base 8). It's a good idea to supply this value, to avoid JavaScript inadvertently doing the wrong thing.
parseInt
base
You can test any of the above expressions here:
prompt()
Like alert(), invoking the prompt() function pops up a small window, but (1) it also allows the user to type in a string and (2) the string entered by the user is returned as the value of invoking the prompt() function.
For example, the following statement prompts the user for a first name and then stores it in a variable.
The prompt() method is not the best way to get input in Javascript but it is OK for now. Better ways are to use HTML forms, or the jQuery library, but we can ignore it for now.
The first argument of the prompt() function is displayed above the input area of the prompt box. The prompt() function takes an optional second argument that, if supplied, is used as a default value for the input area. For example:
Using a default value makes it easier on the user when the default is right, but allows them to correct (override) the value when it's wrong.
The result of invoking the prompt() function is always a string, NOT a number, even if it's all digits, so it's necessary to use parseInt() or parseFloat() to convert sequences of digits to numbers. Compare the following two examples:
In this first example, we just use the + operator on the strings returned by prompt():
However, in this example, we first convert the strings into numbers (a float for the first, and an integer for the second), then apply the + operator:
Note that if we never need the strings a and b, we can take the value of prompt and immediately convert it to a number using parseInt, so the second example can be written more succinctly like this:
a
b
prompt
You have already learned a lot of JavaScript. For diving deeper, please read Chapter 1 of the book Head First Javascript Programming.