Operators and Expressions
Performing Actions on Data
Operators are special symbols used to perform operations on operands (values and variables).
1. Arithmetic Operators
Used for mathematical calculations.
+(Addition)-(Subtraction)*(Multiplication)/(Division)%(Modulus/Remainder): e.g.,10 % 3is1**(Exponentiation): e.g.,2 ** 3is8
2. Assignment Operators
Used to assign values to variables.
=(Assign)+=(Add and assign):x += 5is shorthand forx = x + 5-=,*=,/=work similarly.
3. Comparison Operators
Used to compare two values, returning a Boolean (true or false).
==(Equal to - checks value only)===(Strict Equal to - checks value AND data type. Always use this!)!=(Not equal)!==(Strict not equal)>,<,>=,<=(Greater than, Less than, etc.)
4. Logical Operators
Used to combine multiple conditions.
&&(Logical AND): Returns true if BOTH sides are true.||(Logical OR): Returns true if AT LEAST ONE side is true.!(Logical NOT): Reverses the boolean value (true becomes false).
Mastering operators allows you to write complex logic, which we will use heavily in the next chapter on Conditional Statements!
💡 Himanshu's Tip:
Never, ever use == in your code. Always use ===. The double equals sign tries to be 'smart' and convert types behind your back, which leads to horrible, hard-to-find bugs. Strict equality (===) is the professional standard.
Interview Questions
- What is the difference between
==and===? - What does the modulo operator (
%) do? - How does the Logical AND (
&&) operator work?