-3

function tipCalculator(bill) {
  var tip;
  if (bill < 50) {
    tip = 0.2 * bill;
  } else if (bill > 50 && bill < 200) {
    tip = 0.15 * bill;
  } else {
    tip = 0.10 * bill;
  }
  return tip;
}

bills = [124, 48, 268];
Tip = [tipCalculator(bills[0]),
  tipCalculator(bills[1]),
  tipCalculator(bills[2])
];

console.log(Tip);

I have written this Javascript code pls tell me if this is correct or not because I have not defined the Arrays bills and Tip

1 Answers1

3

It's valid syntactically, in loose mode.

There's an argument to be made that it has an error, though, because as you say you don't declare bills or tip, so the code is relying on what I call The Horror of Implicit Globals: If you assign to an undeclared identifier in loose mode, it creates a global variable. Not a good idea.

I recommend using strict mode, which makes doing that an error:

"use strict";
function tipCalculator(bill) {
  var tip;
  if (bill < 50) {
    tip = 0.2 * bill;
  } else if (bill > 50 && bill < 200) {
    tip = 0.15 * bill;
  } else {
    tip = 0.10 * bill;
  }
  return tip;
}

bills = [124, 48, 268];
Tip = [tipCalculator(bills[0]),
  tipCalculator(bills[1]),
  tipCalculator(bills[2])
];

console.log(Tip);

Strict mode is opt-in in scripts (the "use strict"; above), but is the default within class constructs and JavaScript standard modules (aka "ESM modules").

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875