Lesson 4 - Basic Arithmetic Operations
You lean a programming language to create computer programs. There is a high chance that you will neeed to do some calculations in your program such as finding the total of items a client is buying, or calculate you expenses, or even see how long you take to finish a routine, etc.
These kind of operations are known as Arithimetic Operation. This bit of code teaches you how to do such operations if you use JavaScript as your programming language to code your program.
// Declaring variables
let a = 10;
let b = 5;
// Arithmetic operations
console.log("Addition:", a + b);
console.log("Subtraction:", a - b);
console.log("Multiplication:", a * b);
console.log("Division:", a / b);
console.log("Modulus (remainder):", a % b);
Explanation:
JavaScript supports arithmetic operations: addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).
Notice that " * " is used for multiplication instead of "x", and " / " is used for divition
Try your hand:
1. Create a File:
Create a new file named lesson4-arithmetic.html
.
2. Write the Code:
Copy and paste the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lesson 4 - Arithmetic Operations</title>
</head>
<body>
<script>
let a = 10;
let b = 5;
// Arithmetic operations
console.log("Addition:", a + b);
console.log("Subtraction:", a - b);
console.log("Multiplication:", a * b);
console.log("Division:", a / b);
console.log("Modulus (remainder):", a % b);
</script>
</body>
</html>
Save the file in your folder.
3. Preview the File:
- Open the file in your browser (e.g., Chrome or Firefox). You can double-click on it or right-click -> open with... -> choose your browser
- Press
Ctrl + Shift + J
(Windows) orCmd + Option + J
(Mac) to open the browser's developer console. - Observe the output:
string number boolean object undefined
4. Experiment:
- Change the values of the values of
a
andb
and save the file. - Refresh the browser and note the changes in the console
That was fantastic!