Appliquer la notion

Voici un code qui ne retourne pas le résultat prévu :

1
function htToTtc (htPrice) {
2
  priceToPay = 1.2 * htPrice
3
  return priceToPay
4
}
5
6
const prices = [10, 20, 5]
7
8
let priceToPay = 0
9
for (let i = 0; i < prices.length; i++) {
10
  const currentPrice = htToTtc(prices[i])
11
  priceToPay = priceToPay + currentPrice
12
}
13
14
console.log('Vous devez payer ', priceToPay)
15

Question

Exécuter le code et donner le résultat affiché.

Question

Quel résultat devrait être retourné ?

Indice

Pour passer du prix TTC au prix HT, il faut ajouter 20 % au prix hors taxes.

Question

Corriger le bug et proposer le code corrigé.

Indice

Il y a un problème lié à la portée d'une des variables.

Solution

1
function htToTtc (htPrice) {
2
  const priceToPay = 1.2 * htPrice
3
  return priceToPay
4
}
5
6
const prices = [10, 20, 5]
7
8
let priceToPay = 0
9
for (let i = 0; i < prices.length; i++) {
10
  const currentPrice = htToTtc(prices[i])
11
  priceToPay = priceToPay + currentPrice
12
}
13
14
console.log('Vous devez payer ', priceToPay)
15