Understanding Basic Operators in JavaScript - Part 2
Basic operators in JavaScript are fundamental for performing various operations. Let’s explore some essential operators:
Arithmetic Operators
Arithmetic operators allow mathematical calculations:
Addition (+): Adds two numbers.
let sum = 5 + 3; // sum = 8
Subtraction (-): Subtracts the right operand from the left operand.
let difference = 10 - 5; // difference = 5
Multiplication (*): Multiplies two numbers.
let product = 4 * 6; // product = 24
Division (/): Divides the left operand by the right operand.
let quotient = 10 / 2; // quotient = 5
Remainder (%): Returns the remainder of the division.
let remainder = 10 % 3; // remainder = 1
Exponentiation ():** Raises the left operand to the power of the right operand.
let result = 2 ** 3; // result = 8 (2^3)
String Concatenation
String concatenation merges two strings using the plus operator (+):
let str = "Hello, " + "world!"; // str = "Hello, world!"
You can also concatenate strings with other data types:
let message = "The answer is: " + 42; // message = "The answer is: 42"
Assignment Operators
Assignment operators modify the value of the variable:
+= (Add and Assign): Adds the right operand to the left operand and assigns the result to the left operand.
let num = 5; num += 3; // num = num + 3; num = 8
*= (Multiply and Assign): Multiplies the left operand by the right operand and assigns the result to the left operand.
let num2 = 10; num2 *= 2; // num2 = num2 * 2; num2 = 20
Increment and Decrement Operators
Increment (++) increases a variable by 1, and decrement (–) decreases a variable by 1:
let counter = 2;
counter++; // counter = 3 (increment by 1)
let counter2 = 2;
counter2--; // counter2 = 1 (decrement by 1)
You can also use these operators in prefix or postfix forms, affecting the value differently.
Comparison Operators
Comparison operators are used to comparing two values and return a Boolean result:
> and <: Checks if the left operand is greater than or less than the right operand.
console.log(5 > 3); // true console.log(5 < 3); // false
>= and <=: Checks if the left operand is greater than or equal to, or less than or equal to the right operand.
== and !=: Checks for equality and inequality, often used for non-strict comparisons.
console.log(5 == '5'); // true console.log(5 != '5'); // false
=== and !==: Strict equality and inequality, checks both value and data type.
console.log(5 === '5'); // false console.log(5 !== '5'); // true
Logical Operators
Logical operators are used to combining or negating conditions:
|| (OR): Returns true if at least one condition is true.
console.log(true || false); // true
&& (AND): Returns true only if both conditions are true.
console.log(true && false); // false
! (NOT): Negates a given condition.
console.log(!true); // false
By mastering these operators, you can perform a wide range of operations and create more complex and functional JavaScript code.