By the end of this lesson, you will be able to work effectively with numbers, use basic math operations, and apply number formatting in JavaScript.
In JavaScript, numbers can represent whole numbers (integers) or decimals (floating point numbers). For example, when you go shopping and see a price tag of $20.99, that is a floating point number. You will learn how to manipulate these numbers using JavaScript.
You can perform various math operations in JavaScript. The basic operations are addition, subtraction, multiplication, and division. Here’s a simple example:
File: math_operations.js
const num1 = 10;
const num2 = 5;
const sum = num1 + num2;
const difference = num1 - num2;
const product = num1 * num2;
const quotient = num1 / num2;
console.log('Sum:', sum);
console.log('Difference:', difference);
console.log('Product:', product);
console.log('Quotient:', quotient);
Sum: 15
Difference: 5
Product: 50
Quotient: 2
In the above code:
num1 and num2.+ operator to add them together.console.log() to display the results in the console.Now it’s your turn! Create a program that calculates the area of a rectangle. Use the length and width defined as variables.
const length = 5;
const width = 10;
const area = length * width;
console.log('Area of the rectangle is:', area);
console.log(): If you do not log your results, you will not see the output.console.log().