What is the reason for the value of an object's key becoming undefined when it is set within a loop?

I've always wondered why setting a certain object's key as its own value in a loop results in undefined.

Take this code block, for example:

var text = 'this is my example text', obj = {}, words = text.split(' ');
  for (i = 0; i < words.length; i++) {
    obj[words[i]] = obj[words[i]]; //Focus on this line
    console.log(obj);
}
obj;

What gets printed out:

https://i.sstatic.net/84mhQ.png

Of course, with a bit of type coercion, you can do some interesting things:

obj[words[i]] = (obj[words[i]] || 0)+1;

The result looks like this:

https://i.sstatic.net/CZfun.png

But what's the reason behind it displaying undefined initially? I'm eager to grasp the underlying concept.

Answer №1

Initially, when accessing someObj[words[i]], it would return undefined.

By assigning undefined, this is the outcome.

var string = 'this is is it',
    someObj = {},
    words = string.split(' '),
    i;

for (i = 0; i < words.length; i++) {
    console.log(someObj[words[i]]);
    someObj[words[i]] = someObj[words[i]]; // note: Pay attention here
    console.log(someObj);
}

The provided solution evaluates the actual value for truthiness and returns a value if falsy.

someObj[words[i]] || 0  // returns either a truthy value from the left side or zero
// undefined      || 0 --> 0  right value
// 0              || 0 --> 0  right value
// 1              || 0 --> 1  left value

var string = 'this is is it',
    someObj = {},
    words = string.split(' '),
    i;

for (i = 0; i < words.length; i++) {
    console.log(someObj[words[i]] || 0);
    someObj[words[i]] = (someObj[words[i]] || 0) + 1;
    console.log(someObj);
}

Answer №2

At this moment

someObj[words[i]] = someObj[words[i]];

The snippet of code suggests that within the someObj object, it should search for a key that matches the value of words[i] and then assign it the same value of someObj[words[i]], which ultimately turns out to be undefined for each iteration of i.

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

What security measures does Angular implement to safeguard against malicious user input?

While I was learning how to build a router in vanilla JS, the tutorial author mentioned that it's advisable to use frameworks like Angular or React for various reasons. The author pointed out that Angular, for example, sanitizes user input before inse ...

How can you set a $_GET variable without having to reload the page?

I have a table on my website that displays values for each row, and here's an example code snippet: //JAVASCRIPT <tr onclick="window.history.replaceState(null, null, 'myPage.php?ID=2');"> The URL changes with this code, but it doesn& ...

Encountering errors like "Cannot find element #app" and "TypeError: Cannot read property 'matched' of undefined" typically happens when using vue-router

Recently, I decided to dive into Vue.js as a way to revamp an existing frontend app that was originally built using Scala Play. My goal is to explore the world of component-based web design and enhance my skills in this area. Initially, everything seemed ...

Downsides of utilizing variables as global entities in React components

I am currently working on integrating API data into my React component: const request = new XMLHttpRequest() let outputArray = [] request.open('GET', 'http://localhost:3005/products/157963', true) request.onload = function() { let d ...

Ways to filter and display multiple table data retrieved from an API based on checkbox selection in Angular 2 or JavaScript

Here is a demonstration of Redbus, where bus data appears after clicking various checkboxes. I am looking to implement a similar filter in Angular 2. In my scenario, the data is fetched from an API and stored in multiple table formats. I require the abili ...

SecurityError: The dubious operation triggers CORS to persist in its insecurities

I have developed an HTTP server using Express in Node.js. This server is currently running locally on port 3000. There is a served HTML page called "index.html" which makes AJAX GET requests for contents (in HTML format). These AJAX contents are also serv ...

Having trouble parsing an array from req.body using Node.js Express

I am currently facing an issue while trying to retrieve an array from a JSON request using Postman. In my Node.js application, I am able to read all values from req.body except for the array. When attempting to access the array, I only receive the first va ...

creating a JSON object

Exploring JSON for the first time and I have a couple of questions: Is it possible to create a JSON object using the 'data-id' attribute and have it contain a single array of numbers? Even though I have the code to do this, I am facing difficul ...

Animating shapes in Three.js

Is it possible to animate the underlying shape of a mesh created using Three.js by drawing a shape and extruding it? For example: drawShape: function(){ var shape = new THREE.Shape(); shape.moveTo(0, 0); shape.arc(0,0,30,0,(Math.PI*1.9),true) ...

Tips for designing a customizable color scheme for your website

Are you looking to implement a changeable color scheme for your website? Getting started can be daunting, especially if you're unfamiliar with sass. Would appreciate it if anyone could share some helpful tutorials or links? For example: example ...

Trouble with hide/show loop in setTimeout function

I have a special animation with 3 text items that are initially invisible. The goal is to make these items appear one by one with a delay of 2 seconds after clicking a button. Each item should be visible for 1 second before fading out and making way for th ...

Are you ready to create a Modal Factory?

For a while now, I have been utilizing modals in various front-end frameworks to communicate with users in my applications. Typically, the process involves defining the modal's html and then rendering it through a click event. As my apps continue to ...

How come the useState function remains undefined, even when initialized with a default value?

I attempted to set an empty array as the default value for a state using the useState hook in React. However, when I try to check the type of testing with console.log(Array.isArray(testing)); or simply log testing, it always displays undefined regardless o ...

Issues with the event firing in the Polymer component for google-signin?

I recently set up a new starter-kit project using polymer-cli 1.7 and I'm attempting to incorporate Google authentication utilizing the google-signin element. Although the sign in button appears and works for signing in, the signedIn property isn&apo ...

Nested loop combining Callback and Promise with two API requests

I apologize for the lackluster title, but I couldn't come up with anything more suitable. If this issue has already been addressed, please let me know in the comments and I will delete it promptly. However, keep in mind that this is a specific questio ...

Deactivating the idle timer in React Native: A Step-by-Step Guide

Currently, I am working on an app that involves a timer using RN. However, I have noticed that after approximately 1 minute and 50 seconds, the device's screen starts to dim in preparation for sleep mode. ...

What is the best way to separate axios functions and components in Vue3?

In my opinion, it's more efficient to separate the axios commands from the vue components. This is how I structured my directories: src api - products.js components - Products.vue products.js import axios from 'axios'; const li ...

Seeking assistance in optimizing my Javascript code for more efficient canvas rendering

I've created a script for generating random moving lines as a background element for my portfolio. While it runs smoothly on its own, I encounter frame drops when combining it with other CSS animations and effects, especially at the beginning (althoug ...

What is the best way to incorporate a variable in the find() method to search for similar matches?

I've been working on a dictionary web application and now I'm in the process of developing a search engine. My goal is to allow users to enter part of a word and receive all similar matches. For instance, if they type "ava", they should get back ...

What is the reasoning behind exporting it in this manner in the index file?

As I was going through a tutorial about nests, there was this step where the instructor made a folder named "dtos" and inside it, they created two dto files (create-user.dto and edit-user.dto). Following that, they also added an index file in the same fold ...