Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Basics (Retired) Creating Reusable Code with Functions Giving Information to Functions

Konrad Dziekonski
Konrad Dziekonski
7,798 Points

little modification

Hello,

I have tried to modify Daves code a little by defining third parameter in the getArea function:

function getArea(width, length, unit) { var area = width*length; var unit = 'm2'; return area + "" + unit; }

console.log(getArea(10, 20, unit));

but the console is returning: Uncaught reference error: unit is not defined at random.js:7

could you please explain why is it not working? I thought that if I would store a value of string 'm2' in a variable called unit I could use it than in a way like the function knows that it has to multiply width by length. But hmm why is it stored in variable "area" but the keyword "area" has not been used, what for was it stored in this variable?

I have also tried to delete the third parameter from the function:

function getArea(width, length) { var area = width*length; var unit = 'm2'; return area + "" + unit; }

console.log(getArea(10, 20, 'm2'));

but left it in the console log and it appeared in the console log screen, so why was it necessary to declare the third parameter - unit?

if that make sense at all... i mean my qustion ;] thanks

If you're passing unit as one of the parameters, you don't need to set it as a variable separately.

function getArea(width, length, unit) { 
  var area = width * length; 
  return area + " " + unit; // Added a space between the quotes to separate area and units, if you're not including a space there is no reason to concatenate the string.
}

console.log( getArea( 10, 20, 'm2' ) );

This snippet will output "200 m2" to the console.

function getArea(width, length) { 
  var area = width * length; 
  var unit = 'm2';
  return area + " " + unit;
}

console.log( getArea( 10, 20 ) );

This will also output '200 m2'

The reason you're getting this error is due to defining the variable inside the function. The code that effectively is running is similar to:

  console.log(favFood);
  var favFood = "ice cream";

So at the time that it is calling the variable, it isn't defined.