2

Baby coder here, just getting into functions. I've created a function to calculate the area of a rectangle, and it works as long as two arguments are provided. I want my code to assume the shape is a square (so length and width are equal), if only one argument is provided. I've been trying to come up with a conditional, but don't know how to say "if there is only one argument, then length === width". Any pointers appreciated!

function area(length, width) {
    let rectangleArea = Number(length) * Number(width);
    return rectangleArea;
}
console.log(area(10, 5));

0

2 Answers 2

6

One option is to use a default function parameters for the width parameter and set it to length if it is not passed

function area(length, width = length) {
  let rectangleArea = length * width;
  return rectangleArea;
}

console.log(area(10, 5));
console.log(area(10));

Default function parameters is a recent feature. If it is confusing, you could check if width parameter is undefined and set it to length

function area(length, width) {
  if (typeof width === "undefined")
    width = length;

  let rectangleArea = length * width;
  return rectangleArea;
}

console.log(area(10, 5));
console.log(area(10))

Also, the Number() wrapper is not required here. You are already passing numbers. Even if you pass strings as parameters like area("10", "5"), they are coerced to numbers and multiplied.

Sign up to request clarification or add additional context in comments.

2 Comments

I ended up using the second one, just to avoid confusing myself, but I think I understand why the first works, too. Thank you!
@tarabyte you're welcome. If the answer resolved your issue, please mark it as accepted by clicking on the grey checkmark on the left
2

You may use default parameter width = length. If the value of width is not passed to the function, the value of length will be assigned to the width.

function area(length, width = length) {
    let rectangleArea = Number(length) * Number(width);
    return rectangleArea;
}

console.log(area(10, 5));
console.log(area(10));
console.log(area(5));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.