Exploring how JavaScript variables behave when used inside a nested forEach loop with an undefined

While inside the second for loop, I am attempting to retrieve the value of this.userId. However, it is returning undefined. Let's take a look at the code snippet below:

// The following variable becomes undefined within the second for loop
this.userId = localStorage.getItem('userId');

this.reviews.forEach(function(element1){
  element1.usersWhoLike.forEach(function(element2) {
    if(element2 == this.userId){
      // This results in undefined !!
      console.log('UserID is : ', this.userId)
    }
  });
});

Answer №1

Your forEach loop is missing the scope of the function. Here's a revised version:

this.reviews.forEach((element1) => {

    element1.usersWhoLike.forEach((element2) => {
   
        if(element2 === userId){
            // This will not throw undefined now
            console.log('User ID is: ', this.userId);
        }
    
    }, this);

}, this);

Answer №2

const currentUserId = localStorage.getItem('userId');

Make sure to include this statement within the initial loop iteration.

Answer №3

When using this.userId in the second block of code, it actually refers to the function scope itself. To avoid any confusion, consider adding a variable called 'self' as reference.


this.userId = localStorage.getItem('userId');

var self = this; // Creating a reference
this.reviews.forEach(function(element1){

    element1.usersWhoLike.forEach(function(element2) {

        if(element2 == userId){
            // The use of 'this' here might result in undefined !!
            console.log('UserID is : ', self.userId)
        }

    });

});

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

Getting the WatchPosition update just one time

I have implemented this code to continuously retrieve the first position and I need it to keep doing so. var init = function() { navigator.geolocation.getCurrentPosition(function(position) { new_position = position; }, onEr ...

Is it possible for me to overlap a text over hidden text, and if the hidden text becomes visible through JavaScript, my text will shift to the right of the now visible hidden text?

I'm currently working on a website for a company that requires users to complete all the information before proceeding. To achieve this, I created a form with the following code: <form action="Owners Infoback.php" onsubmit="return validateFo ...

I am looking to dynamically add and remove an active link on my sidebar using JavaScript

Looking to create a dynamic website with interactive features like adding and removing active links upon clicking, and smooth transitioning between sections using JavaScript. Feel free to skip over the SVG code. HTML source code <div class="s ...

Issue encountered with websocket connection while attempting to include dependencies

My current project involves integrating charts for the graphical component using React within an Electron software. I've added interaction with buttons (sections) to insert different data into the graphs based on user clicks on one of the sections. Th ...

Having trouble updating an array in a mongoose document?

Need help with updating an array in a document by adding or replacing objects based on certain conditions? It seems like only the $set parameter is working for you. Here's a look at my mongoose schema: var cartSchema = mongoose.Schema({ mail: Stri ...

Utilizing the Current URL from the address bar as a variable to link within the same page

My goal is to: Extract the current URL address from the browser bar, which will have a format like this: http://example.com/test/index.html?&dv1=1023faf2ee37cbbfa441eca0e1a36c Retrieve the lengthy ID number located at the end of the URL 1023faf2ee37c ...

Transforming jQuery into pure Javascript code

UPDATE SUCCESS! I've cracked the code. The solution was to include jQuery by adding it in Joomla through the template/index.php file with this line under "//Add Javascript Frameworks" JHtml::_('jquery.framework');. PROGRESS I'm seekin ...

Offline communication between Android and JavaScript web applications

I'm a newcomer to this whole scenario - I have a JavaScript web app up and running on a Windows 7 machine using Google Chrome, as well as an Android app. I'd like to establish an offline connection between the two to exchange data, keeping in min ...

I am attempting to retrieve the initial three results from my MySQL database using Node.js, but I keep encountering an error

Below is the code I am currently using: con.query('SELECT * FROM tables', function(err, results) { if (err) throw err console.log(results[0].rawname) for(var i= 0; i <= 3; i++) { ...

The issue of VueRouter malfunctioning in history mode within Wordpress

I have integrated Vue into my Wordpress theme, but I am facing an issue with the router when setting mode: 'history'. The site goes blank and even after trying to configure the .htaccess file, nothing seems to work. My project is located in the V ...

Is the order of return guaranteed for Ajax requests?

This particular inquiry raises the question of whether Ajax requests follow the order in which they are sent. While it appears that Ajax requests may not always return in the same order they were dispatched, the use of the TCP protocol suggests that packet ...

What is the best way to determine the file size using Node.js?

My current challenge involves using multer for uploading images and documents with a restriction on file size, specifically limiting uploads to files under 2MB. I have attempted to find the size of the file or document using the code below, but it is not p ...

Is there a way to detect when the escape key is pressed?

Is there a way to detect when the escape key is pressed in Internet Explorer, Firefox, and Chrome? I have code that works in IE and alerts 27, but in Firefox it alerts 0 $('body').keypress(function(e){ alert(e.which); if(e.which == 27){ ...

Three.js is experiencing difficulties in loading textures for custom Geometry with ShaderMaterial

A Geometry (pyramid) is defined here with four vertices and 4 faces - var geom = new THREE.Geometry(); geom.vertices.push(new THREE.Vector3(0,100,0), new THREE.Vector3(-100,-100,100), new THREE.Vector3(0,-100,-100), new THREE.Vector3(100,-100,100)); geom ...

Koa and Stripe are patiently holding off on displaying the page

My current setup involves using koa and stripe for processing a one-time payment. Although the functionality is there, I'm facing an issue where the page renders before the 'data' assignment takes place. This results in the 'id' sh ...

What measures can be taken to prevent the reloading of a subfolder within the same parent in the Fuel

var DataSourceTree = function (options) { this.source = options.source; } DataSourceTree.prototype = { data: function (options, callback) { var self = this; var ...

Pseudonym fields used for parsing JSON data

On my homepage, users have the ability to upload JSON fields that require parsing. I am specifically looking for certain fields that may have numerous alias names. I am uncertain about the best approach to take in order to identify these aliases. Currentl ...

directive in Angular ordering

After exploring this link, my understanding deepened: http://plnkr.co/edit/k5fHMU?p=preview Upon analyzing the code snippet provided in the link above, I noticed that the Angular app consists of both a controller and a directive. However, there seems to ...

Evolution of the same-origin policy in relation to XMLHttpRequest requests throughout history

About four years ago, I wrote some JavaScript code that included an XMLHttpRequest request. It originally looked like this: xmlhttp.open('GET', 'http://www.example.com/script.php?arg=val&sid=' + Math.random(),true) ; However, sinc ...

Choose all the alternative A radio buttons utilizing JavaScript

If the "4 stars" option is selected at the top, I want all corresponding "4 stars" options in the form to be automatically selected. Similarly, if "3 stars" is chosen, I need all the "3 stars" options to be selected. I attempted to achieve this functionali ...