Basic Operators and Expressions
Operators are symbols that perform operations on variables and values. In this lesson, we’ll cover the basic operators and expressions used in JavaScript.
1. Arithmetic Operators:
+
), subtraction (-
), multiplication (*
), division (/
), and modulus (%
).Example Code:
let x = 10;
let y = 5;
console.log('Addition:', x + y); // Output: 15
console.log('Subtraction:', x - y); // Output: 5
console.log('Multiplication:', x * y); // Output: 50
console.log('Division:', x / y); // Output: 2
console.log('Modulus:', x % y); // Output: 0
2. Assignment Operators:
=
, +=
, -=
, *=
, /=
, %=
.Example Code:
let a = 10;
a += 5; // a = a + 5
console.log('a after += 5:', a); // Output: 15
a -= 3; // a = a - 3
console.log('a after -= 3:', a); // Output: 12
a *= 2; // a = a * 2
console.log('a after *= 2:', a); // Output: 24
a /= 4; // a = a / 4
console.log('a after /= 4:', a); // Output: 6
a %= 2; // a = a % 2
console.log('a after %= 2:', a); // Output: 0
3. Comparison Operators:
==
, ===
, !=
, !==
, >
, <
, >=
, <=
.Example Code:
let b = 10;
let c = '10';
console.log('b == c:', b == c); // Output: true (loose equality)
console.log('b === c:', b === c); // Output: false (strict equality)
console.log('b != c:', b != c); // Output: false
console.log('b !== c:', b !== c); // Output: true
console.log('b > 5:', b > 5); // Output: true
console.log('b < 5:', b < 5); // Output: false
console.log('b >= 10:', b >= 10); // Output: true
console.log('b <= 10:', b <= 10); // Output: true
4. Logical Operators:
&&
(AND), ||
(OR), !
(NOT).Example Code:
let d = true;
let e = false;
console.log('d && e:', d && e); // Output: false
console.log('d || e:', d || e); // Output: true
console.log('!d:', !d); // Output: false
console.log('!e:', !e); // Output: true
5. String Operators:
+
operator.Example Code:
let firstName = 'John';
let lastName = 'Doe';
let fullName = firstName + ' ' + lastName;
console.log('Full Name:', fullName); // Output: John Doe
Conclusion: Understanding and using basic operators and expressions in JavaScript is essential for performing calculations, assigning values, comparing data, and controlling logic flow. Practice these concepts to build a strong foundation in JavaScript programming.