03
Operators
Chapter 3 • Beginner
25 min
Operators
Operators allow you to manipulate values and perform calculations in JavaScript.
Basic Operators
Arithmetic Operators
Perform mathematical operations:
javascript.js
let a = 10;
let b = 3;
console.log(a + b); // Addition: 13
console.log(a - b); // Subtraction: 7
console.log(a * b); // Multiplication: 30
console.log(a / b); // Division: 3.333...
console.log(a % b); // Modulus: 1
console.log(a ** b); // Exponentiation: 1000
Assignment Operators
Assign values to variables:
javascript.js
let x = 10;
x += 5; // x = x + 5 (15)
x -= 3; // x = x - 3 (12)
x *= 2; // x = x * 2 (24)
x /= 4; // x = x / 4 (6)
Increment and Decrement
javascript.js
let i = 1;
let j = ++i; // Pre-increment: j equals 2, i equals 2
let k = i++; // Post-increment: k equals 2, i equals 3
String Operations
Concatenation
Joining strings together:
javascript.js
let firstName = 'John';
let lastName = 'Doe';
let fullName = firstName + ' ' + lastName; // 'John Doe'
Template Literals (ES6)
A more modern way to concatenate strings:
javascript.js
let firstName = 'John';
let lastName = 'Doe';
let fullName = `${firstName} ${lastName}`; // 'John Doe'
Type Coercion
JavaScript will automatically convert types when needed, which can sometimes lead to unexpected results:
javascript.js
let num = 5;
let str = '10';
console.log(num + str); // '510' (string concatenation)
console.log(num + Number(str)); // 15 (numeric addition)
Hands-on Examples
Arithmetic Operators
let a = 15;
let b = 4;
console.log('Addition:', a + b);
console.log('Subtraction:', a - b);
console.log('Multiplication:', a * b);
console.log('Division:', a / b);
console.log('Modulus:', a % b);
console.log('Exponentiation:', a ** b);Arithmetic operators perform basic mathematical operations. The modulus operator (%) returns the remainder after division.