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
}
Christian Fritz
  • 20,641
  • 3
  • 42
  • 71
  • Does this answer your question? [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – fabian Sep 28 '21 at 00:38

2 Answers2

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)
}
Christian Fritz
  • 20,641
  • 3
  • 42
  • 71
  • 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. – Golden-Dragon Sep 28 '21 at 00:52
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]}`)
}
Jhecht
  • 4,407
  • 1
  • 26
  • 44
  • 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.. – Golden-Dragon Sep 28 '21 at 02:13
  • check the edit. it's really unclear what you are trying to do and what any of this information means – Jhecht Sep 28 '21 at 02:50
  • 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! :) – Golden-Dragon Sep 28 '21 at 03:20