zhaoJian's Tech Notes

IT Course JavaScript Basics 040_Operators

Learning / JavaScript Basics ~11610 words · 30 min read - views

JavaScript operators are used to perform mathematical operations, comparisons, logical operations, and return results.

Arithmetic Operators

  • +: Addition
  • -: Subtraction
  • *: Multiplication
  • /: Division
  • %: Modulus (remainder)
  • **: Exponentiation

Example:

let a = 5;
let b = 2;
console.log(a + b); // Output 7
console.log(a - b); // Output 3
console.log(a * b); // Output 10
console.log(a / b); // Output 2.5
console.log(a % b); // Output 1
console.log(a**b); // Output 25

Assignment Operators

  • =: Assignment
  • +=: Addition assignment
  • -=: Subtraction assignment
  • *=: Multiplication assignment
  • /=: Division assignment
  • %=: Modulus assignment
  • **=: Exponentiation assignment
  • ??=: Nullish assignment, assigns only when the variable value is null or undefined

Example:

let x = 5;
x += 2; // x = x + 2; Output 7
x -= 2; // x = x - 2; Output 3
x *= 2; // x = x * 2; Output 10
x /= 2; // x = x / 2; Output 2.5
x %= 2; // x = x % 2; Output 1
x **= 2; // x = x ** 2; Output 25
x ??= 2; // Output 5, assigns 2 when x is null or undefined
console.log(x);

Comparison Operators

  • ==: Equal (type is automatically converted)
  • ===: Strict equal (both value and type are equal)
  • !=: Not equal
  • !==: Strict not equal
  • >: Greater than
  • <: Less than
  • >=: Greater than or equal
  • <=: Less than or equal

When encountering non-numeric values, they are first converted to numeric values before comparison. When encountering strings, the Unicode encoding of characters is compared bit by bit.

Example:

let a = 5;
let b = '5';
let c = 10;
console.log(a == b); // Output true, values are equal
console.log(a === b); // Output false, types are not equal
console.log(a != b); // Output false, values are equal
console.log(a !== b); // Output true, types are not equal
console.log(a > c); // Output false, 5 < 10
console.log(a < c); // Output true, 5 < 10
console.log(a >= c); // Output false, 5 <= 10
console.log(a <= c); // Output true, 5 <= 10

Logical Operators

When processing operands, logical operators convert them to boolean values and return the original value of the operand.

&&: Logical AND

Used to determine if conditions are simultaneously true. If all conditions are true, the result of the entire expression is true; otherwise, the result is false. The AND operation searches from left to right for the first false. If false is found, it stops calculation and returns the original value of this operand (short-circuit evaluation). If there is no false at the end, it returns the last true.

||: Logical OR

Used to determine if at least one condition is true. If at least one condition is true, the result of the entire expression is true; if all conditions are false, the result is false. The OR operation searches from left to right for the first true. If true is found, it stops calculation and returns the original value of this operand (short-circuit evaluation). If there is no true at the end, it returns the last false.

!: Logical NOT

Used to negate a boolean value. If a value is true, using the logical NOT operator negates it to false; if a value is false, it is negated to true. Logical NOT can also be used to convert non-boolean values to boolean values. It converts any value that is not null, undefined, 0, NaN, "" (empty string) to true, while these values themselves are converted to false.

Example:

let a = true;
let b = false;
let c = "hello";
let d = null;
console.log(a && b); // Output false
console.log(c && d); // Output null
console.log(a || b); // Output true
console.log(c || d); // Output hello
console.log(!a); // Output false
console.log(!d); // Output true

Ternary Operator

  • condition ? expr1 : expr2: If the condition is true, return expr1, otherwise return expr2.

Example:

let age = 18;
let status = (age >= 18) ? 'Adult' : 'Minor';
console.log(status); // Output 'Adult'

Nullish Coalescing Operator

The Nullish Coalescing Operator is an operator used to handle default values, typically used to ensure a variable has a non-null (not null and not undefined) value. The syntax of this operator is ??.

When using the nullish coalescing operator, it returns the first defined (not null and not undefined) operand. If the first operand is null or undefined, it returns the second operand.

Example:

let num1 = 0;
let num2 = 1;
let result = num1 ?? num2;
console.log(result); // Output 0, because num is not null or undefined
let user;
console.log(user ?? "Anonymous"); // Output Anonymous, because user is undefined

Bitwise Operators

  • &: Bitwise AND
  • |: Bitwise OR
  • ^: Bitwise XOR
  • ~: Bitwise NOT
  • <<: Left shift
  • >>: Right shift
  • >>>: Unsigned right shift

Example:

let a = 5; // Binary: 0101
let b = 3; // Binary: 0011
console.log(a & b); // Output 1 (Bitwise AND)
console.log(a | b); // Output 7 (Bitwise OR)
console.log(a ^ b); // Output 6 (Bitwise XOR)
console.log(~a); // Output -6 (Bitwise NOT)
console.log(a << 1); // Output 10 (Left shift)
console.log(a >> 1); // Output 2 (Right shift)

