Unable to save object in JavaScript memory

Currently, I am in the process of implementing a Stack in JavaScript using a LinkedList. However, I encountered an issue when trying to instantiate a Node class. When attempting to create a variable let newNode = new Node(x), I am receiving undefined.

I am unsure why this is happening and would like to gain clarity on the matter. By running new Node(x) in the repl, I get { val: -2, next: null } for a node. But as soon as I store it in a variable, like so: let newNode = new Node(x), it returns undefined when I try to console out newNode.

/**
 * initialize your data structure here.
 */
var MinStack = function() {
  this.size = 0;
  this.min = null;
  this.first = null;
};

var Node = function(val) {
  this.val = val;
  this.next = null;
}
/** 
 * @param {number} x
 * @return {void}
 */
MinStack.prototype.push = function(x) {
  if(this.first == null) {
    this.first = new Node(x);
    this.min = this.first;
    this.size++;
    return
  }

  let newNode = new Node(x);
  if(newNode.val < this.min.val) {
    this.min = newNode.val;
  }
  let oldFirst = this.first;
  newNode.next = oldFirst;
  this.first = newNode;
  this.size++;
};
/**
 * @return {void}
 */
MinStack.prototype.pop = function() {
  if(this.first === null) {
    return;
  }
  if(this.min === this.first) {
    let current = this.first.next;
    this.min = current;
    while(current != null) {
      if(current.val < this.min.val || this.size === 2) {
        this.min = current;
      }
      current = current.next;
    }
  }
  this.first = this.first.next;
  this.size--;
  return
};
/**
 * @return {number}
 */
MinStack.prototype.top = function() {
  return this.first.val;
};
/**
 * @return {number}
 */
MinStack.prototype.getMin = function() {
    return this.min.val;
};
// ["MinStack","push","push","push","getMin","pop","top","getMin"]
// [[],[-2],[0],[-3],[],[],[],[]]

var obj = new MinStack()
obj.push(-2)
obj.push(0)
obj.push(-3)
console.log(obj.getMin())
obj.pop();
obj.top();
obj.getMin();

This is the result at the debugger breakpoint:

> let newNode = new Node(x)
undefined
> newNode
undefined
> new Node(x)
{ val: 0, next: null } 

I am puzzled by this inconsistency – what could be causing this?

Answer №1

"Node.js uses the repl module to create an interactive platform for running JavaScript." Check out more about Node REPL here

As stated in Node REPL documentation, when commands evaluate to undefined, it will display as such on the console.

There are cases where you may see output like:

> newNode
undefined

This is not the expected behavior.

The correct interaction should be:

> x = 0
0
> let newNode = new Node(x)
undefined
> newNode
Node { val: 0, next: null }
> new Node(x)
Node { val: 0, next: null }

Answer №2

An error has been identified in the line below

 if(newNode.val < this.min.val) {
    this.min = newNode.val;
  }

The correct implementation should pass the Node instead of just the value

this.min = newNode.val;

This way, when calling the getMin method, the node's value is accessed.

MinStack.prototype.getMin = function() {
    return this.min.val;
};

Answer №3

Forgot to add a semicolon after closing bracket in the Node class/function definition

var Node = function(value) {
  this.value = value;
  this.nextNode = null;
}

The correct way is

