The enigmatic loop traversal

Can you figure out why the name property of the merged object is properly set in the code below, even though the for-loop starts with i = 1?

function merge(root){
  for ( var i = 1; i < arguments.length; i++ ){
    for ( var key in arguments[i] ){
      console.log(i); // returns 1 then 2 (not 0)
      root[key] = arguments[i][key];
    }
  }
  return root;
}

var merged = merge({name: "John"}, {city: "Boston"},{age: 13});
console.log( merged.name ); // "John" ?
console.log( merged.city ); // "Boston" - OK 
console.log( merged.age ); // 13 - OK 

If the loop starts with i = 2, merged.city would be undefined as expected, but surprisingly, merged.name still returns "John".

function merge(root){
  for ( var i = 2; i < arguments.length; i++ ){
    for ( var key in arguments[i] ){
      console.log(i); // returns 2
      root[key] = arguments[i][key];
    }
  }
  return root;
}

var merged = merge({name: "John"}, {city: "Boston"},{age: 13});
console.log( merged.name ); // "John" - ?
console.log( merged.city ); // undefined - OK
console.log( merged.age ); // 13 - OK

Have you thought about how this situation could occur?

Answer №1

When we mention the variable main, we are actually talking about the data structure {age: 25}. This specific entity is what gets referred to as inputs[0]. Consequently, we bypass this and proceed directly with inputs[1] – incorporating all following parameters into it.

Answer №2

It's important to note that in your function, you are passing a parameter and then returning it.

function combine(data) {
  ...
  return data;

When you call the function with:

combine( {title: "Hello"}, ...

The object {title: "Hello"} becomes the data variable which gets merged with other arguments.

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

Communicating data transfer between two Node.js servers through the use of the Node Serial Port technology

How can I send the message "Hello world" from one nodejs server to another using node-serialport? I have confirmed that the radios connecting the two servers are properly connected as they are displaying buffer information after running my current code. ...

Challenges with window opening function while already in fullscreen view

Unsure of what might be causing the issue, but here's the problem... My code to open a new window is as follows: var opts = 'location=0,toolbar=0,menubar=0,scrollbars=0,resizable=0,height=450,width=300,right=350'; window.open('/' ...

Nested Tables in JavaScript: Creating Tables within Tables

Recently, I have been analyzing student data and noticed a recurring structure. While preparing to present information on student performance within the discipline, I also became interested in showcasing a history of new students. It was suggested that hav ...

I encountered a problem while trying to incorporate the solution that prompts another button click event

Interesting topic: JQuery / JavaScript - triggering button click event from another button <input type="submit" name="savebutton" id="uniqueOne" /> <input type="submit" name="savebutton" id="uniqueTwo" /> I have implemented a feature on my si ...

What causes the order of `on` handler calls to be unpredictable in Angular?

Below is the code snippet I have been working on function linkFunc(scope, element, attr){ var clickedElsewhere = false; $document.on('click', function(){ clickedElsewhere = false; console.log('i ...

What is the best way to set the length of an undefined item in an object to 0 in reactjs?

I am facing a challenge keeping track of scores within each article and displaying them accurately. The issue arises when there is a missing "up" or "down" item in the object. Below is the data containing all the votes: const votes = { "1": { "up": ...

Creating a callback function within stored procedures using JavaScript Language Integrated Query in documentDB: A step-by-step guide

According to the documentation, the code snippets below are considered equivalent. However, I have observed that in the first case, I am able to perform operations on multiple documents within the callback function, whereas the map function in the latter s ...

How can you prevent JQuery AJAX from automatically redirecting after a successful form submission?

Encountered an issue with loading http://example.com/signup.ashx: The redirect from 'http://example.com/signup.ashx' to '' was blocked by the CORS policy. This is due to the absence of 'Access-Control-Allow-Origin' header on t ...

Creating a Consistent Look for Italic Font Formatting in Tailwind

In an effort to establish consistent typography on a website being developed by my team, we have devised custom utility classes in Tailwind. One of these classes, small-italicized, also requires the text to be italicized. However, it seems that the fontSiz ...

How can I make the input box TextField in Material UI with React expand to full width when selected?

I am currently customizing a Material UI form where the input box (Text Field) starts off at a width of 200px. My goal is to have the input box expand to 100% width only when it is selected or clicked on. ... <FormGroup sx={{ maxWidth: "200px" ...

Issues encountered with certain Tailwind styles functioning improperly when deployed in a production environment with Next.js

It seems that there are some style issues occurring in the production build hosted on Netlify for a specific component. The problematic component is a wrapper located at ./layout/FormLayout.tsx. Below is the code for this wrapper: const FormLayout: React.F ...

Replace the hyperlink with plain text using JQuery

Is there a way to replace a hyperlink within an li element with different text but without removing the entire list item? <li class="pull-left"> <a href="#" class="js-close-post" data-post-id="1"> Close </a> </li> ...

Implementing AngularJS drag and drop functionality in a custom directive

I am in search of an example that demonstrates similar functionality to the HTML5 File API using Angular-js. While researching directives for Angular 1.0.4, I found outdated examples that heavily rely on DOM manipulation. Here is a snippet of the pure Ja ...

Why isn't my JavaScript Alert displaying a string message?

I'm feeling a bit puzzled and I have a feeling there must be an easy solution, so please lend me a hand. Here's the code snippet that is causing me some confusion: $new = "1"; <script language="javascript"> alert(<?php echo $new; ...

Managing a high volume of HTTP requests within a React-Redux application

Seeking assistance with my react-redux app project. I have a substantial amount of data that has been divided into smaller files, allowing the user to choose a start and end time range. Upon clicking the "Fetch data" button, I create HTTP request promise ...

Can you include the dollar symbol in the currency format?

I currently have this code that formats numbers into currency format, however I would like to include the dollar sign ($) before the numbers. document.getElementById("numbers").onblur = function (){ this.value = parseFloat(this.value.r ...

Exploring the @HostBinding argument in Angular directives

Need help grasping the concept behind the @Hostbinding argument: Snippet of the code: import { Directive, HostBinding } from "@angular/core"; @Directive({ selector: '[appDropdown]' }) export class DropdownDirective { @HostBinding(&apos ...

You have attempted to make an invalid hook call in the react chat app. Hooks can only be called within the body of a function component

Encountering problems like manifest.json:1 Manifest: Line: 1, column: 1, Syntax error. **Important Error Message/User Notification:** react-dom.development.js:20085 The above error occurred in the <WithStyles(ForwardRef(AppBar))> component: Arrange ...

jQuery condition doesn't properly resetting the states of the original checkboxes

Having trouble phrasing the question, apologies! Take a look at this fiddle to see my objective: http://jsfiddle.net/SzQwh/. Essentially, when a user checks checkboxes, they should add up to 45 and the remaining checkboxes should then be disabled. The pr ...

What is the best way to iterate through a puppeteer selector's response in a loop?

So, by using page.evaluate I can accomplish the following: await page.evaluate(function() { var links = document.querySelectorAll('a'); for (var i = 0; i < links.length; i++) console.log(links[i].href); }); However, I am interested in a ...