6 -D.R.Y error


#1

Hi,
After doing this exercise for a while and getting an undefined error when using this code

var orangeCost = function(price){
var val = price * 5;
console.log( "orangeCost" + price);

};

orangeCost(5);

I read the forums and did as someone suggested and changed it to the code below that worked.

var orangeCost = function(price){

console.log(price * 5);
};

orangeCost(5);

Can anyone explain why declaring a var val = in the first set of code threw an error as I'd like to understand when it should and shouldn't be used.
Thanks


#2

Well take a look at your code,

Technically it would work if you incorporated the variable "val" into the console.log statement, but let me show you what the console sees and maybe that will help you understand better.

orangeCost( 5 );

//Console goes back up to the function

var orangeCost = function( 5 ) { //Replaces the parameter "price" with the number 5.

var val = 5 * 5 ;

console.log ("orangeCost" + 5); //Console outputs "orangeCost5"
//the console is expecting the number 25, but got "orangeCost5"

The second function looks like this:

orangeCost( 5 );

var orangeCost = function(5){ //Replaces "price" with the number 5.

console.log(5 * 5); //Logs the number 25 to the console.
//the console is expecting the number 25, got "25", Lesson Passes.
};

I hope that explains the situation, and any issues you've been having.