Search code examples
javascriptstringstring-length

How to work out which variable has the most characters using javascript


How to work out which variable has the most characters.

For example :

var one = "qwert";
var two = "qwertyu"
var three ="qwertyuiop";

How to work out which variable has the most character.

First thing I am doing is counting the number of characters in each string.

var onelength = one.length;
var twolength = two.length;
var threelength = three.length;

The part I am struggling on is javascript to work out which of the above lengths has the most characters.


Solution

  • There's really no way to do this in Javascript (nor indeed in most languages).

    What you're asking for is a kind of reflection. Conceptually, a function nameOfVariable that takes a variable and gives you it's string name in return:

    nameOfVariable(one): 'one'
    

    Not possible.

    The answers above are attempts to work around that. Ultimately in real code this would be structured not as a bag of variables but as an object (which is kinda like a bag of variables, except you can recover the names)

    const strings = {
      one: 'abcde',
      two: 'abcdef',
      three: 'abcd',
    };
      
      
    // Return key in object corresponding to longest string, 
    // or null if object is empty.
    const longest_string = strings => {
      let max = null;
      for (let name in strings) {
        if (max === null || strings[name].length > strings[max].length) {
          max = name;
        }
      }
      return max;
    }
    
    console.log(longest_string(strings));