3

I am trying to implement a stack. when I try to push into the arr this error pops up

TypeError: Cannot read property 'push' of undefined

var MinStack = function() {
    let Min = null;
    const arr = new Array(); // I also tried arr = []
};

/** 
 * @param {number} x
 * @return {void}
 */
MinStack.prototype.push = function(x) {
    this.arr.push(x);
    this.Min = Math.min(...arr);
};

I searched for answers but I didn't find out why can't I access my arr in the constructor?

1
  • 1
    you can not because Min and arr are private properties of the constructor function and can not be accessed by the instantiated ones. Such as when done like var x = new MinStack() then x has access to it's constructors prototype and known as the this, hence x is the this in MinStack.prototype.push but x does not have any way to access Min or arr. So this.arr is undefined... Commented Apr 10, 2020 at 15:33

1 Answer 1

2

This is because this.arr is not defined.

You have defined the arr as a variable as you have used let to declare it, but not as a property of the instances of MinStack.

Variables declared using let or const are scoped to the enclosing block and not available outside of it.

The enclosing block in your case the function block, so it becomes a local variable scoped to the function and not visible outside of it.

When you use a function as a constructor and use the new keyword to instantiate it a new object is created in memory and is assigned to the this reference in the constructor function. properties assigned to that this reference become properties of the instance created from the constructor function:

var MinStack = function() {
    this.Min = null;
    this.arr = new Array(); 
};

/** 
 * @param {number} x
 * @return {void}
 */
MinStack.prototype.push = function(x) {
    this.arr.push(x);
    this.Min = Math.min(...this.arr);
};

MinStack.prototype.min = function(x) {
    return this.Min;
};

const minArr = new MinStack();
minArr.push(1);
minArr.push(2);
minArr.push(3);
minArr.push(-9);
console.log(minArr.min());

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.