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

Enhancing DataTable Performance with Django Filters

I have implemented a feature where users can apply filters to customize the data displayed in a Table. When a user interacts with these filters, an asynchronous Ajax call is triggered: $.ajax({ url: '/fund_monitor/fund_directory&a ...

Exploring the functionalities of Express and Socket.io

I am new to creating a Node.js app using express V 3.4.8 and socket.io V 0.9.16 to display a map with markers showing where users are connecting to the site. I am doing this to learn more about node.js and how to incorporate maps into my projects. However, ...

What are some strategies for postponing the execution of a basic function for an

Whenever I develop microservices, I often come across situations where one function contains multiple other functions. For instance: functionA(); functionB(); functionC(); return json({status: processed}); All the functions within this block are synchro ...

Contrasting onevent with addEventListener

After studying various DOM events, I attempted to implement the 'blur' event on the HTML body. My first attempt was with onblur document.body.onblur = () => { dosomething(); } and I also tried using AddEventListener document.body.addEven ...

How can multiple functions be grouped and exported in a separate file in Node.js?

Is there a way to consolidate and export multiple functions in nodejs? I want to gather all my utility functions in utils.js: async function example1 () { return 'example 1' } async function example2 () { return 'example 2' } ...

Issue with text input field causing the Enter key to not create a new line

In the example above, the text is placed in the middle of the text area. Here is the CSS code : .form-control { height: 300px; display: block; width: 100%; padding: 0.375rem 0.75rem; font-size: 1rem; font-weight: 400; line-heig ...

Easy Steps for Mapping Json Data into an Array

Here is the JSON Format I am working with: { "Data": { "-template": "Parallax", "Explore": { "IslandLife": { "TourismLocation": [ { "Title": "Langkawi", "Latitude": "6.350000", "Longitude": "99.800000", "YouTub ...

Encountering the error message 'XMLHttpRequest is not defined' while incorporating getServerSideProps() in NextJS

I'm currently exploring NextJS with SSR and encountering an error when trying to fetch data from a Spotify playlist using the spotify-web-api-js library. This issue only occurs when executing on the server side: error - ReferenceError: XMLHttpRequest ...

Can a string or javascript object be uploaded without being saved in a file? - IPFS

I've been exploring the capabilities of js-ipfs API and I'm curious to know if js-ipfs is limited to only uploading files/folders. Is there a way to upload other types of data, such as a JavaScript object like: { heading:"SomeHeading", c ...

What are the steps for installing the latest version of popper, v2?

When you run the following command: npm install popper.js --save You will receive a warning message that says: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="81f1eef1f1e4f3afebf2c1b0afb0b7afb0">[email& ...

Unable to retrieve data from the array

I am encountering an issue while trying to fetch data from an array, as I keep receiving undefined Please refer to the image for a visual representation of my problem. I'm not sure what I might be overlooking, so any help would be greatly appreciate ...

Determining the elapsed time using Momentjs

I need assistance with a NodeJS project where I am trying to determine if a specific amount of time (like 1 hour) has passed since creating an object. My project involves the use of MomentJS. For example, if moment(book.createdAt).fromNow() shows 2 hours ...

The mapDispatchToProps function is failing to work, throwing an error: Uncaught TypeError: _this.props.addCountdown is not a function

Currently, I am facing an issue while working on my first app. The problem arises with a form component that should send an object via an onSubmit handler. onSubmit = (e) => { e.preventDefault(); this.props.onSubmit({ title: ...

How to enable drag-and-drop functionality for an iframe?

I've successfully made a chat widget draggable using react-draggable. However, the chat widget is also consumed by an iframe created entirely with HTML. I need the iframe to be draggable as well, but react-draggable doesn't support this. Are ther ...

Optional parameters in Sammy.js

Utilizing ajax for paging has led me to choose Sammy.js, which works well. However, incorporating checkboxes to filter results poses a challenge. While defining a route for Sammy to intercept is feasible, the issue arises when I wish to avoid displaying ce ...

JavaScript code returning the correct result, however, it is unable to capture all characters in the returned string

Currently, I am utilizing $.post to retrieve results from a database. The syntax I am using is as follows: $.post('addbundle_summary', {id:id}, function(resultsummary) { alert(resultsummary[0]); }) In CodeIgniter, within my model, I am retu ...

Utilizing the Power of AJAX in Combination with an Event Loop

I have a function that is supposed to make AJAX requests with an event loop while taking 9 inputs at the top and querying them from a database. Currently, it only logs to the console but will eventually perform more actions. However, I am encountering an ...

What is the best way to access data stored in the state of the store.js within a Vue application?

Currently, I am working on my initial project using Vue.js. The application involves a multi-step form that shares a common header and footer. As the user progresses through each step, the data entered is sent to store.js for storage. However, I have encou ...

Errors and disruptions caused by SmoothScroll, ScrollMagic, and GSAP triggering glitches, jumps, and crashes

Connecting ScrollMagic with GSAP is not an issue - it works seamlessly. However, I encountered a problem when trying to implement smooth scrolling for my mouse. I added a smooth scrolling plugin to my project from this link: http://www.jqueryscript.net/ani ...

"Enhancing User Experience with AngularJS by Dynamically Modifying and Refresh

I'm currently attempting to dynamically add HTML elements using JavaScript with a directive: document.getElementsByClassName("day-grid")[0].innerHTML = "<div ng-uc-day-event></div>"; or var ele = document.createElement("div"); ele.setAttr ...