Operators in JavaScript are symbols or keywords that perform operations on values or variables. They are essential for calculations, comparisons, logical decisions, and more. Think of operators as tools to manipulate data.
1️⃣ Types of JavaScript Operators
Arithmetic Operators
Used for mathematical calculations.
let a = 10; let b = 3; console.log(a + b); // 13 console.log(a % b); // 1
Assignment Operators
Used to assign values to variables. Can also combine operations with assignment.
let x = 5; x += 3; // x = 8 console.log(x);
Comparison Operators
Used to compare values. Returns true or false.
console.log(10 > 5); // true console.log(10 === 10); // true console.log(10 === '10'); // false
Logical Operators
Used to combine or invert conditions.
let a = 5, b = 10; console.log(a < b && b > 5); // true console.log(a > b || b > 5); // true console.log(!(a < b)); // false
String Operators
JavaScript allows concatenating strings using +.
let firstName = "Alice"; let lastName = "Smith"; let fullName = firstName + " " + lastName; console.log(fullName); // Alice Smith
Ternary Operator (Conditional)
Shortcut for if-else statements.
let age = 18; let status = (age >= 18) ? "Adult" : "Minor"; console.log(status); // Adult
condition ? value_if_true : value_if_falseExplanation:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Operators Example</title>
<style>
body { font-family: Arial; padding: 20px; }
button { padding: 10px 20px; margin: 5px; cursor: pointer; }
p { font-size: 18px; color: darkblue; }
</style>
</head>
<body>
<h1>JavaScript Operators Demo</h1>
<p id="demo">Click the button to see results</p>
<button onclick="showOperators()">Show Operators</button>
<script>
function showOperators() {
let a = 10, b = 3;
let name = "Alice";
let greeting = "Hello";
// Arithmetic
let sum = a + b;
let remainder = a % b;
// Comparison
let isEqual = (a == b);
let isGreater = (a > b);
// Logical
let result = (a > b && b < 5);
// String concatenation
let fullGreeting = greeting + ", " + name + "!";
// Ternary
let status = (a > 5) ? "High" : "Low";
document.getElementById("demo").innerHTML =
"Sum: " + sum + "<br>" +
"Remainder: " + remainder + "<br>" +
"Is Equal: " + isEqual + "<br>" +
"Is Greater: " + isGreater + "<br>" +
"Logical Result: " + result + "<br>" +
fullGreeting + "<br>" +
"Ternary Status: " + status;
}
</script>
</body>
</html>