...

Exercise: Square Area and Perimeter

You're designing a tool for architects to calculate both the area and the perimeter of a square.

In this exercise, you will write a program that:

  • Asks the user for the length of a side of the square using the prompt function.
  • Calculates the area of the square using the formula: area = side * side.
  • Calculates the perimeter of the square using the formula: perimeter = 4 * side.
  • Prints both the area and the perimeter to the console in the format: "The area of the square is: AREA" and "The perimeter of the square is: PERIMETER".

Multiplication in JavaScript

To multiply two numbers in JavaScript, you use the * operator. For example:

let num1 = 5;
let num2 = 10;
let product = num1 * num2;
console.log(product); // Outputs: 50

Converting Strings to Numbers

Remember how we had to convert strings to numbers before performing addition? In JavaScript, "5" + 2 evaluates to "52". Number("5") + 2 correctly evaluates to 7. This happens because the + operator can perform both addition and concatenation, and JavaScript assumes you're trying to do concatenation if one of the operands is a string.

This problem does not happen when performing multiplication, division and subtraction. Since the *, /, and- operators have only one job, JavaScript automatically converts strings to numbers when possible. This means "5" * 2 evaluates to 10 just fine, unlike addition. This is because the + operator is used for both concatenation and addition.

However, it is still a good idea to convert strings to numbers whenever it needs to be a number so your code stays clean, and future readers of your code (which includes future you) have a clearer idea of your intent.

Now go write some code!

Loading...

Output (Console)