Welcome to Day 3 of our JavaScript bootcamp! Today, we will dive deep into operators and expressions, essential building blocks in JavaScript that allow you to perform computations and make decisions in your code. This comprehensive guide will cover theory, syntax, detailed examples, exercises, and projects to solidify your understanding. Let’s get started!
Theory: Operators and Expressions
What are Operators?
Operators in JavaScript are symbols that perform operations on operands. Operands are the values or variables on which operators act.
Types of Operators
- Arithmetic Operators
- Assignment Operators
- Comparison Operators
- Logical Operators
Arithmetic Operators
Arithmetic operators perform basic mathematical operations such as addition, subtraction, multiplication, and division.
- Addition (+): Adds two numbers.
- Subtraction (-): Subtracts the second number from the first.
- Multiplication (*): Multiplies two numbers.
- Division (/): Divides the first number by the second.
- Modulus (%): Returns the remainder of a division operation.
- Increment (++): Increases a number by one.
- Decrement (–): Decreases a number by one.
Syntax and Examples
Let’s see these operators in action with examples.
let a = 10; // Declaring a variable 'a' with the value 10
let b = 5; // Declaring a variable 'b' with the value 5
let sum = a + b; // Addition: sum is 15
let difference = a - b; // Subtraction: difference is 5
let product = a * b; // Multiplication: product is 50
let quotient = a / b; // Division: quotient is 2
let remainder = a % b; // Modulus: remainder is 0
a++; // Increment: a is now 11
b--; // Decrement: b is now 4
Assignment Operators
Assignment operators assign values to variables. The most common is the equal sign =
.
- Equal (=): Assigns the value of the right operand to the left operand.
- Plus Equal (+=): Adds the right operand to the left operand and assigns the result to the left operand.
- Minus Equal (-=): Subtracts the right operand from the left operand and assigns the result to the left operand.
- Multiply Equal (*=): Multiplies the left operand by the right operand and assigns the result to the left operand.
- Divide Equal (/=): Divides the left operand by the right operand and assigns the result to the left operand.
Syntax and Examples
let x = 10; // Assigning 10 to variable 'x'
x += 5; // Adding 5 to x: x is now 15
x -= 3; // Subtracting 3 from x: x is now 12
x *= 2; // Multiplying x by 2: x is now 24
x /= 4; // Dividing x by 4: x is now 6
Comparison Operators
Comparison operators compare two values and return a boolean (true or false).
- Equal to (==): Returns true if the operands are equal.
- Not equal to (!=): Returns true if the operands are not equal.
- Strict equal to (===): Returns true if the operands are equal and of the same type.
- Strict not equal to (!==): Returns true if the operands are not equal and/or not of the same type.
- Greater than (>): Returns true if the left operand is greater than the right operand.
- Less than (<): Returns true if the left operand is less than the right operand.
- Greater than or equal to (>=): Returns true if the left operand is greater than or equal to the right operand.
- Less than or equal to (<=): Returns true if the left operand is less than or equal to the right operand.
Syntax and Examples
let m = 7; // Declaring a variable 'm' with the value 7
let n = 5; // Declaring a variable 'n' with the value 5
console.log(m == n); // Equal to: false
console.log(m != n); // Not equal to: true
console.log(m === 7); // Strict equal to: true
console.log(m !== '7'); // Strict not equal to: true
console.log(m > n); // Greater than: true
console.log(m < n); // Less than: false
console.log(m >= 7); // Greater than or equal to: true
console.log(m <= 5); // Less than or equal to: false
Logical Operators
Logical operators are used to combine multiple boolean expressions.
- AND (&&): Returns true if both operands are true.
- OR (||): Returns true if at least one operand is true.
- NOT (!): Returns true if the operand is false, and vice versa.
Syntax and Examples
let p = true; // Declaring a variable 'p' with the value true
let q = false; // Declaring a variable 'q' with the value false
console.log(p && q); // AND: false (both need to be true)
console.log(p || q); // OR: true (at least one is true)
console.log(!p); // NOT: false (p is true, so !p is false)
console.log(!q); // NOT: true (q is false, so !q is true)
Exercises
Write a program to add two numbers and display the result.
let num1 = 8; // Initialize 'num1' with value 8
let num2 = 12; // Initialize 'num2' with value 12
let sum = num1 + num2; // Add 'num1' and 'num2', store in 'sum'
console.log(sum); // Output: 20
Check if a number is even or odd.
let num = 7; // Initialize 'num' with value 7
let isEven = (num % 2) === 0; // Check if 'num' is even
console.log(isEven); // Output: false (7 is odd)
Compare two numbers and display if they are equal.
let num1 = 15; // Initialize 'num1' with value 15
let num2 = 15; // Initialize 'num2' with value 15
let isEqual = num1 === num2; // Check if 'num1' and 'num2' are equal
console.log(isEqual); // Output: true (both are equal)
Determine if a number is greater than another number.
let num1 = 10; // Initialize 'num1' with value 10
let num2 = 5; // Initialize 'num2' with value 5
let isGreaterThan = num1 > num2; // Check if 'num1' is greater than 'num2'
console.log(isGreaterThan); // Output: true (10 is greater than 5)
Use logical operators to combine conditions.
let num1 = 10; // Initialize 'num1' with value 10
let num2 = 20; // Initialize 'num2' with value 20
let num3 = 30; // Initialize 'num3' with value 30
let combinedCondition = (num1 < num2) && (num2 < num3); // Check combined condition
console.log(combinedCondition); // Output: true (both conditions are true)
Increment and decrement a variable.
let count = 0; // Initialize 'count' with value 0
count++; // Increment 'count' by 1
console.log(count); // Output: 1
count--; // Decrement 'count' by 1
console.log(count); // Output: 0
Use compound assignment operators.
let num = 10; // Initialize 'num' with value 10
num += 5; // Add 5 to 'num'
console.log(num); // Output: 15
num -= 3; // Subtract 3 from 'num'
console.log(num); // Output: 12
Write a program to multiply two numbers and display the result.
let num1 = 6; // Initialize 'num1' with value 6
let num2 = 7; // Initialize 'num2' with value 7
let product = num1 * num2; // Multiply 'num1' and 'num2', store in 'product'
console.log(product); // Output: 42
Check if two values are not equal.
let value1 = 'hello'; // Initialize 'value1' with string 'hello'
let value2 = 'world'; // Initialize 'value2' with string 'world'
let areNotEqual = value1 !== value2; // Check if 'value1' and 'value2' are not equal
console.log(areNotEqual); // Output: true
Use the logical OR operator to check conditions.
let isRaining = false; // Initialize 'isRaining' with value false
let isSnowing = true; // Initialize 'isSnowing' with value true
let badWeather = isRaining || isSnowing; // Check if either condition is true
console.log(badWeather); // Output: true
Projects
Project 1: Simple Calculator
Create a simple calculator that performs basic arithmetic operations.
Code:
let num1 = 10; // Initialize 'num1' with value 10
let num2 = 5; // Initialize 'num2' with value 5
let sum = num1 + num2; // Add 'num1' and 'num2'
let difference = num1 - num2; // Subtract 'num2' from 'num1'
let product = num1 * num2; // Multiply 'num1' and 'num2'
let quotient = num1 / num2; // Divide 'num1' by 'num2'
console.log(`Sum: ${sum}`); // Output: Sum: 15
console.log(`Difference: ${difference}`); // Output: Difference: 5
console.log(`Product: ${product}`); // Output: Product: 50
console.log(`Quotient: ${quotient}`); // Output: Quotient: 2
Explanation:
- Initialize two numbers
num1
andnum2
. - Perform addition, subtraction, multiplication, and division operations.
- Print the results.
Project 2: Temperature Converter
Convert a temperature value from Celsius to Fahrenheit and vice versa.
Code:
let celsius = 25; // Initialize 'celsius' with value 25
let fahrenheit = (celsius * 9/5) + 32; // Convert Celsius to Fahrenheit
console.log(`${celsius}°C is ${fahrenheit}°F`); // Output: 25°C is 77°F
fahrenheit = 77; // Reinitialize 'fahrenheit' with value 77
celsius = (fahrenheit - 32) * 5/9; // Convert Fahrenheit to Celsius
console.log(`${fahrenheit}°F is ${celsius}°C`); // Output: 77°F is 25°C
Explanation:
- Convert temperature from Celsius to Fahrenheit using the formula
(C * 9/5) + 32
. - Convert temperature from Fahrenheit to Celsius using the formula
(F - 32) * 5/9
. - Print the converted values.
Additional Projects
Project 1: Age Calculator
Create a program to calculate the age of a person based on the birth year.
Code:
let currentYear = 2024; // Initialize 'currentYear' with value 2024
let birthYear = 1990; // Initialize 'birthYear' with value 1990
let age = currentYear - birthYear; // Calculate age
console.log(`You are ${age} years old.`); // Output: You are 34 years old.
Explanation:
- Initialize the current year and birth year.
- Calculate the age by subtracting the birth year from the current year.
- Print the calculated age.
Project 2: Simple Interest Calculator
Create a program to calculate simple interest based on principal, rate, and time.
Code:
let principal = 1000; // Initialize 'principal' with value 1000
let rate = 5; // Initialize 'rate' with value 5%
let time = 2; // Initialize 'time' with value 2 years
let simpleInterest = (principal * rate * time) / 100; // Calculate simple interest
console.log(`The simple interest is $${simpleInterest}.`); // Output: The simple interest is $100.
Explanation:
- Initialize principal amount, rate of interest, and time period.
- Calculate simple interest using the formula
(P * R * T) / 100
. - Print the calculated simple interest.
Final Projects
Project 1: Shopping Cart Calculator
Create a program that calculates the total cost of items in a shopping cart.
Code:
let item1 = 15; // Initialize 'item1' with value 15
let item2 = 20; // Initialize 'item2' with value 20
let item3 = 10; // Initialize 'item3' with value 10
let totalCost = item1 + item2 + item3; // Calculate total cost
console.log(`The total cost of the items is $${totalCost}.`); // Output: The total cost of the items is $45.
Explanation:
- Initialize the cost of each item.
- Calculate the total cost by adding the cost of all items.
- Print the total cost.
Project 2: Grade Calculator
Create a program to calculate the grade of a student based on marks obtained.
Code:
let marks = 85; // Initialize 'marks' with value 85
let grade;
if (marks >= 90) {
grade = 'A';
} else if (marks >= 80) {
grade = 'B';
} else if (marks >= 70) {
grade = 'C';
} else if (marks >= 60) {
grade = 'D';
} else {
grade = 'F';
}
console.log(`Your grade is ${grade}.`); // Output: Your grade is B.
Explanation:
- Initialize marks obtained by the student.
- Use if-else statements to determine the grade based on marks.
- Print the grade.
Understanding operators and expressions is fundamental to mastering JavaScript. By practicing the exercises and working on the projects provided, you will gain a solid grasp of these concepts. Keep experimenting with different combinations of operators and writing your own programs to reinforce your learning.
Welcome to DevTechTutor.com, your ultimate resource for mastering web development and technology! Whether you're a beginner eager to dive into coding or an experienced developer looking to sharpen your skills, DevTechTutor.com is here to guide you every step of the way. Our mission is to make learning web development accessible, engaging, and effective.