Unfamiliar Operator:Eliminating ambiguity;Concatenating text strings;Prompts

Assinment # 6
JAVASCRIPT


C h a p t e r s


Math expressions: Unfamiliar operators

There are several specialized math expressions you need to know. Here's the first one.
num++;
This is a short way of writing...
num = num + 1;
It increments the variable by 1.
You decrement using minuses instead of pluses.
num--;
You can use these expressions in an assignment. But the result may surprise you.
1 var num = 1;
2 var newNum = num++;
In the example above, the original value of num is assigned to newNum, and num is
incremented afterward. If num is originally assigned 1 in the first statement, the second
statement boosts its value to 2. newNum gets the original value of num, 1.
If you place the pluses before the variable, you get a different result.
1 var num = 1;
2 var newNum = ++num;
In the statements above, both num and newNum wind up with a value of 2.
If you put the minuses after the variable, the new variable is assigned the original value,
and the first variable is decremented.
1 var num = 1;
2 var newNum = num--;
num is decremented to 0, and newNum gets the original value of num, 1.
But if you put the minuses before the variable, newNum is assigned the decremented, not
the original, value. Both num and newNum wind up with a value of 0.
1 var num = 1;
2 var newNum = --num;

Math expressions: Eliminating ambiguity

Complex arithmetic expressions can pose a problem, one that you may remember from
high school algebra. Look at this example and tell me what the value of totalCost is.
var totalCost = 1 + 3 * 4;
The value of totalCost varies, depending on the order in which you do the arithmetic. If
you begin by adding 1 + 3, then multiply the sum by 4, totalCost has the value of 16. But if
you go the other way and start by multiplying 3 by 4, then add 1 to the product, you get 13.
In JavaScript as in algebra, the ambiguity is cleared up by precedence rules. As in
algebra, the rule that applies here is that multiplication operations are completed before
addition operations. So totalCost has the value of 13.
But you don't have to memorize JavaScript's complex precedence rules. You can finesse
the issue by using parentheses to eliminate ambiguity. Parens override all the built-in
precedence rules. They force JavaScript to complete operations enclosed by parens before
completing any other operations.
When you use parens to make your intentions clear to JavaScript, it also makes your code
easier to grasp, both for other coders and for you when you're trying to understand your own
code a year down the road. In this statement, the parentheses tell JavaScript to first multiply 3
by 4, then add 1. The result: 13.
var totalCost = 1 + (3 * 4);
If I move the parentheses, the arithmetic is done in a different order. In this next statement,
the placement of the parens tells JavaScript to first add 1 and 3, then multiply by 4. The result
is 16.
var totalCost = (1 + 3) * 4;
Here's another example.
var resultOfComputation = (2 * 4) * 4 + 2;
By placing the first multiplication operation inside parentheses, you've told JavaScript to
do that operation first. But then what? The order could be..
1. Multiply 2 by 4.
2. Multiply that product by 4.
3. Add 2 to it.
...giving resultOfComputation a value of 34.
Or the order could be...
1. Multiply 2 by 4.
2. Multiply that product by the sum of 4 and 2.
...giving resultOfComputation a value of 48.
The solution is more parentheses.
If you want the second multiplication to be done before the 2 is added, write this...
resultOfComputation = ((2 * 4) * 4) + 2;
But if you want the product of 2 times 4 to be multiplied by the number you get when you
total 4 and 2, write this...
resultOfComputation = (2 * 4) * (4 + 2);

Concatenating text strings

In Chapter 1 you learned to display a message in an alert, coding it this way.
alert("Thanks for your input!");
Or you could code it this way.
1 var message = "Thanks for your input!";
2 alert(message);
But suppose you wanted to personalize a message. In another part of your code you've
asked the user for her name and assigned the name that she entered to a variable, userName.
(You don't know how to do this yet. You'll learn how in a subsequent chapter.)
Now, you want to combine her name with a standard "Thanks" to produce an alert that
says, for example, "Thanks, Susan!"
When the user provided her name, we assigned it to the variable userName. This is the
code.
alert("Thanks, " + userName + "!");
Using the plus operator, the code combines—concatenates—three elements into the
message: the string "Thanks, " plus the string represented by the variable userName plus the
string "!"
Note that the first string includes a space. Without it, the alert would read,
"Thanks,Susan!".
You can concatenate any combination of strings and variables, or all strings or all
variables. For example, I can rewrite the last example this way.
1 var message = "Thanks, ";
2 var banger = "!";
3 alert(message + userName + banger);
Here it is, with three strings.
alert("Thanks, " + "Susan" + "!");
You can assign a concatenation to a variable.
1 var message = "Thanks, ";
2 var userName = "Susan";
3 var banger = "!";
4 var customMess = message + userName + banger;
5 alert(customMess);
If you put numbers in quotes, JavaScript concatenates them as strings rather than adding
them. This code...
alert("2" + "2");
...displays the message "22".
If you mix strings and numbers...
alert("2 plus 2 equals " + 2 + 2);
...JavaScript automatically converts the numbers to strings, and displays the message "2
plus 2 equals 22".

Prompts

A prompt box asks the user for some information and provides a response field for her
answer.
This code asks the user the question "Your species?" and provides a default answer in the
response field, "human". She can change the response. Whether she leaves the default response
as-is or changes it to something else, her response is assigned to the variable.
var spec = prompt("Your species?", "human");
Prompt code is like alert code, with two differences.
In a prompt, you need a way to capture the user's response. That means you need to start
by declaring a variable, followed by an equal sign.
In a prompt, you can specify a second string. This is the default response that appears in
the field when the prompt displays. If the user leaves the default response as-is and just
clicks OK, the default response is assigned to the variable. It's up to you whether you
include a default response.
As you might expect, you can assign the strings to variables, then specify the variables
instead of strings inside the parentheses.
1 var question = "Your species?";
2 var defaultAnswer = "human";
3 var spec = prompt(question, defaultAnswer);
The user's response is a text string. Even if the response is a number, it comes back as a
string. For example, consider this code.
1 var numberOfCats = prompt("How many cats?");
2 var tooManyCats = numberOfCats + 1;
Since you're asking for a number, and the user is presumably entering one, you might
expect the math in the second statement to work. For example, if the user enters 3, the variable
tooManyCats should have a value of 4, you might think. But no such luck. All responses to
prompts come back as strings. When the string, "3", is linked with a plus to the number, 1,
JavaScript converts the 1 to a string and concatenates. So the value of tooManyCats winds up
being not 4 but "31". You'll learn how to solve this problem in a subsequent chaper.
If the user enters nothing and clicks OK, the variable is assigned an empty string: ""
If the user clicks Cancel, the variable is assigned a special value, null.
Some coders write window.prompt instead of, simply, prompt. This is a highly formal
but perfectly correct way to write it. Most coders prefer the short form. We'll stick to the
short form in this training.
In the example above, some coders would use single rather than double quotation marks.
This is legal, as long as it's a matching pair. But in a case like this, I'll ask you to use
double quotation marks.

Assignment

Unable to display PDF file. Download instead.


Perform The Assignment