0

I have a question about plugging the results of the for statement into the If statement. it says bill is not defined, but it is defined in the for statement. i know this has something to do with scope. but i am still new to coding javascript so i wanted to know how can i make it work"?

the code is:

'use strict';

const bills = [125, 555, 44]

for (var i=0; i< bills.length; i++) {
  let bill = bills[i]
  console.log(bill)
}

if(bill >= 50 && bill<= 300  ) {
  let tip = bill *.15
} else {
  let tip = bill *.20
}
1

2 Answers 2

1

const bills = [125, 555, 44];

// see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

const tips = bills.map(bill => bill >= 50 && bill <= 300 ? bill * 0.15 : bill * 0.20);

for(let i = 0; i < bills.length; i++) {
  console.log(`Bill ${bills[i]}, Tip: ${tips[i]}, Total: ${bills[i] + tips[i]}`)
}

Sign up to request clarification or add additional context in comments.

3 Comments

Hi thank you for replying, but there are 3 differnet bills which means there should be 3 different logs being printed, however in this code there is only one log. i wanted to have each bill separatly runned through the if statemenet and printed out... I have no idea how it is done..
check the edit. it's really unclear what you are trying to do and what any of this information means
That is it!!! thanks! i didnt think about putting everything into the for a statement like that, that was smart! I will try to be more clear next time i have a question, thank you for your input as well! :)
1

Yes, the scope is limited to the for loop. Make it global:

let bill;
for (var i=0; i< bills.length; i++) {
  bill = bills[i]
  console.log(bill)
}

But why do that? it's equivalent to just

let bill = bills[bills.length - 1];

Did you perhaps mean to sum them up?

for (var i=0; i< bills.length; i++) {
  bill += bills[i]
  console.log(bill)
}

1 Comment

So i tried to make the bill global like you said but the issue was it didnt get sent into the if statement equation. i want the bill be sent from the array into the if statement and they print out, but after making the bill global what happened was i got a NaN... I am really new to javascirpt so i appoligize if this doesnt make sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.