Breaking down an array to create an object

When attempting array destructuring in JavaScript, I encountered some perplexing behavior.

Below is the code snippet causing the issue:

 let result = {
            start: {},
            end: {},
        };
[result.start.hour, result.start.minute] = [7, 20]
[result.end.hour, result.end.minute] = [17, 30]
console.log(result)

The resulting output is:

{ start: { hour: 17, minute: 30 }, end: {} }

Strangely, [17, 30] were assigned to res.start instead of res.end.

Interestingly, if I insert a console.log statement like so:

 let result = {
            start: {},
            end: {},
        };
[result.start.hour, result.start.minute] = [7, 20]
console.log(JSON.stringify(result));
[result.end.hour, result.end.minute] = [17, 30]
console.log(result)

Then it works as expected. Now, results.end receives the correct values.

I have searched and reviewed the MDN documentation on destructuring but have not found an explanation for this behavior. Any help would be greatly appreciated. Thank you in advance.

Answer №1

Check out this revised solution:

let result = {
  startingTime: {},
  endingTime: {}
};
[result.startingTime.hour, result.startingTime.minute] = [7, 20]; // Be sure to include semicolons.
[result.endingTime.hour, result.endingTime.minute] = [17, 30];
console.log(result);

I took your original code and reformatted it in VS Code using 'Alt + Shift + F'. This resulted in the corrected version shown below, highlighting a clear discrepancy:

let res = {
  start: {},
  end: {}
};
[res.start.hour, res.start.minute] = [7, 20][(res.end.hour, res.end.minute)] = [
  17,
  30
];
console.log(res);

The moral of the story is that semicolons can make a difference in JavaScript programming.

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

Incorporate server-side tags into client-side HTML and JavaScript scripts without the use of template engines

My goal is to carry out the following operation within client-side JavaScript from a file served using Node and Express: var rootURL = <%= "someurlfromserverconfig" %>; I am solely hosting a web directory from my Node app without any template engin ...

Tips for Maintaining Table Headers in Place While Scrolling Through a Table

Check out my jsfiddle: http://jsfiddle.net/7vv9e/2/ In the fiddle, click on the "Add Question" button multiple times until a scroll bar appears next to the table. I am looking to keep the header fixed while scrolling. How can this be achieved? Below is ...

Updating certain fields in AngularJS with fresh data

I am facing a challenge with the following code snippet: <div ng-controller="postsController"> <div id = "post_id_{{post.postid}}" class = "post" ng-repeat="post in posts"> ...... <div class="comments"> < ...

Utilizing a URL to dynamically update the content within an I-Frame

One day, I made the questionable decision to use i-frames to load pages on my website in order to keep a sidebar on the main page without having to constantly make changes. In hindsight, I should have done the opposite and put the sidebar in the i-frame. N ...

Strategies for resolving duplicate jQuery code in my project

Trying to simplify my jQuery code that handles video selection and playback functionality. Users can click on a thumbnail or button to play a specific video, with the title of the video changing accordingly. Despite achieving the desired outcome, the cur ...

Using JSON data to populate a select menu in AngularJS using the ng-options directive

UPDATE: I have successfully resolved my issue. Thanks for the assistance, everyone. I am working with an array of JSON objects that are structured like so: [{"id":"id1", "text":"text1"}, {"id":"id2", "text":"text2"},....] My goal is to populate an Angul ...

RequireJS - Enabling the loading of multiple module instances

I am working on a custom RequireJS plugin that needs to create a new object instance every time it is called. For illustration purposes, consider the following: define("loader", { load: function(name, req, onload, config) { var instance = GlobalGet ...

Oops! An error occurred while trying to find the _mongodb._tcp.blog-cluster-0hb5z.mongodb.net. Please check your query settings and try again

My free Mongo Atlas cluster suddenly stopped connecting, even though everything was working fine before. Strangely, I can see that data has been collected on the MongoDB website. It's puzzling why this issue occurred and now my entire site won't ...

JavaScript throws an error when attempting to access an object's methods and attributes

Within my Angular.js module, I have defined an object like this: $scope.Stack = function () { this.top = null; this.size = 0; }; However, when I try to use the push method of this object, I encounter an error stating undefined: ...

Driving a Car using THREE.js on the Highway

I'm currently developing a car game using THREE.js. I've encountered an issue where I have created a road using Plane geometry and placed the car on it. Now, I have also made a terrain but am unsure of how to link the car to the road so that it m ...

Inheritance of nested directives in Angular.js

Click here for a live example I'm trying to understand how 00B can be contained within 00A. Here is the code snippet: <div directive-one="['foo', 'bar']"> <directive-two /> </div> In this code, the directi ...

What is the most efficient way to halt the pipe if the value of an HTML input element remains unchanged using RxJS?

I'm currently incorporating RxJS into my Angular 9 project. My goal is to bind a keyup event to an input field and trigger an HTTP request whenever the user types a new value. Here's the code snippet I have: fromEvent(this.inputBox.nativeElemen ...

Implementing Dynamic Checkbox Selection using JavaScript

Could someone please assist me with this coding challenge? HTML <div id="toggle"> <ul> <li class="active"><input type="checkbox" id="test" value="2014" name="test" checked/> 2014</li> <div style="display:block;" id ...

What is the best way to utilize "require" dynamically in JavaScript?

Within the "sample.js" file, there is a JavaScript function structured as follows: var mapDict = { '100': 'test_100.js', '200': 'test_200_API.js', '300': 'test_300_API.js' } function mapAPI() { ...

Is there a way for TypeScript to recognize that the potential data types in a union type align with the valid prototypes for a function? Any solutions available?

There seems to be an issue with this (playground link) code snippet: type ReplaceAll2ndArgType = string | ((substring: string, ...args: unknown[]) => string) export async function renderHTMLTemplate( args: Record<string, ReplaceAll2ndArgType> ...

Customizing script loading based on the AngularJS template

I am currently working on developing a Single Page Web Application that will require user/password protection. Specific modules will be loaded based on the user's profile to restrict access in a role-based manner. For loading templates corresponding ...

What is the method for configuring input in a session without having to submit it?

I am encountering a major issue with my PHP MVC pattern website. On one page, I did not implement a "POST" submit method and now I am facing difficulties in passing quantity to the products/order page. If I use a Submit button, the next page does not funct ...

Testing a Component Function in ReactJS: A Step-by-Step Guide

Testing methods in a Meteor application using mocha/chai can be done like this: describe('postMessage', () => { it('should add message', (done) => { // EXECUTE const messageId = postMessage.call({ articleId: 123, conten ...

What is the process for getting non-event javascript instructions to function properly once a DOM element has been added

After inserting DOM elements (such as an AJAX response), event-delegation is necessary to ensure that events work properly. But what about basic JavaScript instructions? All instructions are organized by affected PHP page to simplify code updates and avoi ...

Using PHP to set an array value as a closure for a JavaScript function: Is it possible?

Currently, I am working on creating a custom renderer for the handsontable plugin in my PHP project. To achieve this, I have prepared a set of parameters as a PHP array: $options = [ 'data' => $orders, 'columns' => [ ...