Other Operators

  • typeof: Returns a string indicating the type of the unevaluated operand.
  • instanceof: Used to test whether an object is an instance of a specified type.

Example:

let str = 'Hello';
console.log(typeof str); // Output 'string'
let arr = [1, 2, 3];
console.log(arr instanceof Array); // Output true

+ (Plus Sign)

In JavaScript, the plus sign + has multiple uses, including mathematical operations, string concatenation, and unary operations.

Mathematical Operation

Example:

let a = 5;
let b = 3;
let result = a + b;
console.log(result); // Output 8

If both are numbers, + is used to perform mathematical addition.

String Concatenation

Example:

let str1 = 'Hello';
let str2 = ' World';
let result = str1 + str2;
console.log(result); // Output 'Hello World'

If one of the operands is a string, + will perform string concatenation.

Unary Plus Operator

Example:

let str = '42';
let num = +str;
console.log(num); // Output 42

Using + before a single operand can convert the operand to a number, which is the function of the unary plus operator.

Type Conversion

Example:

let num = 42;
let str = '10';
let result = num + str; // Implicit type conversion (type coercion)
console.log(result); // Output '4210'

If one of the operands is a string, + performs type conversion, converting other operands to strings, then performs string concatenation.

Concatenating Arrays

Example:

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let result = arr1 + arr2;
console.log(result); // Output '1,2,34,5,6'

When one operand is an array, + converts the array to a string and then performs string concatenation.

Special Cases

Example:

let specialResult1 = '1' + 2 + 3;
console.log(specialResult1); // Output '123'
let specialResult2 = 2 + 3 + '1';
console.log(specialResult2); // Output '51'

specialResult1, because the string appears on the leftmost side of +, subsequent numbers are treated as strings for concatenation. specialResult2, because the string appears on the rightmost side of +, the previous numbers perform mathematical operations first and then concatenate.


- (Minus Sign)

In JavaScript, the minus sign - is an operator used to perform mathematical subtraction.

Mathematical Subtraction

Example:

let a = 5;
let b = 3;
let result = a - b;
console.log(result); // Output 2

If both are numbers, - is used to perform mathematical subtraction.

Unary Minus Operator

Example:

let num = 42;
let result = -num;
console.log(result); // Output -42

Using - before a single operand can perform unary negation, turning the operand into its opposite number.

Type Conversion

Example:

let num1 = 42;
let str = '10';
let result = num1 - str;
console.log(result); // Output 32

If one of the operands is a string, - performs type conversion, converting other operands to numbers, then performs mathematical subtraction.

Special Cases

Example:

let specialResult = '10' - 2;
console.log(specialResult); // Output 8

In this special case, because the content in the string can be successfully converted to a number, - performs mathematical subtraction.


=, ==, === (Assignment, Loose Equality, Strict Equality)

In JavaScript, the equals sign = is an assignment operator, while == and === are comparison operators. Loose equality converts both operands to the same type before comparison. In conditional judgments, === is typically used for strict equality comparison because it does not perform type conversion.

Assignment Operator

= is used to assign the value on the right to the variable on the left.

Example:

let x = 5;
let y = 'Hello';
console.log(x); // Output 5
console.log(y); // Output 'Hello'

In this example, = assigns the value on the right to the variables x and y on the left.

Comparison Operators

== and === are used to compare the equality of two values.

Example:

let a = 5;
let b = '5';
console.log(a == b); // Output true
console.log(a === b); // Output false

== performs type conversion when comparing equality, null == undefined outputs true. === requires both value and type to be equal when comparing equality, null === undefined outputs false. NaN is not equal to any value, including NaN itself.


++, -- (Increment, Decrement)

In JavaScript, increment (++) and decrement (--) are operators used to increase or decrease the value of a variable.

Increment Operator (++)

After use, the original variable immediately increases by 1. Prefix increment returns the value after increment (new value); Postfix increment returns the value before increment (old value);

Prefix increment example:

let a = 5;
// Prefix increment, first increase by 1, then use the new value
let b = ++a;
console.log(b); // Output 6
console.log(a); // Output 6

In this example, a first increased by 1, then b got the new a value (6).

Postfix increment example:

let x = 5;
// Postfix increment, first use the current value, then increase by 1
let y = x++;
console.log(y); // Output 5
console.log(x); // Output 6

In this example, y first got the current value of x (5), then x increased by 1.

Decrement Operator (—)

After use, the original variable immediately decreases by 1. Prefix decrement returns the value after decrement (new value); Postfix decrement returns the value before decrement (old value);

Prefix decrement example:

let p = 10;
// Prefix decrement, first decrease by 1, then use the new value
let q = --p;
console.log(q); // Output 9
console.log(p); // Output 9

In this example, p first decreased by 1, then q got the new p value (9).

Postfix decrement example:

let m = 8;
// Postfix decrement, first use the current value, then decrease by 1
let n = m--;
console.log(n); // Output 8
console.log(m); // Output 7

In this example, n first got the current value of m (8), then m decreased by 1.

Operator Precedence:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence

Share:

Comments