Operators Flashcards
Unary, binary and tertiary operators
Unary Operators:
- Operate on a single operand.
- Example: !
(logical NOT), -
(negation), typeof
Binary Operators:
- Operate on two operands.
- Example: +
(addition), -
(subtraction), *
(multiplication), /
(division)
Ternary Operator:
- Operates on three operands.
- Often used as a shortcut for the if
statement.
- Example: condition ? expr1 : expr2
(If condition is true, evaluate expr1; otherwise, evaluate expr2)
“Expressions and operators - JavaScript | MDN” (developer.mozilla.org). Retrieved June 20, 2023.
Assignment operators
Assignment operators in
JavaScript are used to assign
values to variables.
-
=
: Assigns value to a variable
Example:x = 10;
-
+=
: Adds and assigns
Example:x += 5;
(same asx = x + 5;
) -
-=
: Subtracts and assigns
Example:x -= 5;
(same asx = x - 5;
) -
*=
: Multiplies and assigns
Example:x *= 5;
(same asx = x * 5;
) -
/=
: Divides and assigns
Example:x /= 5;
(same asx = x / 5;
) -
%=
: Modulus and assigns
Example:x %= 5;
(same asx = x % 5;
) -
**=
: Exponentiation and assigns
Example:x **= 2;
(same asx = x ** 2;
) -
<<=
: Left shift and assigns
Example:x <<= 2;
(same asx = x << 2;
) -
>>=
: Right shift and assigns
Example:x >>= 2;
(same asx = x >> 2;
) -
>>>=
: Unsigned right shift and assigns
Example:x >>>= 2;
(same asx = x >>> 2;
) -
&=
: Bitwise AND and assigns
Example:x &= 5;
(same asx = x & 5;
) -
^=
: Bitwise XOR and assigns
Example:x ^= 5;
(same asx = x ^ 5;
) -
|=
: Bitwise OR and assigns
Example:x |= 5;
(same asx = x | 5;
)
“Assignment operators” (developer.mozilla.org). Retrieved June 20, 2023.
Comparison operators
Comparison operators are used in logical statements to determine equality or difference between variables or values.
Here are the main comparison operators in JavaScript:
-
==
(Equality) - checks if the values of two operands are equal or not; if yes, then the condition becomes true. May do type cohercion before checking the equality.
Example: (4 == '4'
) is true, but (4 == 5
) is false. -
===
(Strict equality) - checks if the values and types of two operands are equal or not; if yes, then the condition becomes true.
Example: (4 === 4
) is true, but (4 === '4
’) is false. -
!=
(Inequality) - checks if the values of two operands are not equal; if not, then the condition becomes true. May do type cohercion before checking the equality.
Example: (4 != 5
) is true, but (5 != '5'
) is false. -
!==
(Strict inequality) - checks if the values and types of two operands are not equal; if not, then the condition becomes true.
Example: (4 !== '4'
) is true, but (4 !== 4
) is false. -
>
(Greater than) - checks if the value of the left operand is greater than the value of the right operand; if yes, then the condition becomes true.
Example: (5 > 4
) is true, but (3 > 4
) is false. -
<
(Less than) - checks if the value of the left operand is less than the value of the right operand; if yes, then the condition becomes true.
Example: (3 < 4
) is true, but (5 < 4
) is false. -
>=
(Greater than or equal to) - checks if the value of the left operand is greater than or equal to the value of the right operand.
Example: (4 >= 4
) is true, but (3 >= 4
) is false. -
<=
(Less than or equal to) - checks if the value of the left operand is less than or equal to the value of the right operand.
Example: (3 <= 4
) is true, but (5 <= 4
) is false.
“Comparison operators” (developer.mozilla.org). Retrieved June 21, 2023.
Arithmetic operators
Arithmetic operators are used to perform arithmetic operations on numbers.
Here are the main arithmetic operators in JavaScript:
-
+
(Addition) - adds two numbers.
Example:5 + 2
evaluates to7
. -
-
(Subtraction) - subtracts the right-hand operand from the left-hand operand.
Example:5 - 2
evaluates to3
. -
*
(Multiplication) - multiplies two numbers.
Example:5 * 2
evaluates to10
. -
/
(Division) - divides the left-hand operand by the right-hand operand.
Example:5 / 2
evaluates to2.5
. -
%
(Modulus) - returns the remainder when the left-hand operand is divided by the right-hand operand.
Example:5 % 2
evaluates to1
. -
++
(Increment) - increases the value of a variable by1
.
Example: Ifx = 5
, then++x
setsx
to6
. -
--
(Decrement) - decreases the value of a variable by1
.
Example: Ifx = 5
, then--x
setsx
to4
. -
**
(Exponentiation) - raises the left-hand operand to the power of the right-hand operand.
Example:2 ** 3
evaluates to8
.
These operators can be used with numbers or variables containing numbers to perform calculations in JavaScript.
“Arithmetic operators” (developer.mozilla.org). Retrieved June 21, 2023.
Bitwise operators
A bitwise operator treats their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001
. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.
Here are the main bitwise operators in JavaScript:
-
&
(Bitwise AND) - Sets each bit to1
if both bits are1
.
Example:5 & 1
evaluates to1
(0101 & 0001
). -
|
(Bitwise OR) - Sets each bit to1
if one of the two bits is1
.
Example:5 | 1
evaluates to5
(0101 | 0001
). -
^
(Bitwise XOR) - Sets each bit to1
if only one of the two bits is1
.
Example:5 ^ 1
evaluates to4
(0101 ^ 0001
). -
~
(Bitwise NOT) - Inverts all the bits.
Example:~5
evaluates to-6
(~0101
). -
<<
(Left Shift) - Shifts the left operand’s bits to the left, and fill in the right with 0s.
Example:5 << 1
evaluates to10
(0101 <<
1). -
>>
(Sign-Propagating Right Shift) - Shifts the left operand’s bits to the right, discarding bits shifted off.
Example:5 >> 1
evaluates to2
(0101 >> 1
). -
>>>
(Zero-Fill Right Shift) - Shifts the left operand’s bits to the right, discarding bits shifted off, and shifts in 0s from the left.
Example:5 >>> 1
evaluates to2
(0101 >>> 1
).
Bitwise operators are often used in low-level programming, such as working with binary data and memory manipulation. They can be powerful tools but are not as commonly used in higher-level web development tasks.
“Bitwise operators” (developer.mozilla.org). Retrieved June 21, 2023.
What are logical operators?
Logical operators are typically used with boolean (logical) values to perform logical operations. The primary logical operators in JavaScript are:
- Logical AND (
&&
) - Logical OR (
||
) - Logical NOT (
!
)
They return a boolean value when used with boolean values. However, the &&
and ||
operators actually return the value of one of the specified operands when used with non-boolean values.
“Logical operators” (developer.mozilla.org). Retrieved June 22, 2023.
What is the logical AND (&&
) operator?
The logical AND (&&
) operator returns the first operand if it can be converted to false; otherwise, it returns the second operand. So, when used with boolean values, &&
returns true
if both operands are true
; otherwise, it returns false
.
Example:
const a1 = true && true; // Returns true const a5 = "Cat" && "Dog"; // Returns "Dog" const a6 = false && "Cat"; // Returns false
“Logical operators” (developer.mozilla.org). Retrieved June 22, 2023.
What is the logical OR (||
) operator?
The Logical OR (||
) operator returns the first operand if it can be converted to true
; otherwise, it returns the second operand. So, when used with Boolean values, ||
returns true
if either operand is true
; if both are false
, it returns false
.
Example:
const o1 = true || true; // Returns true const o5 = "Cat" || "Dog"; // Returns "Cat" const o6 = false || "Cat"; // Returns "Cat"
“Logical operators” (developer.mozilla.org). Retrieved June 22, 2023.
What is the logical NOT (!
) operator?
The logical NOT (!
) operator returns false
if its single operand can be converted to true
; otherwise, it returns true
.
Example:
const n1 = !true; // Returns false const n3 = !"Cat"; // Returns false
“Logical operators” (developer.mozilla.org). Retrieved June 22, 2023.
What is short-circuit evaluation?
As logical expressions are evaluated left to right, they are tested for possible “short-circuit” evaluation using the following rules:
-
false && anything
is short-circuit evaluated tofalse
. -
true || anything
is short-circuit evaluated to true.
The rules of logic guarantee that these evaluations are always correct. Note that the "anything"
part of the above expressions is not evaluated, so any side effects of doing so do not take effect.
“Logical operators” (developer.mozilla.org). Retrieved June 22, 2023.
What is the Nullish coalescing operator (??
)?
The Nullish coalescing operator (??
) is similar to the logical OR (||
) operator, but it only returns the second expression when the first one is “nullish”, i.e., null
or undefined
. It is thus the better alternative to provide defaults when values like ''
or 0
are valid values for the first expression.
“Logical operators” (developer.mozilla.org). Retrieved June 22, 2023.
What are BigInt operators?
BigInt
operators in JavaScript operate on BigInt values, which are used to represent integers of arbitrary length. Most operators that can be used between numbers can also be used between BigInt
values, including addition (+
), subtraction (-
), multiplication (*
), and division (/
).
Example:
// BigInt addition const a = 1n + 2n; // Returns 3n
Note: Division with BigInts rounds towards zero.
“BigInt operators” (developer.mozilla.org). Retrieved June 23, 2023.
What is the exception to using operators with BigInts?
The unsigned right shift operator (>>>
) is not defined for BigInt values. This is because a BigInt does not have a fixed width, so technically it does not have a “highest bit”.
Example:
const d = 8n >>> 2n; // TypeError: BigInts have no unsigned right shift, use >> instead
“BigInt operators” (developer.mozilla.org). Retrieved June 23, 2023.
Can you mix BigInts and numbers in JavaScript calculations?
No, BigInts and numbers are not mutually replaceable. Mixing them in calculations will result in a TypeError
.
Example:
const a = 1n + 2; // TypeError: Cannot mix BigInt and other types
This is because BigInt
is neither a subset nor a superset of numbers. BigInt
s have higher precision than numbers when representing large integers, but cannot represent decimals, so implicit conversion on either side might lose precision.
“BigInt operators” (developer.mozilla.org). Retrieved June 23, 2023.
How do you explicitly convert between BigInts and numbers?
You can use explicit conversion to signal whether you want the operation to be a number operation or a BigInt
one.
Example:
const a = Number(1n) + 2; // Returns 3 const b = 1n + BigInt(2); // Returns 3n
“BigInt operators” (developer.mozilla.org). Retrieved June 23, 2023.
Can you compare BigInts with numbers?
Yes, you can compare BigInts with numbers using relational operators in JavaScript.
Example:
const a = 1n > 2; // Returns false const b = 3 > 2n; // Returns true
“BigInt operators” (developer.mozilla.org). Retrieved June 23, 2023.
What is the concatenation operator?
The concatenation operator (+
) in JavaScript is used to concatenate, or join, two string values together, returning another string that is the union of the two operand strings.
Example:
console.log("my " + "string"); // console logs the string "my string".
“String operators” (developer.mozilla.org). Retrieved June 23, 2023.
How can the shorthand assignment operator be used with strings?
The shorthand assignment operator (+=
) can be used to concatenate strings in JavaScript. This operator adds the right operand to the left operand and then assigns the result to the left operand.
Example:
let mystring = "alpha"; mystring += "bet"; // Evaluates to "alphabet" and assigns this value to mystring.
“String operators” (developer.mozilla.org). Retrieved June 23, 2023.
What is the conditional (ternary) operator?
The conditional (ternary) operator is a unique JavaScript operator that takes three operands. It’s a shorthand way to express a simple if...else
statement and is used to assign one of two values based on a condition. The syntax is:
condition ? val1 : val2
If the condition is true
, the operator has the value of val1
. Otherwise, it has the value of val2
.
Example:
const status = age >= 18 ? "adult" : "minor";
In this example, the value "adult"
is assigned to the variable status if age is eighteen or more. Otherwise, it assigns the value “minor” to status.
“Conditional (ternary) operator” (developer.mozilla.org). Retrieved June 23, 2023.
What is the comma operator and where is it primarily used?
The comma operator (,
) in JavaScript evaluates both of its operands and returns the value of the last operand. It is primarily used inside a for loop, where it allows multiple variables to be updated each time through the loop.
For example, consider the following code that updates two variables in each iteration:
const x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; const a = [x, x, x, x, x]; for (let i = 0, j = 9; i <= j; i++, j--) { console.log(`a[${i}][${j}]= ${a[i][j]}`); }
Although the comma operator can be used outside of the loop, it is generally considered bad style to do so when not necessary. In most cases, two separate statements can and should be used instead.
“Comma operator” (developer.mozilla.org). Retrieved June 26, 2023.
What is the delete
operator used for?
The delete
operator is a unary operation that removes a property from an object. If the delete operation is successful, accessing that property will yield undefined
.
The operator returns true
if the operation is possible and false
if it’s not.
Example:
const myObj = { h: 4 }; delete myObj.h; // returns true (can delete user-defined properties)
“delete” (developer.mozilla.org). Retrieved June 26, 2023.
What is the “typeof” operator?
The typeof
operator in JavaScript returns a string indicating the type of the unevaluated operand. This operand can be a string, variable, keyword, or object. The operator helps to identify the data type of a variable or value.
For example:
typeof "Hello world"; // returns "string"
“typeof” (developer.mozilla.org). Retrieved June 26, 2023.
What are the possible return values of the “typeof” operator?
The typeof
operator in JavaScript can return one of the following types:
-
"number"
: when the operand is a numeric value. -
"string"
: when the operand is a string of text. -
"boolean"
: when the operand is a boolean value (true or false). -
"undefined"
: when the operand is an undefined value. -
"object"
: when the operand is an object, null, or an array. -
"function"
: when the operand is a function. -
"symbol"
: when the operand is a symbol (introduced in ECMAScript 2015). -
"bigint"
: when the operand is a BigInt number (introduced in ECMAScript 2020).
Note: The typeof
operator returns "object"
for null
because of a bug in the language that was never fixed for backward compatibility.
“typeof” (developer.mozilla.org). Retrieved June 26, 2023.
What is the void
operator in JavaScript?
The void
operator in JavaScript is used to evaluate an expression without returning a value. It can be useful in cases where you want to execute an expression but don’t need or want any value returned.
“void” (developer.mozilla.org). Retrieved June 26, 2023.
What is the in
operator and what does it return?
The in
operator in JavaScript is used to check if a specific property exists in an object or an array.
The syntax is :
'propNameOrNumber in objectName'
The in
operator returns a boolean value, true
if the specified property is found in the object, and false
if it is not.
The in
operator tests if a string or symbol property is present in an object or its prototype chain. If you want to check for only non-inherited properties, use Object.hasOwn() instead.
A property may be present in an object but have value undefined
. Therefore, x in obj
is not the same as obj.x === undefined
. To make in
return false after a property is added, use the delete
operator instead of setting that property’s value to undefined
.
You can also use the in
operator to check whether a particular private class field or method has been defined in an object. The operator returns true
if the property is defined, and false otherwise. This is known as a branded check, because it returns true
if and only if the object was created with that class constructor, after which you can safely access other private properties as well.
class C { #x; static isC(obj) { return #x in obj; } }
The above is an example of branded check
“in operator - JavaScript | MDN” (developer.mozilla.org). Retrieved July 10, 2023.
Give an example of how to use the in
operator.
Here is an example of using the in
operator with an array and an object in JavaScript:
// Arrays const trees = ["redwood", "bay", "cedar", "oak", "maple"]; console.log(0 in trees); // returns true // Custom objects const mycar = { make: "Honda", model: "Accord", year: 1998 }; console.log("make" in mycar); // returns true
“in” (developer.mozilla.org). Retrieved June 28, 2023.
What is the instanceof
operator and what does it return?
The instanceof
operator in JavaScript is used to check the type of an object at runtime. It returns a boolean value, true
if the object is an instance of the specified type, and false
if it is not.
The syntax is:
'objectName instanceof objectType'
“instanceof” (developer.mozilla.org). Retrieved June 28, 2023.
Give an example of how to use the instanceof
operator.
Here is an example of using the instanceof
operator in JavaScript:
const theDay = new Date(1995, 12, 17); if (theDay instanceof Date) { console.log('theDay is an instance of Date'); }
In this example, the console will log 'theDay is an instance of Date'
because theDay
is indeed an instance of the Date
object type.
“instanceof” (developer.mozilla.org). Retrieved June 28, 2023.
What is the purpose of the this
keyword in JavaScript?
The this
keyword in JavaScript is used to refer to the current object. Generally, this
refers to the calling object in a method. It can be used with either the dot or the bracket notation like this.propertyName
or this["propertyName"]
.
“this” (developer.mozilla.org). Retrieved June 29, 2023.
What is the use of the grouping operator ( )
?
The grouping operator ( )
in JavaScript is used to control the precedence of evaluation in expressions. It allows you to change the order in which operations are carried out in an expression.
For example:
a + b * c
is normally evaluated as a + (b * c)
, but by using the grouping operator, you can make it evaluate as (a + b) * c
.
“Grouping operator” (developer.mozilla.org). Retrieved June 29, 2023.
How is the new
keyword used?
The new
keyword is used in JavaScript to create an instance of a user-defined object type or one of the built-in object types.
It’s used as follows:
const objectName = new ObjectType(param1, param2, /* …, */ paramN);
“new” (developer.mozilla.org). Retrieved June 29, 2023.
What is the purpose of the super
keyword?
The super
keyword in JavaScript is used to call functions on an object’s parent. It’s especially useful with classes to call the parent constructor.
For instance, super(args);
calls the parent constructor and super.functionOnParent(args);
calls a function on the parent.
“super” (developer.mozilla.org). Retrieved June 29, 2023.