revision:
Operand - operators: the numbers (in an arithmetic operation) are called operands. The operation (to be performed between the two operands) is defined by an operator. An operator is unary if it has a single operand. An operator is binary if it has two operands. Operations run from left to right.
Grouping operators: operations within brackets are executed earlier than those outside.
Order of operations: B I D M A S, i.e. brackets, indices, division, multiplication, addition, substraction.
<div class="spec"> <a id="id1"></a><br> <a id="id2"></a><br> <a id="id3"></a> </div> <script> document.getElementById('id1').innerHTML = "string + number: " +(2+2+"1"); document.getElementById('id2').innerHTML = "string + number: " + (2+"2"+1); document.getElementById('id3').innerHTML = "string + number: " + ("1"+2+3); </script>
The assignment operator (=) assigns a value to a variable.
The + operator can also be used to add (concatenate) strings. When used on strings, the "+" operator is called the concatenation operator.
Adding two numbers, will return the sum, but adding a number and a string will return a string. The rule is simple: if either operand is a string, the other one is converted into a string as well.
String concatenation and conversion is a special feature of the binary plus "+". If the operand is not a number, the unary plus converts it into a number.
P.S. Other arithmetic operators work only with numbers and always convert their operands to numbers.
<div class="spec"> <a id="id4"></a><br><br> <a id="id5"></a><br><br> <a id="id6"></a><br><br> <a id="id7"></a><br><br> <a id="id8"></a><br><br> <a id="id9"></a><br><br> <a id="id10"></a><br><br> <a id="id11"></a><br><br> <a id="id12"></a><br><br> <a id="id13"></a><br><br> <a id="id14"></a><br><br> </div> <script> let s = "my" + "string"; document.getElementById('id4').innerHTML = "string + string: " + s; document.getElementById('id5').innerHTML = "string + number: " + ("1" + 2); document.getElementById('id6').innerHTML = "string + number: " + (2 + "1"); let x=1; document.getElementById('id7').innerHTML = "positive number: " + x; let y = -2; document.getElementById('id8').innerHTML = "negative number: " + y; document.getElementById('id9').innerHTML = "true: " + true; document.getElementById('id10').innerHTML = "empty variable" +''; let apples = "2"; let oranges = "3"; document.getElementById('id11').innerHTML = "addition: " + (apples + oranges); let apples1 = '2'; let oranges1 = '5'; document.getElementById('id12').innerHTML = "adding of string numbers: " + (+apples1 + +oranges1); document.getElementById('id13').innerHTML = "adding of string numbers: " + (Number(apples1) + Number(oranges1)); let apples2 = 2; let oranges2 = 3; document.getElementById('id14').innerHTML = "adding numbers: " +(apples2 + oranges2); </script>
<div class="spec"> <a id="id16"></a> </div> <script> document.getElementById('id16').innerHTML = ("6"/"2"); </script>
<div class="spec"> <a id="id18"></a><br><br> <a id="id19"></a><br><br> <a id="id20"></a><br><br> <a id="id21"></a> </div> <script> document.getElementById('id18').innerHTML = (10/2); let radius = 7;let pi = 3.1415; let result2 = radius % 3; let result3 = pi * radius**2; document.getElementById('id19').innerHTML = result2; document.getElementById('id20').innerHTML = result3; let result4 = 5 * (10-3)**2; document.getElementById('id21').innerHTML = result4; </script>
"x**y" produces the same result as "Math.pow(x,y)".
Instead of using the Math.pow() function to raise a number to a power, you can use the ** operator as a shorthand.
longhand
Math.pow(2,3); // 8 Math.pow(2,2); // 4 Math.pow(4,3); // 64 const power = Math.pow(4, 3); // 64
shorthand
2**3 // 8 2**2 // 4 4**3 // 64 const power = 4**3; // 64
The += assignment operator can also be used to add (concatenate) strings.
The equality operator (==) checks whether its two operands are equal, returning a Boolean result. Double equals (==) is a "comparison operator" that transforms the operands having the same type before comparison. It tests for abstract equality, meaning that before doing the equality comparison it performs the necessary type conversion.
The equality operators (== and !=) use the "abstract equality comparison algorithm" to compare two operands:
if the operands are both objects, return "true" only if both operands reference the same object;
if one operand is "null" and the other is "undefined", return "true";
if the operands are of different types, try to convert them to the same type before comparing:
when comparing a number to a string, try to convert the string to a numeric value;
if one of the operands is Boolean, convert the Boolean operand to 1 if it is true and +0 if it is false;
if one of the operands is an object and the other is a number or a string, try to convert the object to a primitive using the object's valueOf() and toString() methods.
If the operands have the same type, they are compared as follows:
string : return "true" only if both operands have the same characters in the same order;
number : return "true" only if both operands have the same value; +0 and -0 are treated as the same value;
if either operand is NaN, return false;
boolean : return "true" only if operands are both true or both false.
The strict equality operator (===) checks whether its two operands are equal, returning a Boolean result. The strict equality operator always considers operands of different types to be different. It does not attempt type conversion.
The strict equality operators (=== and !==) use the strict equality comparison algorithm to compare two operands:
if the operands are of different types, return "false".
if both operands are objects, return "true" only if they refer to the same object;
if both operands are "null" or both operands are "undefined", return true;
if either operand is NaN, return "false".
Otherwise, compare the two operand's values:
numbers must have the same numeric values; +0 and -0 are considered to be the same value;
strings must have the same characters in the same order;
booleans must be both "true" or both "false".
syntax:
equality operator: x == y
strict equality operator: x=== y
equality operator
<div class="spec"> <p class="spec" style="margin-left:5vw;" id="op-01"></p> <p class="spec" style="margin-left:5vw;" id="op-02"></p> <p class="spec" style="margin-left:5vw;" id="op-03"></p> <p class="spec" style="margin-left:5vw;" id="op-04"></p> <p class="spec" style="margin-left:5vw;" id="op-05"></p> <p class="spec" style="margin-left:5vw;" id="op-06"></p> <p class="spec" style="margin-left:5vw;" id="op-07"></p> </div> <script> const string1 = "hello"; const string2 = String("hello"); const string3 = new String("hello"); const string4 = new String("hello"); console.log(string1 == string2); console.log(string1 == string3); console.log(string2 == string3); console.log(string3 == string4); console.log(string4 == string4); document.getElementById("op-01").innerHTML = "hello == String('hello'): " + (string1 == string2); document.getElementById("op-02").innerHTML = "hello == new String('hello'): " + (string1 == string3); document.getElementById("op-03").innerHTML = "String('hello') == new String('hello'): " + (string2 == string3); document.getElementById("op-04").innerHTML = "new String('hello') == new String('hello'): " + (string3 == string4); document.getElementById("op-05").innerHTML = "new String('hello') == new String('hello'): " + (string4 == string4); </script>
strict equality operator
<div class="spec"> <p class="spec" style="margin-left:5vw;" id="op-08"></p> <p class="spec" style="margin-left:5vw;" id="op-09"></p> <p class="spec" style="margin-left:5vw;" id="op-10"></p> <p class="spec" style="margin-left:5vw;" id="op-11"></p> <p class="spec" style="margin-left:5vw;" id="op-12"></p> <p class="spec" style="margin-left:5vw;" id="op-13"></p> <p class="spec" style="margin-left:5vw;" id="op-14"></p> </div> <script> console.log("hello" === "hello"); // true console.log("hello" === "hola"); // false console.log(3 === 3); // true console.log(3 === 4); // false console.log(true === true); // true console.log(true === false); // false console.log(null === null); // true document.getElementById("op-08").innerHTML = '"hello" === "hello": ' + ("hello" === "hello"); document.getElementById("op-09").innerHTML = '"hello" === "hola": ' + ("hello" === "hola"); document.getElementById("op-10").innerHTML = '3 === 3: ' + (3 === 3); document.getElementById("op-11").innerHTML = '3 === 4: ' + (3 === 4); document.getElementById("op-12").innerHTML = 'true === true: ' + (true === true); document.getElementById("op-13").innerHTML = 'true === false: ' + (true === false); document.getElementById("op-14").innerHTML = 'null === null: ' + (null === null); </script>
<div class="spec"> <a id="id31"></a> <a id="id32"></a> <a id="id33"></a> <a id="id34"></a> </div> <script> let age = 25; document.getElementById('id31').innerHTML = "age = 25: " + (age == 25); document.getElementById('id32').innerHTML = "age = 30: " + (age == 30); let name = 'shaun'; document.getElementById('id33').innerHTML = "name = shaun: " + (name = 'shaun'); document.getElementById('id34').innerHTML = "name = Shaun: " + (name = 'Shaun'); </script>
<div class="spec"> <a id="id41"></a><br> <a id="id42"></a><br> <a id="id43"></a><br> <a id="id44"></a> </div> <script> let age_d = 25; document.getElementById('id41').innerHTML = "age_d > 30: " + (age_d > 20); let name_a = 'shaun'; document.getElementById('id42').innerHTML = "name_a > crystal: " + (name_a > 'crystal'); document.getElementById('id43').innerHTML = "name_a > Shaun: " + (name_a > 'Shaun'); document.getElementById('id44').innerHTML = "name_a > Crystal: " + (name_a > 'Crystal'); </script>
<div class=spec> <input id="ouderdom" value="18" /> <button onclick="myFunction()">Try it</button> <p id="id51"></p> </div> <script> function myFunction() { let ouderdom = document.getElementById("ouderdom").value; let voteable = (age < 18) ? "Too young":"Old enough"; document.getElementById("id51").innerHTML = voteable + " to vote."; } </script>
Ternary operator can be used to compress if-else statements. "if else statements" can be written in one line using the ternary (? :) operator. The conditional (ternary) operator is the only JavaScript operator that takes three operands:
a condition followed by a question mark (?),
then an expression to execute if the condition is truthy followed by a colon (:),
and finally the expression to execute if the condition is falsy.
longhand
const x = 20; let answer; if (x > 10) { answer = "greater than 10"; } else { answer = "less than 10"; }
shorthand
const answer = x > 10 ? "greater than 10" : "less than 10"; const answer = x > 10 ? "greater than 10" : x < 5 ? "less than 5" : "between 5 and 10"; group = age > 18 ? "Adult" : "Child";
ternary operator - longhand and shorthand
longhand
let info; if (value < minValue) { info = "Value is too small"; } else if (value > maxValue) { info = "Value is too large"; } else { info = "Value is in range"; }
shorthand
const info = value < minValue ? "Value is too small" : value > maxValue ? "Value is too large" : "Value is in range";
Toggle display of an element: you can easily toggle between hiding and displaying an element with the single line method.
Example - code
const toggle = element => element.style.display = (element.style.display === "none" ? "block" : "none")
const toggle = ele => (ele.style.display = (ele.style.display === 'none') ? 'block' : 'none');
const toggle = ele => ele.hidden = !ele.hidden;
<div class="spec"> <a id="id52"></a><br> <a id="id53"></a><br> <a id="id54"></a><br> <a id="id55"></a> </div> <script> document.getElementById('id52').innerHTML = "age == 25: " + (age == 25); document.getElementById('id53').innerHTML = "age == '25': " + (age == '25'); document.getElementById('id54').innerHTML = "age != 25: " + (age != 25); document.getElementById('id55').innerHTML = "age != '25': " + (age != '25'); </script>
<div class="spec"> <a id="id56"></a><br> <a id="id57"></a><br> <a id="id58"></a><br> <a id="id59"></a> </div> <script> document.getElementById('id56').innerHTML = "age === 25: " + (age === 25); document.getElementById('id57').innerHTML = "age === '25': " + (age === '25'); document.getElementById('id58').innerHTML = "age !== 25: " + (age !== 25); document.getElementById('id59').innerHTML = "age !== '25': " + (age !== '25'); </script>
The precedence of NOT "!" is the highest of all logical operators, so it always executes first, before && or ||.
<div class="spec"> <a id="id60"></a><br><br> <a id="id61"></a><br><br> <a id="id62"></a><br><br> <a id="id63"></a><br><br> <a id="id64"></a> </div> <script> document.getElementById('id60').innerHTML = "true && true: " + (true && true); document.getElementById('id61').innerHTML = "false && true: " + (false && true); document.getElementById('id62').innerHTML = "true && false: " + (true && false); document.getElementById('id63').innerHTML = "false && false: " + (false && false); let hour = 12; let minute = 30; if(hour == 12 && minute == 30){ document.getElementById('id64').innerHTML = 'the time is 12:30'; } </script>
"Short-circuit evaluation" works with the && logical operator. The expressions are evaluated left to right.
Short circuit evaluation with &&(AND) logical operator means if the first expression evaluates to false then the whole expression will be false and the rest of the expressions will not be evaluated.
longhand
if (variable1 !== null || variable1 !== undefined || variable1 !== ' ') { let variable2 = variable1; }
shorthand
const variable2 = variable1 || 'new';
You can use the && operator if you want to execute a function if a variable is true. This operator will return false as soon as it gets any falsy value and will return the last true value if all the values are truthy.
longhand
if (isLoggedin) { redirectToHomepage(); } var age = 25; function driveCar() { return 'Driving Car'; }
shorthand
isLoggedin && redirectToHomepage(); var result = age > 18 && driveCar(); console.log(result); // Driving Car
<div class="spec"> <a id="id65"></a><br> <a id="id66"></a><br> <a id="id67"></a><br> <a id="id68"></a><br> <a id="id69"></a><br> <a id="id70"></a><br> <a id="id71"></a><br> <a id="id72"></a><br> <a id="id73"></a><br> <a id="id74"></a><br> <a id="id75"></a><br> <a id="id76"></a><br> <a id="id77"></a> </div> <script> document.getElementById('id65').innerHTML = "true || true: " + (true||true); document.getElementById('id66').innerHTML = "false || true: " + (false||true); document.getElementById('id67').innerHTML = "true || false: " + (true||false); document.getElementById('id68').innerHTML = "false || false: " + (false||false); let hour2 = 9; if(hour2 <10 || hour2 >18){ document.getElementById('id69').innerHTML = ('the ofice is closed'); } else document.getElementById('id70').innerHTML = (' the office is open'); let hour1 = 12; let isWeekend = true; if(hour1 <10 || hour1 >18 || isWeekend){ document.getElementById('id71').innerHTML = ('the office is closed'); } document.getElementById('id72').innerHTML = "1||10: " + (1||0); document.getElementById('id73').innerHTML = "true||'no matter what': " + (true||'no matter what'); document.getElementById('id74').innerHTML = "null||1: " + (null||1); document.getElementById('id75').innerHTML = "null||0||1: " +(null||0||1); document.getElementById('id76').innerHTML = "undefined||null||0: " + (undefined||null||0); let currentUser = "John"; let defaultUser = null; let name1 = currentUser || defaultUser || 'unnamed'; document.getElementById('id77').innerHTML = name1;
"Short-circuit evaluation" works with the || logical operators. The expressions are evaluated left to right.
Short circuit evaluation with ||(OR) logical operator means if the first expression evaluates to true then the whole expression will be true and the rest of the expressions will not be evaluated.
longhand
if (variable1 !== null || variable1 !== undefined || variable1 !== ' ') { let variable2 = variable1; }
shorthand
const variable2 = variable1 || 'new';
<div class="spec"> <a id="id78"></a><br> <a id="id79"></a><br> <a id="id80"></a><br> <a id="id81"></a><br> <a id="id82"></a> </div> <script> document.getElementById('id78').innerHTML = "!true: " + (!true); document.getElementById('id79').innerHTML = "!false: " + (!false); document.getElementById('id80').innerHTML = "!0: " + (!0); document.getElementById('id81').innerHTML = "!!0: " + (!!0); document.getElementById('id82').innerHTML = "!!'non-empty string': " + (!!'non-empty string'); </script>
The null coalescing operator "??" returns the right-hand side if the left-hand side is null. Otherwise, it returns the value on the left.
The nullish coalescing operator ?? provides a short way to choose the first “defined” value from a list. It is used to assign default values to variables.The point of this operator, is to allow you to return a value if the evaluated expression is either null or undefined. Pretty much like the || operator, the logic behind it is the same: if the left side of the expression is evaluated to "null" or "undefined", it will return the right side, otherwise, it will return the left side.
longhand
if(someValue){ console.log(someValue) } else { console.log("Nothing found") }
shorthand
console.log(someValue ?? "Nothing found")
The "typeof" operator returns the type of a variable, object, function, or expression
<div class="spec"> <a id="id83" style="margin-left:3vw;"></a> </div> <script> document.getElementById("id83").innerHTML = typeof "John" + "<br>" + typeof 3.14 + "<br>" + typeof NaN + "<br>" + typeof false + "<br>" + typeof [1, 2, 3, 4] + "<br>" + typeof {name:'John', age:34} + "<br>" + typeof new Date() + "<br>" + typeof function () {} + "<br>" + typeof myCar + "<br>" + typeof null; </script>
The "delete" operator deletes a property from an object.
The "in" operator returns true if the specified property is in the specified object, otherwise false.
<div class="spec"> <a id="id85"></a> </div> <script> // Arrays var cars = ["Saab", "Volvo", "BMW"]; // Objects var person = {firstName:"John", lastName:"Doe", age:50}; document.getElementById("id85").innerHTML = ("Saab" in cars) + "<br>" + (0 in cars) + "<br>" + (1 in cars) + "<br>" + (4 in cars) + "<br>" + ("length" in cars) + "<br>" + ("firstName" in person) + "<br>" + ("age" in person) + "<br>" + // Predefined objects ("PI" in Math) + "<br>" + ("NaN" in Number) + "<br>" + ("length" in String); </script>
The instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value. Its behavior can be customized with Symbol.hasInstance.
The "instanceof" operator returns true if the specified object is an instance of the specified object.
Syntax: object instanceof constructor
A "bitwise" operator treats their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers.
& — AND statement ; returns a one in each bit position for which the corresponding bits of both operands are ones.
| — OR statement ; returns a zero in each bit position for which the corresponding bits of both operands are zeros.
~ — NOT ; inverts the bits of its operand.
^ — XOR ; returns a zero in each bit position for which the corresponding bits are the same
<< — Left shift ; shifts a in binary representation b bits to the left, shifting in zeros from the right.
>> — Right shift ; shifts a in binary representation b bits to the right, discarding bits shifted off
>>> — Zero fill right shift ; shifts a in binary representation b bits to the right, discarding bits shifted off, and shifting in zeros from the left.
Instead of using the Math.floor() function to round a number down, you can use the ~~ operator as a shorthand. The bitwise NOT operator (i.e ~) will grab the numbers, it will turn them into a 32bits integer (discarding any extra bits) and then it will invert all their bits essentially turning any integer of value x into -(x+1).
The operator uses it twice on the same value, thus getting the same result as the Math.floor method.
longhand
Math.floor(4.9) === 4 //true Math.floor(5.25) // -> 5.0 const floor = Math.floor(4.8); // 4 let x = 3.8 let y = ~x //this turns x into -(3 + 1), remember, the number gets turned into an integer let z = ~y //this turns y (which is -4) into -(-4 + 1) which is 3
shorthand
~~4.9 === 4 //true ~~5.25 // -> 5.0 const floor = ~~4.8; // 4 let flooredX = ~~x //and this performs both steps from the left at the same time.
<div class="spec"> <canvas id="canvas" width="400" height="400"></canvas><br> <label for="theme">Select theme: </label> <select id="theme"> <option value="white">White</option> <option value="blue">Blue</option> </select><br><br> </div> <script> const select = document.querySelector('select'); const canvas = document.querySelector('canvas'); let ctx = canvas.getContext('2d'); ctx.font = "40px Helvetica"; ctx.strokeText("My website!", 100, 50); select.onchange = function() { select.value === 'blue' ? update('blue','white') : update('white','blue'); } function update(bgColor, textColor) { canvas.style.backgroundColor = bgColor; canvas.style.color = textColor; } </script>
<div class="spec"> <canvas id="canvas1" width="400" height="400"></canvas> <button onclick="bgChange()">Change color</button> </div> <script> function random(number) { return Math.floor(Math.random()*number); } function bgChange() { const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; canvas1.style.backgroundColor = rndCol; } </script>
let x = 1; x = -x; alert( x ); // -1, unary negation was applied let x = 1, y = 3; alert( y - x ); // 2, binary minus subtracts values
alert( 5 % 2 ); // 1, a remainder of 5 divided by 2 alert( 8 % 3 ); // 2, a remainder of 8 divided by 3
alert( 2 ** 2 ); // 2² = 4 alert( 2 ** 3 ); // 2³ = 8 alert( 2 ** 4 ); // 2⁴ = 16 alert( 4 ** (1/2) ); // 2 (power of 1/2 is the same as a square root) alert( 8 ** (1/3) ); // 2 (power of 1/3 is the same as a cubic root)
let s = "my" + "string"; alert(s); // mystring alert( '1' + 2 ); // "12" alert( 2 + '1' ); // "21" alert(2 + 2 + '1' ); // "41" and not "221" alert('1' + 2 + 2); // "122" and not "14" alert( 6 - '2' ); // 4, converts '2' to a number alert( '6' / '2' ); // 3, converts both operands to numbers
// No effect on numbers let x = 1; alert( +x ); // 1 let y = -2; alert( +y ); // -2 // Converts non-numbers alert( +true ); // 1 alert( +"" ); // 0 let apples = "2"; let oranges = "3"; alert( apples + oranges ); // "23", the binary plus concatenates strings let apples = "2"; let oranges = "3"; // both values converted to numbers before the binary plus alert( +apples + +oranges ); // 5 // the longer variant // alert( Number(apples) + Number(oranges) ); // 5
let x = 2 * 2 + 1; alert( x ); // 5 let a = 1; let b = 2; let c = 3 - (a = b + 1); alert( a ); // 3 alert( c ); // 0 let a, b, c; a = b = c = 2 + 2; alert( a ); // 4 alert( b ); // 4 alert( c ); // 4
let n = 2; n += 5; // now n = 7 (same as n = n + 5) n *= 2; // now n = 14 (same as n = n * 2) alert( n ); // 14 let n = 2; n *= 3 + 5; // right part evaluated first, same as n *= 8 alert( n ); // 16
let counter = 2; counter++; // works the same as counter = counter + 1, but is shorter alert( counter ); // 3 let counter = 2; counter--; // works the same as counter = counter - 1, but is shorter alert( counter ); // 1 let counter = 1; let a = ++counter; // (*) alert(a); // 2 let counter = 1; let a = counter++; // (*) changed ++counter to counter++ alert(a); // 1
let a = (1 + 2, 3 + 4); alert( a ); // 7 (the result of 3 + 4) // three operations in one line for (a = 1, b = 3, c = a * b; a < 10; a++) { ... }
alert( 2 > 1 ); // true (correct) alert( 2 == 1 ); // false (wrong) alert( 2 != 1 ); // true (correct) let result = 5 > 4; // assign the result of the comparison alert( result ); // true
alert( 'Z' > 'A' ); // true alert( 'Glow' > 'Glee' ); // true alert( 'Bee' > 'Be' ); // true
alert( '2' > 1 ); // true, string '2' becomes a number 2 alert( '01' == 1 ); // true, string '01' becomes a number 1 alert( true == 1 ); // true alert( false == 0 ); // true let a = 0; alert( Boolean(a) ); // false let b = "0"; alert( Boolean(b) ); // true alert(a == b); // true!
alert( 0 == false ); // true alert( '' == false ); // true alert( 0 === false ); // false, because the types are different
alert( null === undefined ); // false alert( null == undefined ); // true alert( null > 0 ); // (1) false alert( null == 0 ); // (2) false alert( null >= 0 ); // (3) true alert( undefined > 0 ); // false (1) alert( undefined < 0 ); // false (2) alert( undefined == 0 ); // false (3)
result = a || b; alert( true || true ); // true alert( false || true ); // true alert( true || false ); // true alert( false || false ); // false if (1 || 0) { // works just like if( true || false ) alert( 'truthy!' ); } let hour = 9; if (hour < 10 || hour > 18) { alert( 'The office is closed.' ); } let hour = 12; let isWeekend = true; if (hour < 10 || hour > 18 || isWeekend) { alert( 'The office is closed.' ); // it is the weekend }
result = value1 || value2 || value3; alert( 1 || 0 ); // 1 (1 is truthy) alert( null || 1 ); // 1 (1 is the first truthy value) alert( null || 0 || 1 ); // 1 (the first truthy value) alert( undefined || null || 0 ); // 0 (all falsy, returns the last value) let firstName = ""; let lastName = ""; let nickName = "SuperCoder"; alert( firstName || lastName || nickName || "Anonymous"); // SuperCoder true || alert("not printed"); false || alert("printed");
result = a && b; alert( true && true ); // true alert( false && true ); // false alert( true && false ); // false alert( false && false ); // false let hour = 12; let minute = 30; if (hour == 12 && minute == 30) { alert( 'The time is 12:30' ); } if (1 && 0) { // evaluated as true && false alert( "won't work, because the result is falsy" ); }
result = value1 && value2 && value3; // if the first operand is truthy, // AND returns the second operand: alert( 1 && 0 ); // 0 alert( 1 && 5 ); // 5 // if the first operand is falsy, // AND returns it. The second operand is ignored alert( null && 5 ); // null alert( 0 && "no matter what" ); // 0 alert( 1 && 2 && null && 3 ); // null alert( 1 && 2 && 3 ); // 3, the last one
result = !value; alert( !true ); // false alert( !0 ); // true alert( !!"non-empty string" ); // true alert( !!null ); // false
let user; alert(user ?? "Anonymous"); // Anonymous (user is undefined) let user = "John"; alert(user ?? "Anonymous"); // John (user is not null/udefined) let firstName = null; let lastName = null; let nickName = "Supercoder"; // shows the first defined value: alert(firstName ?? lastName ?? nickName ?? "Anonymous"); // Supercoder let height = 0; alert(height || 100); // 100 alert(height ?? 100); // 0
// Number addition and subtraction console.log(2 + 3 - 1); // expected output: 4 // Number multiplication and division console.log(4 * 3 / 2); // 12 / 2 // expected output: 6 // Number remainder and exponential console.log(11 % 3 ** 2); // 11 % 9 // expected output: 2
let x = 2; const y = 3; console.log(x); // expected output: 2 console.log(x = y + 1); // 3 + 1 // expected output: 4 console.log(x = x * y); // 4 * 3 // expected output: 12
console.log(5 & 13); // 0101 & 1101 = 0101 // expected output: 5; console.log(parseInt('0101', 2) & parseInt('1101', 2)); // expected output: 5; console.log(5 & 13 & 3); // 0101 & 1101 & 0011 = 0001 // expected output: 1; console.log(5 | 13); // 0101 | 1101 = 1101 // expected output: 13
const Rectangle = class { constructor(height, width) { this.height = height; this.width = width; } area() { return this.height * this.width; } }; console.log(new Rectangle(5, 8).area()); // expected output: 40
let x = 1; x = (x++, x); console.log(x); // expected output: 2 x = (2, 3); console.log(x); // expected output: 3
console.log(1 == 1); // expected output: true console.log('1' == 1); // expected output: true console.log(1 === 1); // expected output: true console.log('1' === 1); // expected output: false
function getFee(isMember) { return (isMember ? '$2.00' : '$10.00'); } console.log(getFee(true)); // expected output: "$2.00" console.log(getFee(false)); // expected output: "$10.00" console.log(getFee(1)); // expected output: "$2.00"
const Employee = { firstname: 'John', lastname: 'Doe' }; console.log(Employee.firstname); // expected output: "John" delete Employee.firstname; console.log(Employee.firstname); // expected output: undefined
let a, b, rest; [a, b] = [10, 20]; console.log(a); // expected output: 10 console.log(b); // expected output: 20 [a, b, ...rest] = [10, 20, 30, 40, 50]; console.log(rest); // expected output: Array [30,40,50]
function* foo() { yield 'a'; yield 'b'; yield 'c'; } let str = ''; for (const val of foo()) { str = str + val; } console.log(str); // expected output: "abc"
const getRectArea = function(width, height) { return width * height; }; console.log(getRectArea(3, 4)); // expected output: 12
console.log(1 + 2 * 3); // 1 + 6 // expected output: 7 console.log(1 + (2 * 3)); // 1 + 6 // expected output: 7 console.log((1 + 2) * 3); // 3 * 3 // expected output: 9 console.log(1 * 3 + 2 * 3); // 3 + 6 // expected output: 9
const car = { make: 'Honda', model: 'Accord', year: 1998 }; console.log('make' in car); // expected output: true delete car.make; if ('make' in car === false) { car.make = 'Suzuki'; } console.log(car.make); // expected output: "Suzuki"
const a = 3; const b = -2; console.log(a > 0 && b > 0); // expected output: false
const a = 3; const b = -2; console.log(!(a > 0 || b > 0)); // expected output: false
const a = 3; const b = -2; console.log(a > 0 || b > 0); // expected output: true
function Car(make, model, year) { this.make = make; this.model = model; this.year = year; } const car1 = new Car('Eagle', 'Talon TSi', 1993); console.log(car1.make); // expected output: "Eagle"
function Foo() { if (!new.target) { throw 'Foo() must be called with new'; } } try { Foo(); } catch (e) { console.log(e); // expected output: "Foo() must be called with new" }
const foo = null ?? 'default string'; console.log(foo); // expected output: "default string" const baz = 0 ?? 42; console.log(baz); // expected output: 0
const object1 = { a: 'foo', b: 42, c: {} }; console.log(object1.a); // expected output: "foo" const a = 'foo'; const b = 42; const c = {}; const object2 = { a: a, b: b, c: c }; console.log(object2.b); // expected output: 42 const object3 = { a, b, c }; console.log(object3.a); // expected output: "foo"
console.log(3 + 4 * 5); // 3 + 20 // expected output: 23 console.log(4 * 3 ** 2); // 4 * 9 // expected output: 36 let a; let b; console.log(a = b = 5); // expected output: 5
const adventurer = { name: 'Alice', cat: { name: 'Dinah' } }; const dogName = adventurer.dog?.name; console.log(dogName); // expected output: undefined console.log(adventurer.someNonExistentMethod?.()); // expected output: undefined
const person1 = {}; person1['firstname'] = 'Mario'; person1['lastname'] = 'Rossi'; console.log(person1.firstname); // expected output: "Mario" const person2 = { firstname: 'John', lastname: 'Doe' }; console.log(person2['lastname']); // expected output: "Doe"
function sum(x, y, z) { return x + y + z; } const numbers = [1, 2, 3]; console.log(sum(...numbers)); // expected output: 6 console.log(sum.apply(null, numbers)); // expected output: 6
const test = { prop: 42, func: function() { return this.prop; }, }; console.log(test.func()); // expected output: 42
console.log(typeof 42); // expected output: "number" console.log(typeof 'blubber'); // expected output: "string" console.log(typeof true); // expected output: "boolean" console.log(typeof undeclaredVariable); // expected output: "undefined";
void function test() { console.log('boo!'); // expected output: "boo!" }(); try { test(); } catch (e) { console.log(e); // expected output: ReferenceError: test is not defined }
function* foo(index) { while (index < 2) { yield index++; } } const iterator = foo(0); console.log(iterator.next().value); // expected output: 0 console.log(iterator.next().value); // expected output: 1
function* func1() { yield 42; } function* func2() { yield* func1(); } const iterator = func2(); console.log(iterator.next().value); // expected output: 42