0

The following code works fine

// Define the closure
var rentPrice = function (initialRent) {
  var rent = initialRent;

  // Define private variables for
  // the closure
  return {
    getRent: function () {
      return console.log(rent);
    },
    incRent: function (amount) {
      rent += amount;
      console.log(rent);
    },
    decRent: function (amount) {
      rent -= amount;
      console.log(rent);
    },
  };
};

var Rent = rentPrice(8000);

// Access the private methods
Rent.incRent(2000);
Rent.decRent(1500);
Rent.decRent(1000);
Rent.incRent(2000);
Rent.getRent();

But if I change it to let or const it gives an error

VM1926:1 Uncaught SyntaxError: Identifier 'rentPrice' has already been declared

So if the code is changed to the following it gives the error

// Define the closure
let rentPrice = function (initialRent) {
  let rent = initialRent;

  // Define private variables for
  // the closure
  return {
    getRent: function () {
      return console.log(rent);
    },
    incRent: function (amount) {
      rent += amount;
      console.log(rent);
    },
    decRent: function (amount) {
      rent -= amount;
      console.log(rent);
    },
  };
};

let Rent = rentPrice(8000);

// Access the private methods
Rent.incRent(2000);
Rent.decRent(1500);
Rent.decRent(1000);
Rent.incRent(2000);
Rent.getRent();

Question :- Why am I getting this error I am not redeclaring rentPrice I am invoking it and storing it in a variable Rent so why am I getting this error ?

Image

Sachin
  • 149
  • 1
  • 16
  • 3
    There's probably some additional piece of code that does `let rentPrice = /* something */`. I would not expect the code you've shown to give that error on its own. And i just converted it to snippets in your question, and i see no error. – Nicholas Tower Nov 30 '22 at 18:48
  • 1
    Can confirm that the code shown does not cause any error – Cjmarkham Nov 30 '22 at 18:49
  • @Nicholas Tower Ok this might be due to the fact that first I ran the code with var on my broswer console and then edited the var with let using the keyboard up arrow key so it might be that previous code still had rentPrice declared that's why I am getting this error. – Sachin Nov 30 '22 at 18:56
  • Ah yeah, if you're running this in your browser console, and you run it multiple times, then you'll get the error. By running it twice, you're trying to declare a variable with the same name twice. – Nicholas Tower Nov 30 '22 at 18:57

0 Answers0