var Node = function(value) {
  this.value = value;
  this.nextNode = null;
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Passing data from the server to the HTML page for manipulation

I need assistance in retrieving and manipulating the value stored in the variable $result[] from a PHP file to my HTML file for further processing. Can you provide guidance or reference code on how to return data from server side to client side? Here is a ...

Unable to retrieve the string contained within an element - JavaScript object literal

I am currently facing an issue where I am attempting to retrieve the text content of two div elements with classes .class-date and .class-time, but I keep encountering an Uncaught TypeError stating "e.siblings is not a function". I believe this may be a ...

Filtering a string array in Angular based on an object's value

I am facing a challenge with two arrays in my code. The first array, $scope.termini, contains strings, and the other one, $scope.reserved, contains objects. Each object in the second array has a variable called vrijemeTermina. My goal is to filter $scope.t ...

Retrieving decimal value from a given string

Currently, I am working with Google Maps and encountering an issue with distance values being returned as strings like 1,230.6 km. My goal is to extract the floating number 1230.6 from this string. Below is my attempted solution: var t = '1,234.04 km ...

The second tab on Bootstrap5's tab content feature seems to generate an endless amount of white

I am working on a project where I need to display statistics for both the current month and year. To organize this data, I created a card with tabs for each - one tab for the month and another for the year. By default, the month tab is loaded first. Howev ...

the value of properrty becomes undefined upon loading

In my code, there exists an abstract class named DynamicGridClass, containing an optional property called showGlobalActions?: boolean?. This class serves as the blueprint for another component called MatDynamicGridComponent, which is a child component. Ins ...

What is the best way to secure the installation of python packages for long-term use while executing my code within a python shell on NodeJS?

I have been encountering difficulties while attempting to install modules such as cv2 and numpy. Although I have come across a few solutions, each time the shell is used the installation process occurs again, resulting in increased response times. Below i ...

Should we pass <script> tags or unsanitized values to the Handlebars layout?

How can I pass values to handlebars that are not sanitized upon output? For instance, I want to ensure that when using the code res.render('index', {script: '<script src="bundle.js"></script>'}), it is not rendered as {{scri ...

Jenkins integration with a MEAN stack application: A step-by-step guide

I'm working on a Mean stack application and looking to integrate Jenkins CI into my workflow. I am uncertain about the steps needed to accomplish this task. Currently, I use bower for installing frontend packages and npm for other functionalities. ...

return to the original secured page based on the most recent language preference

I'm facing an issue with a logical redirection that needs to redirect users to the previous protected page after login. The login functionality is implemented using my custom login page and Google Credentials. Additionally, I have set up a multilingu ...

Occasionally, the function `Element.getElementByTag("mytag")` may come up empty

Here is the outer html of Element1 in CKeditor: <element1 id="s1"> <mytag>Test1</mytag> <span> </span> Some text <mytag>Test</mytag> <span> </span> <mytag>Test3</mytag> some text <span&g ...

Troubles arise when attempting to utilize yarn for my projects

Whenever I enter the command yarn start in the terminal, I get this output: yarn run v1.22.4 $ react-scripts start 'react-scripts' is not recognized as an internal or external command, operable program or batch file. error Command fai ...

Could anyone provide an explanation of the current situation in this section of the code?

I am currently working on a piece of code that looks like this: ruter.get('/', async function (_, res) { const [categories, items] = (await Promise.all([ db.query('SELECT * FROM categories'), db.query('SELECT * FROM invento ...

Several DIVs with the same class can have varying CSS values

I am looking to modify the left-margin value of various separate DIVs using JavaScript. The challenge is: I only want to use a single className, and I want the margin to increase by 100px for each instance of the class. This way, instead of all the DIVs ...

Need help implementing the disableGutters property on MTableToolbar?

I am currently using react material-table and I would like to customize the default toolbar styles by passing the prop disableGutters={true}, similar to how it's done in material-ui toolbar. Below is the code snippet that I have tried: <MaterialTab ...

Is there a way to see the countdown timers in Angular 7?

Is there a way for me to view my timer's countdown as it starts? I have attempted to bind it to a variable, but all I see is [object Object]: setTime(time) { if (this.settime >= 5 ) { this.currentTime = time; this.alerttime = thi ...

Modifying the Redux state using an array with prototypes

In my React application, I am utilizing Redux along with the ChartJS library to create charts. Occasionally, when I extract an array from the global Redux state, it appears in this format: ejeY: Array(7) 0: 43783 1: 85001 2: 100960 3: 752 ...

Invoking an *.aspx method from an external HTML file

Greetings, I am a newcomer to the world of web application development. I have successfully created an *aspx page that communicates with a webservice through a method returning a string. My next goal is to invoke this aspx method from a remote HTML 5 page ...

PHP - Offline/Online Status Polling Protocol Guide for Beginners

I am in search of a solution to track the online and offline status of users on my website. My site is a single page with no clickable links, so users may leave their tabs open for long periods without interaction. It is not essential to pinpoint the exact ...

When evaluating objects or arrays of objects to determine modifications

How can we detect changes in table data when users add input to cells? For example, if a user clicks on a cell and adds an input, the function should return TRUE to indicate that there are changes. If the user just clicks on the cell without making any ch ...