JavaScript Operators
JavaScript operators are used to perform operations on variables and values. They allow you to perform calculations, assign values, and compare data.
Common JavaScript Operators
- Arithmetic: +, -, *, /
- Assignment: =, +=, -=
- Comparison: ==, ===, !=, >, <
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations such as addition, subtraction, multiplication, and division.
Addition Operator (+)
The addition operator is used to add two values.
Subtraction Operator (-)
The subtraction operator is used to subtract one value from another.
let x = 10;
let y = 5;
document.getElementById('sub').innerHTML = x - y;
Multiplication Operator (*)
The multiplication operator is used to multiply values.
let x = 10;
let y = 5;
document.getElementById('mul').innerHTML = x * y;
Division Operator (/)
The division operator is used to divide one value by another.
let x = 10;
let y = 5;
document.getElementById('div').innerHTML = x / y;
Assignment Operators
Assignment operators are used to assign values to variables. They can also be used to perform operations and assign the result.
Assignment Operator (=)
The assignment operator is used to assign a value to a variable.
Addition Assignment Operator (+=)
This operator adds a value to a variable and assigns the result.
Subtraction Assignment Operator (-=)
This operator subtracts a value from a variable and assigns the result.
let x = 10;
x -= 5;
document.getElementById('subAssign').innerHTML = x;
Comparison Operators
Comparison operators are used to compare two values. They return either true or false.
Equal to (==)
This operator checks if two values are equal.
Strict Equal (===)
This operator checks both value and data type.
Not Equal (!=)
This operator checks if two values are not equal.
Greater Than (>)
Checks if one value is greater than another.
Less Than (<)
Checks if one value is less than another.
Why Operators are Important
- They allow calculations in programs
- They help in decision making
- They are used in almost every JavaScript program
Best Practices
- Use meaningful variable names
- Always understand what each operator does
- Avoid unnecessary complex expressions