JavaScript Operators Tutorial
What are the Operators?
- Operators are symbols or keywords used to perform operations on values or variables in JavaScript.
- They are categorized into various types, including arithmetic, assignment, comparison, logical, and more.
- Understanding and using operators is crucial for manipulating data and controlling the flow of your JavaScript code.
Arithmetic Operators
- Used for mathematical operations.
- +: Addition
- -: Subtraction
- *: Multiplication
- /: Division
- %: Remainder
- ++: Increment (increases by 1)
- --: Decrement (decreases by 1)
- **: Exponentiation (power)
let x = 10;
let y = 5;
let addition = x + y;
let subtraction = x - y;
let multiplication = x * y;
let division = x / y;
Assignment Operators
- Assign values to variables.
- =: Assigns a value to a variable (e.g., const x = 5;).
- +=: Adds a value to the existing value of a variable (e.g., a += 5;).
- -=: Subtracts a value from the existing value (e.g., a -= 2;).
- *=: Multiplies the existing value (e.g., a *= 3;).
- /=: Divides the existing value (e.g., a /= 2;).
- %=: Computes the remainder (e.g., a %= 2;).
- **=: Raises to the power (e.g., a **= 2;).
let a = 10;
a += 5; // a is now 15
a -= 3; // a is now 12
a *= 2 // a is now 24
b = 2;
b **= 2; // b is now 4
Comparison Operators
- Compare values and return a boolean (true or false).
let isEqual = x === y; // false
let isGreaterThan = x > y; // true
Logical Operators
- Combine and manipulate boolean values.
let isTrue = true;
let isFalse = false;
let andOperator = isTrue && isFalse; // false
let orOperator = isTrue || isFalse; // true
let notOperator = !(isTrue || isFalse) // false
Unary Operators
- Perform operations on a single operand. Either Increment or Decrement
let num = 5;
num++; // Increment by 1, num is now 6
num--; // Decrement by 1, num is now 5
Bitwise Operators
- Manipulate binary representations of values.
let a = 5; // Binary: 101
let b = 3; // Binary: 011
let bitwiseAnd = a & b; // Result: 001 (1 in decimal)
Ternary Operator
- A concise way to write conditional statements.
- This will understand once we know the conditional statements. So, don't worry if you not figure it out.
let age = 20;
let canVote = (age >= 18) ? console.log('Yes') : 'No';
String Operators
- The + operator is used to concatenate the strings.
let greeting = 'Hello, ';
let name = 'John';
let message = greeting + name; // 'Hello, John'
Type Operators
- Check the type of a value.
typeof 42; // 'number'
let name = "Jack";
console.log(typeof(name)) // 'string'
Spread Operator
- Used to split array or object elements.
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5]; // [1, 2, 3, 4, 5]