This question is an exact duplicate:

There is such code, found in the book on js. There are no errors in this example. everything is displayed as it should and output 450

'use strict'; function CoffeeMachine(power, capacity) { var waterAmount = 0; this.waterAmount = function(amount) { if(!arguments.length) return waterAmount; if(amount < 0) { throw new Error('Значение должно быть положительным!'); } if(amount > capacity) { throw new Error('Значение не должно быть больше ' + capacity); } waterAmount = amount; }; } var coffeeMachine = new CoffeeMachine(1000, 500); coffeeMachine.waterAmount(450); alert(coffeeMachine.waterAmount()); 

But in this example, undefined is displayed.

 'use strict'; function CoffeeMachine(power, capacity) { var waterAmount = 0; this.waterAmount = function(amount) { if(!arguments.length) return waterAmount; if(amount < 0) { throw new Error('Значение должно быть положительным!'); } if(amount > capacity) { throw new Error('Значение не дожно быть больше ' + capacity); } waterAmount = amount; }; } var coffeeMachine = new CoffeeMachine(1000, 500); alert(coffeeMachine.waterAmount(450)); 

Then I just recorded the alert immediately and that's it. explain what is the difference, why when it is not recorded in the alert then everything works, but on the contrary it does not.

Reported as a duplicate by the participants andreymal , nick_n_a , Yaant , Grundy javascript Feb 12 at 9:20 pm

This question has been marked as a duplicate of an existing one.

  • coffeeMachine.waterAmount(450) and coffeeMachine.waterAmount() - there is a difference. - nick_n_a February
  • 3
    Full duplicate: Error while outputting JavaScript data - andreymal
  • one
    And what is the relationship between the title of the question and its text? - Yaant 3:51 pm

2 answers 2

 // вызов без параметров - getter - возвращает текущее значение var a1 = coffeeMachine.waterAmount(); // вызов с параметром - setter - ничего не возвращает var a2 = coffeeMachine.waterAmount(123); console.log(a1, a2); 

Can write

  this.waterAmount = function(amount) { if(!arguments.length) return waterAmount; ... return waterAmount = amount; }; 

Then setter will return the new value.

    Look .. the following is happening - the first time you call

     coffeeMachine.waterAmount(450); 

    your function does not give anything because the conditions in the if are not satisfied: the first if
    !arguments.length - will be true if the waterAmount method has no arguments .. and there are no more retracts. therefore, the method returns nothing. but the method writes the value

     waterAmount = amount 

    and the next time it is called without parameters, the first if will be executed and the value 450 will be returned. hence this behavior. so that it would work in the alert call the method with the argument, and in the alert without.

    • yes .. and with the setters here I somehow don’t see any connection - Sergey Petrashko