Basic operators allow you to manipulate values.
Example 2.5. Concatenation
var foo = 'hello'; var bar = 'world'; console.log(foo + ' ' + bar); // 'hello world'
Example 2.7. Incrementing and decrementing
var i = 1; var j = ++i; // pre-increment: j equals 2; i equals 2 var k = i++; // post-increment: k equals 2; i equals 3
In JavaScript, numbers and strings will occasionally behave in ways you might not expect.
Example 2.8. Addition vs. concatenation
var foo = 1; var bar = '2'; console.log(foo + bar); // 12. uh oh
Example 2.9. Forcing a string to act as a number
var foo = 1; var bar = '2'; // coerce the string to a number console.log(foo + Number(bar));
The Number constructor, when called as a function (like above) will have the effect of casting its argument into a number. You could also use the unary plus operator, which does the same thing:
Example 2.10. Forcing a string to act as a number (using the unary-plus operator)
console.log(foo + +bar);
Logical operators allow you to evaluate a series of operands using AND and OR operations.
Example 2.11. Logical AND and OR operators
var foo = 1; var bar = 0; var baz = 2; foo || bar; // returns 1, which is true bar || foo; // returns 1, which is true foo && bar; // returns 0, which is false foo && baz; // returns 2, which is true baz && foo; // returns 1, which is true
Though it may not be clear from the example, the ||
operator returns the value of the first truthy operand, or, in cases
where neither operand is truthy, it'll return the last of both operands.
The &&
operator returns the value of the first
false operand, or the value of the last operand if both operands are
truthy.
Be sure to consult the section called “Truthy and Falsy Things” for more details on
which values evaluate to true
and which evaluate to
false
.
You'll sometimes see developers use these logical operators for
flow control instead of using if
statements. For
example:
// do something with foo if foo is truthy foo && doSomething(foo); // set bar to baz if baz is truthy; // otherwise, set it to the return // value of createBar() var bar = baz || createBar();
This style is quite elegant and pleasantly terse; that said, it can be really hard to read, especially for beginners. I bring it up here so you'll recognize it in code you read, but I don't recommend using it until you're extremely comfortable with what it means and how you can expect it to behave.
Comparison operators allow you to test whether values are equivalent or whether values are identical.
Example 2.12. Comparison operators
var foo = 1;
var bar = 0;
var baz = '1';
var bim = 2;
foo == bar; // returns false
foo != bar; // returns true
foo == baz; // returns true; careful!
foo === baz; // returns false
foo !== baz; // returns true
foo === parseInt(baz); // returns true
foo > bim; // returns false
bim > baz; // returns true
foo <= baz; // returns true
Copyright Rebecca Murphey, released under the Creative Commons Attribution-Share Alike 3.0 United States license.