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:

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:

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

Detecting Specific Web Browsers on My Website: What's the Best Approach?

My website is experiencing compatibility issues with certain browsers, such as Firefox. I want to display a message when users visit the webpage using an unsupported browser, similar to how http://species-in-pieces.com shows a notification saying "Works ...

Arrange the div and ensure that the external JavaScript file functions properly when the page loads

I am encountering an issue with my JavaScript and CSS code. It works perfectly fine within the fiddle environment but fails to function properly outside of it. Here is the link to the fiddle When I embed the code into an HTML document directly, it does n ...

Update Button Visibility Based on State Change in ReactJS

Currently, I'm utilizing a Material UI button within my React application. Despite changing the state, the button remains visible on the screen. Here's the relevant code snippet: function MainPage() { const state = useSelector(state => sta ...

Error: The Google Translate key is not found in the Node.js AJAX request

I have a basic Node.js script that functions properly when executed locally in the terminal: exports.google_translate = function (translate_text, res) { var Translate = require('@google-cloud/translate'); var translate = new Trans ...

What is this error: "Unknown authentication strategy 'loca'"?

Whenever I try to utilize passport.js, it keeps throwing the following error: Unknown authentication strategy "local"! config/configuration.js var passport = require('passport') , LocalStrategy = require('passport-local').Strategy; ...

Troubleshooting issue with applying hover effect to child divs

How come when I hover over one of the child items in my parentDiv, the background of the last childDiv changes no matter which child I place my mouse on? for (let i = 0; i < Number(height); i++) { for (let j = 0; j < Number(width); j++ ...

What is the functionality of the getBlock('meta') method within DocPad?

While transitioning a website from a different site generator to DocPad, I am currently exploring the capabilities of the getBlock('meta') feature. Understanding how to utilize getBlock('scripts') and getBlock('styles') was re ...

bespoke regulation protocol for collection of items

Is there a way to sort an array of objects based on specific rules? Unlike objects, arrays have fixed item order, so how can I rearrange them according to certain criteria? [{name: 'james', name: 'alice', name: 'sam'}] If I w ...

Tips for customizing the IconButton appearance in material-ui

While Material-ui offers a default icon button, I am interested in customizing its design to resemble this: IconButton design needed Could you please advise me on how to make this change? Thank you. ...

Angular is encountering an issue where it is unable to read the value of a JavaScript function, despite the object having a value

I have developed some JavaScript functions that involve reading and writing to a JSON file, with the intention of calling them in an Angular environment (from TypeScript code) using the jsonfile library. Below is the code snippet: function savePatient(pa ...

What is the best way to assess each item in an array and apply the useState() hook based on a specific condition

I am currently working on a simulation for a blackjack hand and have run into an issue with my code. The game follows these steps: users receive two random cards and a total point value, then click 'hit' to draw another random card from the deck. ...

Storing the current date() in JSON format using AngularJS

I am currently working on saving various data, including the current date, in a JSON file stored in LocalStorage. While I have been successful in saving the data, the date is saved in the ISO 8601 format: [{"date":"2014-10-13T17:55:32.953Z"}] This format ...

Tips to prevent redirection in a JavaScript function

When a user clicks on a specific link, the HideN function is triggered. Here's an example: <a href="<?php echo $dn5['link']; ?>" onclick="HideN('<?php echo $dn5['id'];?>','<?php echo $dn5['fro ...

Activate Button upon Textbox/Combobox/RadDatePicker Modification through JavaScript

On my ASP.NET form, I have various input elements including textboxes, dropdowns, date pickers, and update buttons. My goal is to enable the update button whenever a user makes a change in any of these fields. To achieve this, I applied a specific CSS cla ...

JSON does not send information to the specified web address

Attempting to send some data to the following URL: " $(function() { var frm = $(document.myform); var data = "?lm_po_id=154668&authentication=ThisisAuth&description=ThisIsDesc";//JSON.stringify(frm.serializeArray()); ...

Issue with implementing MUI Style Tag in conjunction with styled-components and Typescript

I have created a custom SelectType component using Styled Components, which looks like this: import Select from '@mui/material/Select'; export const SelectType = styled(Select)` width:100%; border:2px solid #eaeaef; border-radius:8px ...

Trying to retrieve JSON data from an API in VueJS and successfully logging the results, but struggling to render the data on the page. (I

Having recently transitioned from React to VueJs, I encountered a problem where fetching data using axios.get returns a successful response in the console.log. However, when trying to iterate through the array with v-for, nothing is rendered. If you have a ...

Challenges with fading images using jQuery

I am currently working on animating a 5 image slideshow by creating a fading effect between the images rather than just switching abruptly. Here is my HTML structure: <div id="slides"> <ul class="pics"> <li><img src="imag ...

Angular.js: Ensure all services are loaded before initializing the application

I am currently developing an application using angular.js and I need to ensure that the result from a specific service is accessible throughout the entire application right from the beginning. How can this be accomplished? The service in question is as f ...

Toggle the visibility of a div based on the id found in JSON data

I am looking to implement a JavaScript snippet in my code that will show or hide a div based on the category ID returned by my JSON data. <div id="community-members-member-content-categories-container"> <div class="commun ...