The enchanting world of permutation magic in Javascript

Currently delving into algorithms to grasp permutations in javascript, I stumbled upon the following one that left me intrigued:

var permArr = [], usedChars = [];
function permute(input) {
  var i, ch, chars = input.split('');
  for (i = 0; i < chars.length; i++) {
    ch = chars.splice(i, 1);
    usedChars.push(ch);
    if (chars.length == 0) permArr[permArr.length] = usedChars.join('');
    permute(chars.join(""));
    chars.splice(i, 0, ch);
    usedChars.pop();
  }
  return permArr
}

For reference, I came across this algorithm on:

While it's evident that this algorithm functions as intended, there is a specific line that poses confusion and eludes clarity:

var i, ch, chars = input.split("");

Upon logging 'i' or 'ch' either before or after in the code, both variables consistently yield undefined results. Interestingly, removing these variables significantly impairs the algorithm's functionality.

I seek elucidation regarding this particular line and its operative mechanism. Any insights would be greatly appreciated!

Answer №1

No Sorcery Involved

let index, character, characters = input.split('');

Defines the variables index, character, and characters, assigning to characters the result of input.split('').

In simple terms, it's equivalent to:

let index; // undefined
let character; // undefined
let characters = input.split(''); // Array of strings

This practice is usually done so that the variables can be accessed throughout loop iterations (to access previous values).

However...

index is just used as the loop variable and could be declared within the loop like this:

for (let index = 0; index < characters.length; index++) {

character could exist inside the loop since it gets reassigned in the initial statement anyway.

  for (let index = 0; index < characters.length; index++) {
      let character = characters.splice(index, 1);

This can make the example slightly confusing (some might say it's not well-written).

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

What are the advantages of passing state from child components up in React?

I have been attempting to update the state within the App component from a child component, but I am concerned that this approach may cause issues later in my application. I've experimented with passing down the setFunction to the child components an ...

Experimenting with React components that showcase various components in a loop

Currently, I am working on a react-native app where I have a simple component that receives an array and displays it as markers on a map using react-native-maps. My goal is to write tests for this component. The test should verify that there is a marker p ...

Retrieve an HTML document from a specified URL using JavaScript AJAX methods

var $ = require('jquery'); $.ajax({ type:"GET", dataType: 'html', url: 'http://www.google.com/', success: function(res){ console.log(res); } }); The error displaying in the console is: XMLHttpRequest cannot lo ...

React has reached the maximum update depth limit

In my current project, I am developing a react application that involves a user inputting a search term and receiving an array of JSON data from the backend. On the results page, I have been working on implementing faceted search, which includes several fi ...

Using an if statement within a map function in a React component

I am facing a challenge with using an if statement inside a map function without changing the return value. Here is my code snippet: this.example = this.state.data.map((item) => { return( <div> {if(1 + 1 == 2){ dat ...

Node Js Error: morgan causing TypeError - app.use is not a valid function

Just diving into the world of node js and decided to follow a tutorial on scotch.io. I added morgan for logging requests, but when I hit run, I encountered an error saying TypeError: app.use is not a function. Here's the snippet from my app.js; const ...

Looping through an array in JavaScript - able to see content in console.log() but encountering issues with iteration using $.each()

Similar Question: How can I retrieve a value from an AJAX call? Using jQuery for asynchronous return value assignment I've encountered an issue while attempting to loop through an array in JavaScript. The problem arises when trying to iterate ...

Adding a Timepicker to a Datepicker on a jsp webpage with javascript

I am working on a JSP page that includes a date picker. I want to enhance this datepicker by adding a start time and end time within the calendar itself. How can I achieve this? Additionally, I need to implement validation ensuring that the start time is a ...

Accessing the API to retrieve an image when the 'a' tag is clicked

Currently, I am accessing the API to retrieve an image of a specific cat breed. When the API is called for the image, you receive a JSON object with the following URL: URL: "" I aim to display this image upon clicking on that specific breed. However, I a ...

What is the best way to retrieve a {collection object} from a JavaScript map?

My application utilizes a third-party library that returns the map in the following format: public sids: Map<SocketId, Set<Room>> = new Map(); When I try to access it using the code below: io.of("/").adapter.sids.forEach(function(va ...

The shadow cast by the point light in Three.js seems to be misplaced

Take a look at this JS fiddle to view my code. I'm encountering an issue where there is a gap between the object and its shadow. Interestingly, this gap does not occur with spot lights. Any suggestions on how I can resolve this? Highlighted code snip ...

Issue with long text in a resizable table using jQuery tablesorter 2.31.1

My issue is that when I try to resize the columns in tablesorter, they snap back into place. The column width set with resizable_widths does not apply correctly until a column is manually resized. Despite setting the width of all cells to 120px, any cells ...

Parsing JSON data results in a string output

After realizing that my initial post was not clear enough, here are more details. Jade: meta(name='revObj', content=(JSON.stringify('#{rev[1]}'))) The resulting HTML from Jade: <meta name="revObj" content=""{ companyAddress: &apo ...

Creating JavaScript objects through function calls

let getBoxWidth = function() { this.width=2; }; alert(getBoxWidth.width); Hello there! Can you explain why the output is undefined in this scenario? ...

Ways to insert text at the start and end of JSON data in order to convert it into JSONP format

Currently, I am working on a project where I need to add a prefix "bio(" and a suffix ")" to my JSON data in order to make it callable as JSONP manually. I have around 200 files that require this modification, which is why I am looking for a programmatic ...

Display a dynamic list of data fetched from an axios Get request in a React MUI dropdown menu

import { useEffect, useState } from "react"; import Box from "@mui/material/Box"; import FormControl from "@mui/material/FormControl"; import InputLabel from "@mui/material/InputLabel"; import MenuItem from "@m ...

The combination of Inline CSS and Bootstrap classes does not seem to be functioning properly

I'm new to web design and currently working on a website project. My concept involves hiding the #login-box when the user clicks on the login button, and displaying another element (.dashboard) in its place. Initially, I set the .dashboard class to ha ...

Trigger a click event on a file input in Ionic 3 Android by using the Fire method

In my Ionic 3 project, I've enabled users to upload multiple images through the application. I am seeking a way to trigger the file browser to open when a Button is clicked, as shown below. Here is the snippet of code I am currently working with: hom ...

Is there a way to store my collection data in a variable and access it externally from the file?

Topic of Interest : Working with Discord.js I am seeking advice on how to save collector data in a variable and access it outside of the file, for example in index.js. I aim to create a setup command that prompts users with questions when they type -setup ...

Exploring the world of shapes and angles in three.js

I'm attempting to recreate a scene similar to this one, where the shapes have an outline: Unfortunately, neither of these two options are working: const material = new THREE.MeshNormalMaterial(); const material = new THREE.MeshBasicMaterial({ color: ...