Javascript - Strings

| Comments

Sorting Strings

Javascript has a native method sort that allows sorting arrays. Doing a simple array.sort() each value will be treated as a string and sorted alphabetically. Also you can create your own custom sorting function passing it how argument.

1
2
['Shanghai', 'New York', 'Mumbai', 'Buenos Aires'].sort();
// ["Buenos Aires", "Mumbai", "New York", "Shanghai"]

But when you try order an array of non ASCII characters like this ['é', 'a', 'ú', 'c'], you will obtain an strange result ['c', 'e', 'á', 'ú']. That happens because sort works only with english language.

See the next example:

1
2
3
4
5
6
7
// Spanish
['único','árbol', 'cosas', 'fútbol'].sort();
// ["cosas", "fútbol", "árbol", "único"] // bad order

// German
['Woche', 'wöchentlich', 'wäre', 'Wann'].sort();
// ["Wann", "Woche", "wäre", "wöchentlich"] // bad order

Fortunately exists two ways to avoid this mistake localeCompare and Intl.Collator provided by ECMAScript Internationalization API.

Both methods have his own custom parameters in order to configure it for work adequately.

Using localeCompare()

1
2
3
4
5
6
7
8
9
['único','árbol', 'cosas', 'fútbol'].sort(function (a, b) {
  return a.localeCompare(b);
});
// ["árbol", "cosas", "fútbol", "único"]

['Woche', 'wöchentlich', 'wäre', 'Wann'].sort(function (a, b) {
  return a.localeCompare(b);
});
// ["Wann", "wäre", "Woche", "wöchentlich"]

Using Intl.Collator()

1
2
3
4
5
['único','árbol', 'cosas', 'fútbol'].sort(Intl.Collator().compare);
// ["árbol", "cosas", "fútbol", "único"]

['Woche', 'wöchentlich', 'wäre', 'Wann'].sort(Intl.Collator().compare);
// ["Wann", "wäre", "Woche", "wöchentlich"]
  • For each method you can customize the location.
  • According Firefox Intl.Collator it’s more fast for compare large numbers of strings.

So remember when you are working with arrays of string in another language that not is english, use this methods to avoid unexpected errors.

ES6 Template Strings

As of ES6, JS now has template strings as an alternative to the classic end quotes strings.

Normal string

1
2
3
4
5
var firstName = 'John';
var middleName = 'Paul';
var lastName = 'Jones';
console.log('My name is ' + firstName + ' ' + middleName + ' ' + lastName);
// My name is John Paul Jones

Template String

1
2
3
4
5
var firstName = 'John';
var middleName = 'Paul';
var lastName = 'Jones';
console.log(`My name is ${firstName} ${middleName} ${lastName}`);
// My name is John Paul Jones

You can do Multi-line strings without \n and simple logic (ie 2+3) inside ${} in Template String.

You are also able to to modify the output of template strings using a function; they are called Tagged template strings for example usages of tagged template strings.

You may also want to read to understand template strings more

Javascript - Better Nested Conditionals With Objects

| Comments

How can we improve and make more efficient nested if statement on javascript.

1
2
3
4
5
6
7
8
9
10
11
12
13
if (color) {
  if (color === 'black') {
    printBlackBackground();
  } else if (color === 'red') {
    printRedBackground();
  } else if (color === 'blue') {
    printBlueBackground();
  } else if (color === 'green') {
    printGreenBackground();
  } else {
    printYellowBackground();
  }
}

One way to improve the nested if statement would be using the switch statement. Although it is less verbose and is more ordered, It’s not recommended to use it because it’s so difficult to debug errors, here’s why

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
switch(color) {
  case 'black':
    printBlackBackground();
    break;
  case 'red':
    printRedBackground();
    break;
  case 'blue':
    printBlueBackground();
    break;
  case 'green':
    printGreenBackground();
    break;
  default:
    printYellowBackground();
}

But what if we have a conditional with several checks in each statement? In this case, if we like to do less verbose and more ordered, we can use the conditional switch. If we pass true as parameter to the switch statement, It allows us to put a conditional in each case.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
switch(true) {
  case (typeof color === 'string' && color === 'black'):
    printBlackBackground();
    break;
  case (typeof color === 'string' && color === 'red'):
    printRedBackground();
    break;
  case (typeof color === 'string' && color === 'blue'):
    printBlueBackground();
    break;
  case (typeof color === 'string' && color === 'green'):
    printGreenBackground();
    break;
  case (typeof color === 'string' && color === 'yellow'):
    printYellowBackground();
    break;
}

But we must always avoid having several checks in every condition, avoiding use of switch as far as possible and take into account that the most efficient way to do this is through an object

1
2
3
4
5
6
7
8
9
10
11
var colorObj = {
  'black': printBlackBackground,
  'red': printRedBackground,
  'blue': printBlueBackground,
  'green': printGreenBackground,
  'yellow': printYellowBackground
};

if (color && colorObj.hasOwnProperty(color)) {
  colorObj[color]();
}

Another best example why to use objects for conditionals - link