A Comprehensive Guide to ECMAScript Operators
In ECMAScript, an operation refers to the process of performing actions on values to produce new values. Operators are symbols or keywords used to execute various operations. ECMAScript supports a wide range of operations and operators, including arithmetic operations, comparison operations, logical operations, bitwise operations, and the ternary operator, among others.
Below is an introduction to some common operations and operators:
- Arithmetic Operators: Used to perform basic arithmetic operations, including addition, subtraction, multiplication, division, and modulo.
var x = 5;
var y = 3;
console.log(x + y); // 8
console.log(x - y); // 2
console.log(x * y); // 15
console.log(x / y); // 1.6666666666666667
console.log(x % y); // 2
- Comparison Operators: Used to compare the magnitude or equality of two values, returning a boolean value. These include less than, greater than, less than or equal to, greater than or equal to, equal to, and not equal to.
var x = 5;
var y = 3;
console.log(x < y); // false
console.log(x > y); // true
console.log(x <= y); // false
console.log(x >= y); // true
console.log(x == y); // false
console.log(x != y); // true
- Logical Operators: Used to combine and operate on boolean values, including logical AND, logical OR, and logical NOT.
var x = true;
var y = false;
console.log(x && y); // false
console.log(x || y); // true
console.log(!x); // false
- Bitwise Operators: Used to perform operations on binary numbers, including bitwise AND, bitwise OR, and bitwise XOR.
var x = 5; // Binary representation: 00000101
var y = 3; // Binary representation: 00000011
console.log(x & y); // 00000001 (bitwise AND)
console.log(x | y); // 00000111 (bitwise OR)
console.log(x ^ y); // 00000110 (bitwise XOR)
console.log(~x); // 11111010 (bitwise NOT)
console.log(x << 1); // 00001010 (left shift by one)
console.log(x >> 1); // 00000010 (right shift by one)
- Ternary Operator: Used to select different values based on a condition.
var x = 5;
var y = 3;
console.log(x > y ? "x is greater than y" : "x is not greater than y"); // "x is greater than y"
There are other operations and operators as well, including assignment operators, increment/decrement operators, the in operator, and the instanceof operator. Understanding and mastering these operations and operators is crucial for writing efficient and flexible JavaScript code.