2

While learning JavaScript and trying to solve a challenge question, my code keeps outputting 'undefined value'.

My code:

function paidAmount(bill){
var tipPercent
if (bill < 50){
    tipPercent = 0.20;
}
else if (bill >= 50 && bill <=200){
    tipPercent = 0.15;
}
else{
    tipPercent = 0.10;
}
return bill * tipPercent;
}

var tip1 = console.log(paidAmount(124));
var tip2 = console.log(paidAmount(48));
var tip3 = console.log(paidAmount(268));

var tipTotal = [tip1, tip2, tip3];

console.log(tipTotal);

Output:

18.599999999999998
9.600000000000001
26.8
(3) [undefined, undefined, undefined]
1
  • 2
    The console.log() function always returns undefined
    – Pointy
    Commented Feb 5, 2019 at 3:12

3 Answers 3

3

You cannot assign values which are inside console.log. Make them separate

function paidAmount(bill){
var tipPercent
if (bill < 50){
    tipPercent = 0.20;
}
else if (bill >= 50 && bill <=200){
    tipPercent = 0.15;
}
else{
    tipPercent = 0.10;
}
return bill * tipPercent;
}


var tip1 = paidAmount(124);
var tip2 = paidAmount(48);
var tip3 = paidAmount(268);
console.log(paidAmount(124));
console.log(paidAmount(268));
console.log(paidAmount(48));
var tipTotal = [tip1, tip2, tip3];

console.log(tipTotal);

2
  • If it helped you upvote and mark it correct so it can help others too
    – ellipsis
    Commented Feb 5, 2019 at 4:53
  • Why repeat the calculation? you should've done console.log(tip1). DRY.
    – Jamiec
    Commented Feb 5, 2019 at 8:38
0

[console.log(tip1),console.log(tip2),...] is wrong, but you can try another way :

function paidAmount(bill) {
  var tipTotal = [] ;
  var tipPercent ;

  for (value of bill) {
    tipPercent = (value < 50 ) ? 0.20 : ( ( value >= 50 && value <= 200) ? 0.15 : 0.10 ) ;
    tipTotal.push( value * tipPercent ) ;
  }

  return tipTotal ;
}

console.log( paidAmount([124, 48, 268]) );

0
0

console.log returns undefined. See the specs linked below for more information.

Namespace Console spec link

Namspace Console spec image

Logger spec

Also, in your example, you don't have to store the results into the variables tip1, tip2, tip3.

Instead you could directly call the paidAmount inside of console.log:

console.log(paidAmount(124), paidAmount(48), paidAmount(268));

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.