|
Expressions & Operators
|
In order to make variables useful, you need to be able to manipulate variables and evaluate them in different contexts.
This ability is provided by expressions. At its most basic, an expression is nothing more than a collection of variables, operators, and other expressions all of which evaluate to a single value.
As with data types, JavaScript has several kinds of expressions:
Assignments
(x = 10 and y =5)
| ASSIGNMENTS | WHAT IT DOES |
| x = y | Sets x to the value of y |
| x += y | x = x + y (15) |
| x -= y | x = x y (5) |
| x *= y | x = x * y (50) |
| x /= y | x = x / y (2) |
| x %= y | x = x % y (0) |
Operators
| OPERATORS | WHAT IT DOES |
| x + y (Numeric) | Adds x and y together |
| x + y (String) | Concatenates text x and text y together (ie, "check" + "box" "checkbox") |
| x y | Subtracts y from x |
| x * y | Multiples x and y together |
| x / y | Divides x by y |
| x % y | Modulus of x and y (ie, the remainder when x is divided by y) |
| x++, ++x1 | Adds on to x (same as x = x + 1) |
| x--, --x1 | Subtracts one from x (same as x = x 1) |
| -x | Reverse the sign of x |
1x++ and ++y are not immediately obvious statements! Put the signs before the variable and it immediately changes. Place them after and it changes afterwards.
Unary operators converts a single expression into a single, more complex expression. The operator in the expression 3 is a unary operator which performs the operation of negation on the operand 3.
Binary operators combine two expressions into a single, or more complex expression. They operator on two operands. (x + y)
Ternary operator (?:) (also know as the Conditional operator) combines the value of three expressions into a single expression.
var username = prompt("Please enter your name", "Frank");
var greeting = "Hello ";greeting += ((username != null) ? username : "there");
If the user provides a name, ie. Frank, then we would end up with
NOTE: greeting += someStr is really greeting = greeting + someStrgreeting == "Hello Frank"
NOTE: greeting += ((username != null) ? username : "there");
is equivalent to the following below:if (username != null) { // if there is something in the prompt then
greeting = greeting + username; // OR greeting += username;
}
else { // if the prompt is empty or cancelled then
greeting = greeting + "there"; // OR greeting += there;
}OR we can really shorten the above example to
if (username) greeting += username;
else greeting += "there";
An example of the ternary operator in "real code". (Annotated Version)
There are a group of symbols used in JavaScript that refer to the basic "logical operations". These are AND, OR, and NOT.Logical Operators
| OPERATOR | WHAT IT DOES |
| && | Logical "AND" returns true when both operands are true; otherwise it returns false |
| || | Logical "OR" returns true if either operand is true. It only returns false when both operands are false |
| ! | Logical "NOT"returns true if the operand is false and false if the operand is true. This is a unary operator and precedes the operand |
As is often the case, the hardest part about learning to use logical operators is remembering what the symbols mean. In most cases, you'll find the basic ideas pretty intuitive as long as you can easily read and write the symbols.
Short-circuit evaluation uses the following rules:
For example:
var x = 10;
var y = 20;(x > y) && (x < y) // would immediately evaluate to false once the first part of the expression (x > y) is evaluated to false
/* Likewise */
(y > x) || (x > y) // is evaluated to true simply because the first part of the expression (y > x) is true
These examples use comparison operators, which we will be discussing next.
Because the logical "not" operator (!) takes a single operator, there is no short-circuit evaluation for it.
Youll often want to compare the value of one variable with another, or the value of a variable against a literal value (ie, a value typed into the expression). For example, you might want to compare the value of the day of the week to "Tuesday," and you can do this by checking if todaysDate == "Tuesday".
Tip
If you are comparing strings, be aware that "a" is greater than "A" and that "abracadabra" is less than "be". (Why "a" is greater than "A" )
Comparisons
|
COMPARISONS |
WHAT IT DOES |
| x == y | Returns true if x and y are equal |
| x != y | Returns true if x and y are not equal |
| x > y | Returns true if x is greater than y |
| x >= y | Returns true if x is greater or equal to y |
| x < y | Returns true if x is less than y |
| x <= y | Returns true if x is less or equal to y |
| x && y | Returns true if both x and y are true |
| x || y | Returns true if either x or y are true |
| !x | Returns true if x is false |
Note: in JavaScript, all comparison operators are binary operators.
If the types of the two values differ, attempt to convert them into the same type so they can be compared.
Objects, arrays, and functions are compared by reference. This means that two variables are equal only if they refer to the same object. Two separate arrays are never equal by the definition of the == operator, even if they contain identical elements.
Comparison operators can be used to compare numbers as well as strings
1) 1 == 1 (returns ?)
2) 3 < 1 (returns ?)
3) 5 >= 4 (returns ?)
4) "the" != "he" (returns ?)
5) 4 == "4" (returns ?)
6) 4 == "a4" (returns ?)
7) true == 1 (returns ?)
8) true == 0 (returns ?)
9) a == b (returns ?) if a = new Array(1,2) and b = new Array(1,2)
How
to use logical & comparison operators
You can use logical operators to create statements that "evaluate" to either true or false. The following examples illustrate this:
5 == 5
This statement evaluates to true because 5 is EQUAL TO 5.5 == 6
This statement evaluates to false because 5 isn't EQUAL TO 6.5 != 6
This statement evaluates to true because 5 is NOT EQUAL TO 6.5==5 && 6==6
This statement evaluates to true because statement one AND statement two are both true.5==5 && 5==6
This statement evaluates to false because statement one AND statement two are not both true, (even though statement one is true).5==5 || 5==6
This statement evaluates to true because either statement one OR statement two is true.
Conditional expressions are a little different than the others, because a conditional expression can evaluate to one of two different values based on a condition. The structure of a conditional expression is:
(condition) ? val1 : val2
Note: This should look familiar, remember the ternary operator?
(day == "Saturday") ? "Weekend!" : "Not Saturday!"
Evaluates to "Weekend!" when day is "Saturday". Otherwise, the expression evaluates to "Not Saturday!"
Concatenation returns the union of two strings so that
"Welcome to " + "the World of JavaScript"
Evaluates to a single string with the value "Welcome to the World of JavaScript". As with numbers, this can be done with a short cut concatenation operator. For example:
var welcome = "Welcome to ";
welcome += "the World of JavaScript";
would assign the string "Welcome to the World of JavaScript" to the variable welcome.
document.write(welcome + "the World of JavaScript");
document.write(welcome, "the", " World of JavaScript");
would write the string "Welcome to the World of JavaScript" to the document.
Because expressions can be the operands for other expressions, it is necessary to understand operator precedence. Operator precedence is the set of rules that determines the order in which these compound expressions are evaluated.
The operators that you have learned are evaluated in the following order (from lowest precedence to highest):
- Assignment operators (=, +=, -=, *=, /=, %=)
- Conditional (?:)
- Logical or (||)
- Logical and (&&)
- Equality (==, !=)
- Relational (<, <=, >=, >)
- Addition/Subtraction (+, -)
- Multiply/divide/modulus (*, /, %)
- Parentheses(())
Examples:
- 5 + 3 * 2 = 11 but (5 + 3) * 2 = 16
- false || true && false ==> false