Home > Mobile >  issue with scope from 2 javascript statements
issue with scope from 2 javascript statements

Time:09-28

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
}

CodePudding user response:

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)
}

CodePudding user response:

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]}`)
}

  • Related