0

Do you have an idea how I could get it to work?

const TAX_RATE = 0.08;

var purchase_amount = 10;

function addTax(amt) {
  amt += amt * TAX_RATE;
}

addTax( purchase_amount );

console.log( purchase_amount );
t3ol5
  • 94
  • 7

4 Answers4

1

Reassigning amt within your addTax function doesn't affect anything outside of it, so you need to return the new value, and have it assigned to purchase_amount when you call the function.

const TAX_RATE = 0.08;
let purchase_amount = 10;
function addTax(amt) {
  return amt + amt * TAX_RATE;
}
purchase_amount = addTax( purchase_amount );
console.log( purchase_amount );
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

Return the value from the function.amt becomes a local variable inside the function only

const TAX_RATE = 0.08;

var purchase_amount = 10;

function addTax(amt) {
  amt += amt * TAX_RATE;
  return amt;
}

var newAmt = addTax(purchase_amount);

console.log(newAmt);
brk
  • 48,835
  • 10
  • 56
  • 78
1

Javascript doesn't pass parameters by reference, so you have to return the value you need from the function, or pass object reference as value to the function. Check Pass Variables by Reference in Javascript.

loler
  • 2,594
  • 1
  • 20
  • 30
1

While the others answers are correct, that JavaScript is pass by value, and not pass by reference this is not exactly the case for objects.

I'm not certain offhand why exactly JavaScript does this (somebody else might be able to explain the exact reasoning better) but when you pass an object into a function, the original object is modified within the function.

So if you were to do this, this would work without having to set any outside values. This would be especially helpful in cases where you are uses custom class objects.

function addTax( obj ) {
    if ( typeof obj['tax_rate'] == "undefined" ) return;
    
    obj['cost'] = obj['cost'] + ( obj['cost'] * obj['tax_rate'] );
    delete obj['tax_rate'];
}

var myTaxObject = {
    cost: 10,
    tax_rate: 0.08
}

addTax( myTaxObject );

console.log( myTaxObject );

Food for thought.