The+ operator acts in two different ways depending on the type of its two operands. If one or both of them are strings, it acts as a string concatenator. If both are numeric, it acts as an arithmetic addition.
An example of string concatenation is"one " + "world" resulting in"one world". If one of the two operands isn't a string, it is implicitly converted to a string before the+ operation takes place.
"use strict";// regular concatenationconstword_1="one";constword_2="world";letresult=word_1+" "+word_2;alert(result);// "one world"// implicit type conversionconstarr=[41,42,43];result=word_1+arr+word_2;// first, the array is converted to a stringalert(result);// "one41,42,43world"// ditoconstx=1;result=x+word_2;alert(result);// "1world"
JavaScript has the arithmetic operators+,-,*,/,% (remainder), and** (exponentiation). These operators work the way you learned in mathematics. Multiplication and division will be calculated before addition and subtraction. If you want to change such precedence, you can use parenthesizes.
Hint: In opposite to some other languages, the division operation may result in a floating point number - it's not always a pure integer.
consta=12+5;// 17constb=12-5;// 7constc=12*5;// 60constd=12/5;// 2.4 Division results in floating point numbersconste=12%5;// 2 Remainder of 12/5 is 2constf=12-2*5;// 2 Multiplication is calculated firstconstg=(12-2)*5;// 50 Parenthesis are calculated first
Some mathematical operations, such as dividing by zero, cause the returned variable to be one of the error values - for example,infinity, orNaN (Not a number).
The return value of the remainder operator maintains the sign of the first operand.
The+ and- operators also have unary versions, where they operate only on one variable. When used in this fashion,+ returns the number representation of the object, while- returns its negative counterpart.
"use strict";consta=42;constb=+a;// b is 42constc=-a;// c is -42
As noted above,+ is also used as the string concatenation operator: If any of its arguments is a string or is otherwisenot a number, all arguments are converted to strings and concatenated together. All other arithmetic operators works the other way round: They attempt to convert their arguments into numbers before evaluating.
"use strict";consta=42;constb="2";constc="3";alert(a+b);// "422" (a string)alert(a*b);// 84 (a number)alert(b*c);// 6 (a number)
There are seven bitwise operators:&,|,^,~,>>,<<, and>>>.
These operators convert their operands to integers (truncating any floating point towards 0), and perform the specified bitwise operation on them. The logical bitwise operators,&,|, and^, perform theand,or, andxor on each individual bit and provides the return value. The~ (not operator) inverts all bits within an integer, and usually appears in combination with the logical bitwise operators.
Two bit shift operators,>>,<<, move the bits in one direction that has a similar effect to multiplying or dividing by a power of two. The final bit-shift operator,>>>, operates the same way, but does not preserve the sign bit when shifting.
These operators are kept for parity with the related programming languages, but are unlikely to be used in most JavaScript programs.
The assignment operator= assigns a value to a variable. Primitive types, such as strings and numbers, are assigned directly. However, function and object names are just pointers to the respective function or object. In this case, the assignment operator only changes the reference to the object rather than the object itself.For example, after the following code is executed, "0, 1, 0" will be alerted, even thougharray_A was passed to the alert, butarray_B was changed. This is because they are two references to the same object.
"use strict";constarray_A=[0,1,2];constarray_B=array_A;array_B[2]=0;alert(array_A);// 0, 1, 0
Similarly, after the next code snippet is executed,x is a pointer to an empty array.
"use strict";constz=[5];constx=z;z.pop();alert(x);
If the result of any of the above-shown arithmetic or bitwise operators shall be assigned to its first operand, you can use a shorter syntax. Combine the operator, e.g.,+, directly with the assignment operator= resulting in+=. As an examplex = x + 5 can be abbreviated asx += 5.
The abbreviated operator/assignment syntax reads:
| Arithmetic | Logical | Shift |
|---|---|---|
| += | &= | >>= |
| -= | |= | <<= |
| *= | ^= | >>>= |
| /= | ||
| %= |
For example, a common usage for+= in afor loop:
"use strict";constarr=[1,2,3];letsum=0;for(leti=0;i<arr.length;i++){sum+=arr[i];// same as: sum = sum + arr[i];}alert(sum);
Increment and decrement operators are a particular form of arithmetic operators:++ and--.a++ incrementsa and returns the old value ofa.++a incrementsa and returns the new value ofa. The decrement operator acts similarly but reduces the variable instead.
As an example, the next operations all perform the same task:
"use strict";leta=1;alert(a);// 1a=a+1;alert(a);// 2a+=1;alert(a);// 3a++;alert(a);// 4++a;alert(a);// 5// but this SHOWS something different; see next chapteralert(a++);// shows 5 againalert(a);// nevertheless, 'a' was incremented to 6
Increment operators may be written before or after a variable. The position decides whether they are pre-increment or post-increment operators, respectively. That affects the operation.
"use strict";// increment occurs before a is assigned to bleta=1;letb=++a;// a = 2, b = 2;// increment occurs to c after c is assigned to dletc=1;letd=c++;// c = 2, d = 1;
Due to the possibly confusing nature of pre and post-increment behavior, code can be easier to read if you avoid increment operators.
"use strict";// increment occurs before a is assigned to bleta=1;a+=1;letb=a;// a = 2, b = 2;// increment occurs to c after c is assigned to dletc=1;letd=c;c+=1;// c = 2, d = 1;
Comparison operators determine whether their two operands meet the given condition. They returntrue orfalse.
Concerning the 'equal' and 'not-equal' operators, you must take care.== is different from===. The first one tries to adapt the data type of the two types to each other and then compares the values. The second one compares the types as well as their values and returns onlytrue if type and value are identical:3 == "0003" istrue and3 === "3" isfalse.
| Op. | Returns | Notes |
|---|---|---|
| == | true, if the two operands are equal | May change an operand's type (e.g. a string as an integer). |
| === | true, if the two operands arestrictly equal | Does not change operands' types. Returnstrue if they are the same typeand value. |
| != | true, if the two operands are not equal | May change an operand's type (e.g. a string as an integer). |
| !== | true, if the two operands are notstrictly equal | Does not change the operands' types. Returnstrue if they differ in typeor value. |
| > | true, if the first operand is greater than the second one | |
| >= | true, if the first operand is greater than or equal to the second one | |
| < | true, if the first operand is less than the second one | |
| <= | true, if the first operand is less than or equal to the second one |
We recommend using thestrict versions (=== and!==) because the simple versions may lead tostrange and non-intuitive situations, such as:
0==''// true0=='0'// truefalse=='false'// false (''Boolean to string'')false=='0'// true (''Boolean to string'')false==undefined// falsefalse==null// false (''Boolean to null'')null==undefined// true
... although you might want:
0===''// false0==='0'// falsefalse==='false'// falsefalse==='0'// falsefalse===undefined// falsefalse===null// falsenull===undefined// false
The logical operators areand,or, andnot — written as&&,||, and!. The first two take two boolean operands each. The third takes one and returns its logical negation.
Operands are boolean values or expressions that evaluate to a boolean value.
"use strict";consta=0;constb=1;if(a===0&&b===1){// logical 'and'alert("a is 0 AND b is 1");}if(a===1||b===1){// logical 'or'alert("a is 1 OR b is 1");}
&& and|| areshort circuit operators: if the result is guaranteed after the evaluation of the first operand, it skips the evaluation of the second operand. Due to this, the&& operator is also known as the guard operator, and the|| operator is known as the default operator.
"use strict";// declare 'myArray' without initializationletmyArray;// runtime error!if(myArray.length>0){alert("The length of the array is: "+myArray.length);}// no error because the part after '&&' will not be executed!if(myArray&&myArray.length>0){alert("The length of the array is: "+myArray.length);}
The! operator determines the inverse of the given boolean value:true becomesfalse andfalse becomestrue.
Note: JavaScript represents false by either a Boolean false, the number 0, NaN, an empty string, or the built-in types undefined or null. Any other value is treated as true.
Concerning the precedence of the three operators,! is evaluated first, followed by&&, and lastly||.
a || b && !c | | | | | | └ 1. ┘ | └───── 2. ───┘ └───────── 3. ───────┘
More details on the relationship between precedence and short-circuiting are explained atMDN
? :The? : operator (also called the "ternary" operator) is an abbreviation of theif statement. First, it evaluates the part before the question mark. Then, iftrue, the part between the question mark and the colon is evaluated and returned, else the part behind the colon.
consttarget=(a==b)?c:d;
However, be careful when using it. Even though you can replace verbose and complex if/then/else chains with ternary operators, it may not be a good idea to do so. You can replace
if(p&&q){returna;}else{if(r!=s){returnb;}else{if(t||!v){returnc;}else{returnd;}}}
with
return(p&&q)?a:(r!=s)?b:(t||!v)?c:d
The above example is a poor coding style/practice. When other people edit or maintain your code, (which could very possibly be you,) it becomes much more difficult to understand and work with the code.
Instead, it is better to make the code more understandable. Some of the excessive conditional nesting can be removed from the above example.
if(p&&q){returna;}if(r!=s){returnb;}if(t||!v){returnc;}else{returnd;}
deletedelete obj.x unbinds propertyx from objectobj.
The delete keyword deletes a property from an object. It deletes both the value of the property and the property itself. After deletion, the property cannot be used before it is added back again. Thedelete operator is designed to be used onobject properties. It has no effect on variables or functions.
newnew cl creates a new object of typecl. Thecl operand must be a constructor function.
instanceofo instanceof c tests whethero is an object created by the constructorc.
typeoftypeof x returns a string describing the type ofx. Following values may be returned.
| Type | returns |
|---|---|
| boolean | "boolean" |
| number | "number" |
| string | "string" |
| function | "function" |
| undefined | "undefined" |
| null | "object" |
| others (array, ...) | "object" |