OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

How I return something from class methods?

  • Thread starter Thread starter Mohammad Ullah
  • Start date Start date
M

Mohammad Ullah

Guest
In constructor function I returned this.ar, and in push method I returned item, but the problem is when I return from constructor and push both, only the constructor returns, and push returns 1,2,3... is there any solution? I want when user console the class then print the array -- (this.ar). Note: IIFE not working in class object.

Code:
class Arr{
    constructor(ar){
        this.top = -1;
        this.ar = ar;
        return this.ar;
    }
    
    push(item){
        if(this.ar.length >= 0 ){
            this.top = this.ar.length - 1;
            this.top++;
            this.ar[this.top] = item;
            return item;
        }
        else{
            return "Something went wrong";
        }
    }
    

}
const stack = [];
const array = new Arr(stack);

console.log(array.push(3));

console.log(array);

I tried IIFE which not gonna work in class, and I returned this.ar from direct class, it's also not works. I want the output - show code comment right side.

Code:
const stack = [];
const array = new Arr(stack);

console.log(array.push(3)); // 3
console.log(array.push(4)); // 4


console.log(array); // [3,4]

<p>In constructor function I returned this.ar, and in push method I returned item, but the problem is when I return from constructor and push both, only the constructor returns, and push returns 1,2,3... is there any solution?
I want when user console the class then print the array -- (this.ar).
Note: IIFE not working in class object.</p>
<pre><code>class Arr{
constructor(ar){
this.top = -1;
this.ar = ar;
return this.ar;
}

push(item){
if(this.ar.length >= 0 ){
this.top = this.ar.length - 1;
this.top++;
this.ar[this.top] = item;
return item;
}
else{
return "Something went wrong";
}
}


}
const stack = [];
const array = new Arr(stack);

console.log(array.push(3));

console.log(array);
</code></pre>
<p>I tried IIFE which not gonna work in class, and I returned this.ar from direct class, it's also not works. I want the output - show code comment right side.</p>
<pre><code>const stack = [];
const array = new Arr(stack);

console.log(array.push(3)); // 3
console.log(array.push(4)); // 4


console.log(array); // [3,4]
</code></pre>
 

Latest posts

Top