Operators
JavaScript's numeric operators include +, -, *, /, % (remainder), and ** (exponentiation). Values are assigned using =. Each binary operator also has a compound assignment counterpart such as += and -=, which extend out to x = x operator y.
x += 5;
x = x + 5;
You can use ++ and -- to increment and decrement respectively. These can be used as a prefix or postfix operators.
The + operator also does string concatenation:
"hello" + " world"; // "hello world"
If you add a string to a number (or other value) everything is converted into a string first. This might trip you up:
"3" + 4 + 5; // "345"
3 + 4 + "5"; // "75"
Adding an empty string to something is a useful way of converting it to a string itself.
Comparisons in JavaScript can be made using <, >, <= and >=, which work for both strings and numbers. For equality, the double-equals operator performs type coercion if you give it different types, with sometimes interesting results. On the other hand, the triple-equals operator does not attempt type coercion, and is usually preferred.
123 == "123"; // true
1 == true; // true
123 === "123"; // false
1 === true; // false
The double-equals and triple-equals also have their inequality counterparts: != and !==.
JavaScript also has bitwise operators and logical operators. Notably, logical operators don't work with boolean values only — they work by the "truthiness" of the value.
const a = 0 && "Hello"; // 0 because 0 is "falsy"
const b = "Hello" || "world"; // "Hello" because both "Hello" and "world" are "truthy"
The && and || operators use short-circuit logic, which means whether they will execute their second operand is dependent on the first. This is useful for checking for null objects before accessing their attributes:
const name = o && o.getName();
Or for caching values (when falsy values are invalid):
const name = cachedName || (cachedName = getName());
For a comprehensive list of operators, see the guide page or reference section. You may be especially interested in the operator precedence.
Grammar
JavaScript grammar is very similar to the C family. There are a few points worth mentioning:
- Identifiers can have Unicode characters, but they cannot be one of the reserved words.
- Comments are commonly
//or/* */, while many other scripting languages like Perl, Python, and Bash use#. - Semicolons are optional in JavaScript — the language automatically inserts them when needed. However, there are certain caveats to watch out for, since unlike Python, semicolons are still part of the syntax.
For an in-depth look at the JavaScript grammar, see the reference page for lexical grammar.