Breaking Down Arrays

The variable b is coming up as undefined and it's being assigned 'a' as the default value when there is no value present. However, when assigned the value of 'c', an error is thrown. Can anyone provide a clear explanation of what is going on here? Is this potentially a bug?

const [a, b = c, c] = [1, , 3]

Answer №1

When destructuring into variables, the evaluation occurs from left to right following the order of the array or property list.

Variables declared with const are not accessible until after the line that initializes them has been executed.

The code provided is essentially:

const arr = [1, , 3];
const a = arr[0];
const b = arr[1] === undefined ? arr[1] : c;
const c = arr[2];

This reveals the issue you're encountering; attempting to access c before it's defined. This behavior is expected and not a bug.

To achieve the desired output, extract the value of c first so that you can use it as a default value for b.

const arr = [1, , 3];
const c = arr[2];
const [a, b = c] = arr;
console.log(a, b, c);

It is advisable to avoid using sparse arrays whenever possible, as they can lead to confusion and unexpected behavior.

Answer №2

There is a clever trick to achieve this in just one line by destructuring the keys of the array. You can assign the 2nd index before the 1st and use that as the default value. However, it's important to note that this method is more for academic purposes and not recommended for actual code implementation.

const { 0: a, 2: c, 1: b = c } = [1, , 3]

console.log(a, b, c)

Answer №3

const [a, b = c, c] = [1, , 3]

The scenario depicted above can be viewed as

const a = [1, , 3][0];
const b = [1, , 3][1] || c; // Reference Error
const c = [1, , 3][2];

console.log(a, b, c);

In contrast, the following statement

const [a, b = c, c] = [1, , 3]

Can be envisioned as

const a = [1, , 3][0];
const b = [1, , 3][1] || a;
const c = [1, , 3][2];

console.log(a, b, c); //1 1 3

Thus, in the initial instance c is referenced before being initialized leading to an error, while in the latter example, a is already defined when accessed.

If you were to perform the same operation using var, you would not encounter an error initially due to hoisting.

var [a, b = c, c] = [1, , 3]
console.log(a, b, c) //1 undefined 3

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

Having trouble loading data.json file in React.js and jQuery intergration

Having a background in mobile development, I am relatively new to web development so please excuse any amateur questions. Currently, I am working on a react.js project using create-react-app (which utilizes Babel). I am following a tutorial that requires ...

Troubleshooting: ReactJS image change on mouse over not functioning

My objective is to develop a stateless image button component that changes images upon hovering, which can be easily reused in various other instances. However, I'm currently facing an issue where I'm unable to set the "hover" image when the onM ...

Switching the ng-class in Angular with a click event

I'm having trouble modifying a class I've created based on a value from JSON, and then changing it when the user clicks on it. Here's my code in the controller: $scope.like = function(){ if ($scope.class === "ion-ios-heart-outline") ...

Unable to assign an argument to a function in commander.js

Having some trouble passing an option to a custom command in commander.js... program .command('init [options]') .description('scaffold the project') .option('-b, --build', 'add "build" folder with subfolders') . ...

Is it possible to safeguard undisclosed data in browser console?

Can JavaScript be employed to prevent users from editing hidden fields through the browser console? ...

Display a Bootstrap 5 Modal in a React component based on specified conditions

I'm currently leveraging Bootstrap 5.13 in my react project. I'm looking to implement a Modal window that will be displayed upon form submission, once the backend confirms successful data saving. To achieve this, I've created a separate com ...

What is the best way to incorporate a loop into a React return statement?

After learning React, I decided to develop the Tic-tac-toe game following the official documentation. There were extra tasks listed below the "Tutorial" section, and one of them was: "Rewrite the Board component to use two loops to generate the squares in ...

Is it possible to arrange a string array in Java as they are inputted without relying on the Array or Collection classes?

My task requires taking the number of strings to be sorted as input, and then sorting them in ascending order as they are entered. The initial part was smooth sailing, but I'm stuck on how to implement the sorting (the compareto method is recommended ...

Achieving successful implementation of SSAO shader on SkinnedMesh models

Trying to implement the SSAO post-processing shader with the most recent version (r77) of three.js has been a challenge for me. I have been utilizing the EffectComposer, with the code completely replicated from the example page provided here: The specific ...

Adding a file attachment and preview feature within a text area: a step-by-step guide

I have been working on a chat box that includes emojis and a file attachment button. While the emojis are functioning correctly, I am experiencing difficulty with the file attachment preview not showing in the text area. Are there any suggestions or plugin ...

Enhancing security with Mongoose's bcrypt for asynchronous password setting and saving

I've defined a mongoose schema that includes a method to set a password using bcrypt: UserSchema.methods.setPassword = function (password) { bcrypt.hash(password, saltRounds).then(function (hash) { this.hash = hash; }); }; When creating a us ...

What is the method for establishing a callback for call status using the Twilio Voice JavaScript SDK?

Currently, I am in the process of utilizing the Twilio Programmable Voice JavaScript SDK to initiate an outbound call with a statusCallback and statusCallbackEvent in order to update another system once the call is finished. Below is the snippet of my cod ...

Ajax script failing to run

I'm currently developing a new social networking site that includes a feature for creating groups. Most of my code is functioning flawlessly, except for this small section that handles approving or declining pending members. The following PHP code sni ...

Having Multiple File Inputs [type=file] in one webpage

Is it possible to have two separate inputs for uploading images, each setting a different background image in a div? The second file input is: <input type='file' id='getval' name="logo" /> I want this file to be set as the back ...

Reordering an array based on the reverse sort order of another array in PHP

I am facing an issue with sorting arrays in PHP. I have an array containing year dates sorted using the rsort function to display them from highest to lowest. The variables $variable1, $variable2, $variable3, etc., are predefined based on data collected fr ...

What are the steps to installing and utilizing the Chart.js package on your local machine?

I thought installing chart.js on my Raspberry Pi would be a simple task, but I seem to be struggling with it. Due to the nature of my project, I need to have it installed locally rather than relying on an online version. Following the usual steps, I navig ...

insert data into modal's interface

I'm encountering an issue with my code, where the modal is not displaying the values inside the brackets as if they were not bound correctly. Everything else in the ng-repeat seems to be working fine, but for some reason the values are not being displ ...

Tips for achieving a dimmed content effect on Semantic UI React within a NextJS project

I'm currently facing an issue with incorporating dimmed content into the Semantic UI React sidebar on Next.js... Here is the example of dimmed content on Semantic UI: https://i.sstatic.net/5dOGK.png This is the layout code I am using: import React, ...

Setting radio button values according to dropdown selection - a beginner's guide

I am trying to dynamically set the default values of radio buttons based on the selection made in a drop-down menu. For example, if option A or B is chosen, I want the radio button value to default to "Summary", and if option C is chosen, I want the value ...

Is there a way to retrieve the timezone based on a province or state in TypeScript on the frontend?

I've been working on an angular app that allows users to select a country and state/province. My current challenge is determining the timezone based on the selected state/province, with a focus on Canada and the US for now (expanding to other countrie ...