Now that we've explored variables, data types, and basic operations, let's see how they come together in some simple, real-world (or at least, algorithm-world!) scenarios. These examples will help solidify your understanding and show you how these fundamental building blocks create the logic of programs.
Imagine you're calculating the area of a rectangle. You need to store the length and width, and then perform a multiplication. This is a perfect candidate for our basic building blocks.
let rectangleLength = 10;
let rectangleWidth = 5;
let rectangleArea = rectangleLength * rectangleWidth;
console.log(rectangleArea);In this example:
rectangleLengthandrectangleWidthare variables of typenumberstoring our dimensions.rectangleAreais anothernumbervariable that holds the result of multiplying the length and width.console.log()is used to display the final calculated area.
Let's visualize this process with a simple flowchart. This diagram shows the steps involved in our rectangle area calculation.
graph TD;
A[Start]
B{Declare rectangleLength}
C{Declare rectangleWidth}
D{Calculate rectangleArea = rectangleLength * rectangleWidth}
E{Display rectangleArea}
F[End]
A --> B
B --> C
C --> D
D --> E
E --> F
Consider another common task: calculating the total cost of items. If you buy multiple items of the same price, you multiply the quantity by the price per item.
let itemQuantity = 3;
let pricePerItem = 2.50;
let totalCost = itemQuantity * pricePerItem;
console.log(totalCost);Here:
itemQuantityis anumberrepresenting how many items we have.pricePerItemis anumber(specifically, a floating-point number) representing the cost of one item.totalCostis anumberthat stores the result of the multiplication.