Javascript - Functions, missing argument

Viewed 105

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));

2 Answers

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.

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));

Related