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 + parseInt(bar));
Logical operators allow you to evaluate a series of comparators using AND and OR operations.
Example 2.10. 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 Example 2.10, “Logical AND and OR operators”, the ||
operator returns the value of the first truthy comparator, or false if
no comparator is truthy. The &&
operator returns
the value of the last false comparator, or the value of the last
comparator if all values are truthy. Essentially, both operators return
the first value that proves them true or false.
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.11. 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.