ES6: Unintuitive array element swapping using destructuring assignment

ES6: Unintuitive array element swapping using destructuring assignment

Found this tricky scenario when trying to sort an array by swapping elements using destructuring assignment.

Found this tricky scenario when trying to sort an array by swapping elements using destructuring assignment.

// try to sort the array by swapping elements
const a = [2, 1];

// does not work // 1. cache values on right side of =, i.e. [1, 2] // 2. a[0] := 1; a is now [1, 1] // 3. a[a[0]-1] = a[1-1] = a[0] := 2; a is now [2, 1] again [a[0], a[a[0]-1]] = [a[a[0]-1], a[0]]; console.log(a); // [2, 1]

// does work // 1. cache values on right side of =, i.e. [2, 1] // 2. a[a[0]-1] = a[2-1] = a[1] := 2; a is now [2, 2] // 3. a[0] := 1; a is now [1, 2] [a[a[0]-1], a[0]] = [a[0], a[a[0]-1]]; console.log(a); // [1, 2]

// seems like the values on the right of the = are cached first, then each assignment is executed in order from left to right. // if latter assignments depend on values of previous assignments, this will cause unintuitive results

Here's a nodejs REPL

javascript node-js

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How to Hire Node.js Developers And How Much Does It Cost?

A Guide to Hire Node.js Developers who can help you create fast and efficient web applications. Also, know how much does it cost to hire Node.js Developers.

Top 7 Most Popular Node.js Frameworks You Should Know

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser. In this post, you'll see top 7 of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Hire Node.JS Developers | Skenix Infotech

We are providing robust Node.JS Development Services with expert Node.js Developers. Get affordable Node.JS Web Development services from Skenix Infotech.

Node.js for Beginners - Learn Node.js from Scratch (Step by Step)

Node.js for Beginners - Learn Node.js from Scratch (Step by Step) - Learn the basics of Node.js. This Node.js tutorial will guide you step by step so that you will learn basics and theory of every part. Learn to use Node.js like a professional. You’ll learn: Basic Of Node, Modules, NPM In Node, Event, Email, Uploading File, Advance Of Node.

Hands on with Node.Js Streams | Examples & Approach

The practical implications of having Streams in Node.js are vast. Nodejs Streams are a great way to handle data chunks and uncomplicate development.