Let me preface this by saying I'm a beginner in the world of programming so please excuse my ignorance.
I wrote a simple script for calculating discounts that work, however it displays "undefined" after I execute the code.
let price = prompt("What is the total cost? ");
function total() {
if (price > 250) {
var result = price * discount;
var cost = price - result;
console.log("your total cost will be " + cost);
} else {
console.log("your total cost will be " + price)
}
}
discount = 0.15
console.log(total());
However, when I switch the console.log statements to return statements the undefined message goes away.
let price = prompt("What is the total cost? ");
function total() {
if (price > 250) {
var result = price * discount;
var cost = price - result;
return ("your total cost will be " + cost);
} else {
return ("your total cost will be " + price)
}
}
discount = 0.15
console.log(total());
Why is this? It's confusing me and I don't understand why I'm getting the undefined message.
On the two lines marked "1" you are outputting strings to the console.
In the line marked "2" you are outputting the results of the function total() to the console. But, in your code there is no "result" because you didn't return a value. (Therefore, the value of total() was undefined).
However, when you replaced the lines marked "1" with return(..) in your second code, the total function returned a value (the string). So when you tried to console.log the value of the total() function, it worked.
To look at it another way... if you had a function like this:
function example(){
let value1 = 5+5;
let value2 = 1+1;
}
What would be the value of example()? Nothing -- or undefined. Because how would the function know if you wanted value1, value2 or some combination of the two?
You use the "return" statement to let the function know what is the final value.
function example(){
let value1 = 5+5;
let value2 = 1+1;
return value1*value2;
}
Now the function returns the value (in this case 20).