Categories
JavaScript JavaScript Basics

Comparing Non-English Strings with JavaScript Collators

With the combination of the double equal or triple equal operator with string methods, we can compare strings easily in a case-sensitive or case insensitive manner. However, this doesn’t take into account the characters that are in non-English strings like French or Italian. These languages have alphabets that may contain accents, something that isn’t recognized in normal string comparisons.

To handle this scenario, we can use the Intl.Collator object to compare strings with accents or for different locales. The Intl.Collator object is a constructor for collators, which are objects that let us compare characters in a language-sensitive way. With Collators, we can compare the order of single characters according to the language that is specified.

Basic Collator Usage for String Equality Comparison

To use a collator, we can construct a Collator object and then use its compare method. The compare method does a comparison of the alphabetical order of the entire string based on the locale. For example, if we want to compare two strings in the German using its alphabet’s order, we can write the following code:

const collator = new Intl.Collator('de');  
const order = collator.compare('Ü', 'ß');  
console.log(order);

We created the Collator object by writing new Intl.Collator(‘de’) to specify that we are comparing strings in the German alphabet. Then we use the created compare method, which takes two parameters as the two strings that you want to compare in string form.

Then a number is returned from the compare function. 1 is returned if the string in the first parameter comes after the second one alphabetically, 0 if both strings are the same, and -1 is returned if the string in the first parameter comes before the second string alphabetically.

So if we flip the order of the strings like in the code below:

const collator = new Intl.Collator('de');  
const order = collator.compare('ß', 'Ü');  
console.log(order);

Then the console.log outputs -1.

If they’re the same, like in the following code:

const collator = new Intl.Collator('de');  
const order = collator.compare('ß', 'ß');  
console.log(order);

Then we get 0 returned for order.

To summarize: If the strings are equal, the function returns 0. If they are not equal the function returns either 1 or -1 which also indicates the alphabetical order of the strings.

Advanced Usage

The Collator is useful because we can put it in the Array.sort method as a callback function to sort multiple strings in the array. For example, if we have multiple German strings in an array, like in the code below:

const collator = new Intl.Collator('de');  
const sortedLetters = ['Z', 'Ä', 'Ö', 'Ü', 'ß'].sort(collator.compare);  
console.log(sortedLetters);

Then we get [“Ä”, “Ö”, “ß”, “Ü”, “Z”].

The constructor takes a number of options that take into account the features of the alphabets of different languages. As we can see above, the first parameter in the constructor is the locale, which is BCP-47 language tag, or an array of such tags. This is an optional parameter. An abridged list of BCP-47 language tags include:

  • ar — Arabic
  • bg — Bulgarian
  • ca — Catalan
  • zh-Hans — Chinese, Han (Simplified variant)
  • cs — Czech
  • da — Danish
  • de — German
  • el — Modern Greek (1453 and later)
  • en — English
  • es — Spanish
  • fi — Finnish
  • fr — French
  • he — Hebrew
  • hu — Hungarian
  • is — Icelandic
  • it — Italian
  • ja — Japanese
  • ko — Korean
  • nl — Dutch
  • no — Norwegian
  • pl — Polish
  • pt — Portuguese
  • rm — Romansh
  • ro — Romanian
  • ru — Russian
  • hr — Croatian
  • sk — Slovak
  • sq — Albanian
  • sv — Swedish
  • th — Thai
  • tr — Turkish
  • ur — Urdu
  • id — Indonesian
  • uk — Ukrainian
  • be — Belarusian
  • sl — Slovenian
  • et — Estonian
  • lv — Latvian
  • lt — Lithuanian
  • tg — Tajik
  • fa — Persian
  • vi — Vietnamese
  • hy — Armenian
  • az — Azerbaijani
  • eu — Basque
  • hsb — Upper Sorbian
  • mk — Macedonian
  • tn — Tswana
  • xh — Xhosa
  • zu — Zulu
  • af — Afrikaans
  • ka — Georgian
  • fo — Faroese
  • hi — Hindi
  • mt — Maltese
  • se — Northern Sami
  • ga — Irish
  • ms — Malay (macrolanguage)
  • kk — Kazakh
  • ky — Kirghiz
  • sw — Swahili (macrolanguage)
  • tk — Turkmen
  • uz — Uzbek
  • tt — Tatar
  • bn — Bengali
  • pa — Panjabi
  • gu — Gujarati
  • or — Oriya
  • ta — Tamil
  • te — Telugu
  • kn — Kannada
  • ml — Malayalam
  • as — Assamese
  • mr — Marathi
  • sa — Sanskrit
  • mn — Mongolian
  • bo — Tibetan
  • cy — Welsh
  • km — Central Khmer
  • lo — Lao
  • gl — Galician
  • kok — Konkani (macrolanguage)
  • syr — Syriac
  • si — Sinhala
  • iu — Inuktitut
  • am — Amharic
  • tzm — Central Atlas Tamazight
  • ne — Nepali
  • fy — Western Frisian
  • ps — Pushto
  • fil — Filipino
  • dv — Dhivehi
  • ha — Hausa
  • yo — Yoruba
  • quz — Cusco Quechua
  • nso — Pedi
  • ba — Bashkir
  • lb — Luxembourgish
  • kl — Kalaallisut
  • ig — Igbo
  • ii — Sichuan Yi
  • arn — Mapudungun
  • moh — Mohawk
  • br — Breton
  • ug — Uighur
  • mi — Maori
  • oc — Occitan (post 1500)
  • co — Corsican
  • gsw — Swiss German
  • sah — Yakut
  • qut — Guatemala
  • rw — Kinyarwanda
  • wo — Wolof
  • prs — Dari
  • gd — Scottish Gaelic

For example, de is for German or fr-ca for Canadian French. So, we can sort Canadian French strings by running the following code:

const collator = new Intl.Collator('fr-ca');  
const sortedLetters = ['ç', 'à', 'c'].sort(collator.compare);  
console.log(sortedLetters);

The constructor to Collator can also take an array of strings for multiple locale comparison — new Intl.Collator([/* local strings */]). The array argument allows us to sort strings from multiple locales. For example, we can sort both Canadian French alphabet and the German alphabet at the same time:

const collator = new Intl.Collator(['fr-ca', 'de']);  
const sortedLetters = [  
  'Ü', 'ß', 'ç', 'à', 'c'  
].sort(collator.compare);
console.log(sortedLetters);

Then we get [“à”, “c”, “ç”, “ß”, “Ü”] from the console.log statement.

Additional Options

Unicode extension keys which include "big5han", "dict", "direct", "ducet", "gb2312", "phonebk", "phonetic", "pinyin", "reformed", "searchjl", "stroke", "trad", "unihan" are also allowed in our locale strings. They specify the collations that we want to compare strings with. However, when there are fields in the options in the second argument that overlaps with this, then the options in the argument overrides the Unicode extension keys specified in the first argument.

Numerical collations can be specified by adding kn to your locale string in your first argument. For example, if we want to compare numerical strings, then we can write:

const collator = new Intl.Collator(['en-u-kn-true']);  
const sortedNums = ['10', '2'].sort(collator.compare);  
console.log(sortedNums);

Then we get [“2”, “10”] since we specified kn in the locale string in the constructor which makes the collator compare numbers.

Also, we can specify whether upper or lower case letters should be sorted first with the kf extension key. The possible options are upper, lower, or false. false means that the locale’s default will be the option. This option can be set in the locale string by adding as a Unicode extension key, and if both are provided, then the option property will take precedence. For example, to make uppercase letters have precedence over lowercase letters, we can write:

const collator = new Intl.Collator('en-ca-u-kf-upper');  
const sorted = ['Able', 'able'].sort(collator.compare);  
console.log(sorted);

This sorts the same word with upper case letters first. When we run console.log, we get [“Able”, “able”] since we have an uppercase ‘A’ in ‘Able’, and a lowercase ‘a’ for ‘able’. On the other hand, if we instead pass in en-ca-u-kf-lower in the constructor like in the code below:

const collator = new Intl.Collator('en-ca-u-kf-lower');  
const sorted = ['Able', 'able'].sort(collator.compare);  
console.log(sorted);

Then after console.log we get [“able”, “Able”] because kf-lower means that we sort the same word with lowercase letters before the ones with uppercase letters.

The second argument of the constructor takes an object that can have multiple properties. The properties that the object accepts are localeMatcher, usage, sensitivity, ignorePunctuation, numeric, and caseFirst. numeric is the same as the kn option in the Unicode extension key in the locale string, and caseFirst is the same as the kf option in the Unicode extension key in the locale string. The localeMatcher option specifies the locale matching algorithm to use. The possible values are lookup and best fit. The lookup algorithm searches for the locale until it finds the one that fits the character set of the strings that are being compared. best fit finds the locale that is at least but possibly more suited that the lookup algorithm.

The usage option specifies whether the Collator is used for sorting or searching for strings. The default option is sort.

The sensitivity option specifies the way that the strings are compared. The possible options are base, accent, case, and variant.

base compares the base of the letter, ignoring the accent. For example a is not the same as b, but a is the same as á, a is the same as Ä.

accent specifies that a string is only different if there is a base letter or their accents are unequal then they’re unequal, ignoring case. So a isn’t the same as b, but a is the same as A. a is not the same as á.

The case option specifies that strings that are different in their base letters or case are considered unequal, so a wouldn’t be the same as A and a wouldn’t be the same as c, but a is the same as á.

variant means that strings that are different in the base letter, accent, other marks, or case are considered unequal. For example a wouldn’t be the same as A and a wouldn’t be the same as c. But also a wouldn’t be the same as á.

The ignorePunctuation specifies whether punctuation should be ignored when sorting strings. It’s a boolean property and the default value is false.

We can use the Collator constructor with the second argument in the following way:

const collator = new Intl.Collator('en-ca', {  
  ignorePunctuation: false,  
  sensitivity: "base",  
  usage: 'sort'  
});  
console.log(collator.compare('Able', 'able'));

In the code above, we sort by checking for punctuation and only consider letters different if the base letter is different, and we keep the default that upper case letters are sorted first, so we get [‘Able’, ‘able’] in the console.log.

We can search for strings as follows:

const arr = ["ä", "ad", "af", "a"];  
const stringToSearchFor = "af";
const collator = new Intl.Collator("fr", {  
  usage: "search"  
});  
const matches = arr.filter((str) => collator.compare(str, stringToSearchFor) === 0);  
console.log(matches);

We set the usage option to search to use the Collator to search for strings and when the compare method returns 0, then we know that we have the same string. So we get [“af”] logged when we run console.log(matches).

We can adjust the options for comparing letter, so if we have:

const arr = ["ä", "ad", "ef", "éf", "a"];  
const stringToSearchFor = "ef";
const collator = new Intl.Collator("fr", {  
  sensitivity: 'base',  
  usage: "search"  
});
const matches = arr.filter((str) => collator.compare(str, stringToSearchFor) === 0);
console.log(matches);

Then we get [“ef”, “éf”] in our console.log because we specified sensitivity as base which means that we consider the letters with the same base accent as the same.

Also, we can specify the numeric option to sort numbers. For example, if we have:

const collator = new Intl.Collator(['en-u-kn-false'], {  
  numeric: true  
});  
const sortedNums = ['10', '2'].sort(collator.compare);  
console.log(sortedNums);

Then we get [“2”, “10”] because the numeric property in the object in the second argument overrides the kn-false in the first argument.

Conclusion

JavaScript offers a lot of string comparison options for comparing strings that aren’t in English. The Collator constructor in Intl provides many options to let us search for or sort strings in ways that can’t be done with normal comparison operators like double or triple equals. It lets us order numbers, and consider cases, accents, punctuation, or the combination of those features in each character to compare strings. Also, it accepts locale strings with key extensions for comparison.

All of these options together make JavaScript’s Collator constructor a great choice for comparing international strings.

Categories
JavaScript Basics

The Complete Guide to Using Arrays in JavaScript

Arrays are lists of objects that can be manipulated in various ways. Each entry can be accessed by their own index. Arrays can be combined in various ways and they can be also be nested in each other, letting us create multi-dimensional arrays. We can make arrays out of a collection of any objects. They can also be destructed into variables so each entry can be accessed and manipulated individually. JavaScript arrays are zero-indexed so the starting index of each array is always zero. This means that index 0 has the first element of the array.

Arrays can contain any type of object. They do not have to be the same type of objects. Also if an array entry with a given index hasn’t been assigned yet, it has an undefined value.

Examples of things that can be stored with arrays include:

  • to-do list
  • recipe list
  • address book contacts
  • shopping list
  • grocery list
  • your appointments
  • anything else that can be entered into a list.

Without arrays, all we can do is declare variables for each entry individually which is a real pain and not practical.

Declaring Arrays

To declare arrays, we use the let or const keyword — like this:

let arr = [1,2,3];
const arr2 = [1,2,3];

We use let for variables and const for arrays that don’t change.

Also, we can declare the arrays first and then insert the values later, like this:

let arr = []
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;

This is the same as let arr = [1,2,3] since we have the same entries and the same order in both arr arrays.

We can declare arrays with different type of values in the same array, like this:

let arr = [1, 'chicken', {foo: 'bar'}];

As you can see, it doesn’t matter what kind of data we put in the array. However, we do have to be careful to avoid data type errors when we traverse or manipulate arrays by checking the type and content of the objects, and whether any entry is null or undefined .

Another way to create an array is the new keyword, like this:

let names = new Array('Bob','Jane', 'John');

Accessing Array Data

We access array items by their index. For example, to get the second element of an array, we write:

arr[1]

If arr is assigned to [1, ‘chicken’, {foo: ‘bar’}]; , then arr[1] would be 'chicken' .


Get Array Size

Array is an object that has the length property that we can get the size of the array, so the names array we have above would have a length of three. We write the names.length to access the length of the array.


Multidimensional Arrays

In JavaScript, multidimensional arrays are just an array nested in another array. So, to declare a multidimensional array, we can use the same declaration methods as above, except we replace the entities inside with arrays. For example, we can write:

let multiArray = [[1,2,3], [4,5,6]];

or:

let multiArray = new Array([1,2,3], [4,5,6]);

We can also write:

let multiArray = [];
multiArray[0] = [];
multiArray[0][0] = 1;
multiArray[0][1] = 2;
multiArray[0][2] = 3;
multiArray[1] = [];
multiArray[1][0] = 4;
multiArray[1][1] = 5;
multiArray[1][2] = 6;

All three of these pieces of code are equivalent.

We access multidimensional array entries by adding another square bracket with the index of the inner array. For example, if we want to get the second item of the first array in multiArray then we write:

multiArray[0][1]

Traversing Arrays

We can traverse the values of arrays with loops. Loops are pieces of code that repeat until the ending condition is met. In JavaScript, we have the for loop, while loop and the do...while loop.

For Loop

With the for loop, given that we have the name array, we can traverse the loop by running:

let names = new Array('Bob','Jane', 'John');
for (let i = 0; i < names.length; i++){
  console.log(names[i]);
}

A for loop is usually written with the starting condition as the first statement, then the ending condition in the second statement, and the index changing condition in the third statement. The statements are separated by the semicolons. Because arrays start with index zero in JavaScript, we terminate the loop when the array’s index reaches one less than the array’s length.

While Loop

while loop will loop whenever a condition stays true.

For example, the loop below will run if the index number i is less than three:

const array = [1,2,3];let i = 0;
while(i < array.length){
  console.log(i);
}

If the condition in the parentheses is never true, then the loop content will never run.

Do While Loop

do...while loop will always execute the first iteration.

const array = [1,2,3];let i = 0;
do{
  console.log(i);
}
while(i < array.length)

In the example above, it will at least log 0, but it will also log 1 and 2 in this case since those two numbers are less than three.

With the above loops, you can call break to stop the loop or return before the loop is completely finished.

//do while loop
const array = [1,2,3];

let i = 0;

do{
  console.log(i);  
  if (i == 1}{    
    break;  
  }
}
while(i < array.length)

//while loop
i = 0;
while(i < array.length){  
  if (i == 1){ 
   break;  
  }
  console.log(i);
}

//for loop
for (let j = 0; j < array.length; j++){  
  if (j == 1){
    break;
  }
  console.log(j);
}

In the above examples, you will not see two logged.

An example of returning from within the loop:

const loop = ()=>{
  const array = [1,2,3];
  for (let j = 0; j < array.length; j++){
    if (j == 1){
      return j;
    }
    console.log(j);
  }
}
loop() //returns 1

You can also skip iterations with the continue statement:

const array = [1,2,3];
for (let j = 0; j < array.length; j++){  
  if (j == 1){
    continue;
  }
  console.log(j) // 1 will be skipped;
}

Array Properties

Since an array is a JavaScript object. It is its own properties. Like any object in JavaScript, it has the prototype property which lets developers add methods and properties of an array object. The constructor property is the reference to the function that’s created by the array object’s prototype. The length returns the size of the array.

Array Methods

To make manipulating arrays easy, the JavaScript’s standard library contains lots of array methods that make manipulating arrays easy. There are methods to find and filter items, and add and remove items in an array for example. There are also functions to combine multiple arrays into one.

These are some common array methods that you can use to do common operations with arrays.

Array.forEach

forEach will iterate through every entry of the array. You cannot break out of it or return a value from it. It takes a callback function where you can execute code.

Example:

const array = [1,2,3];
array.forEach(a => {  
  console.log(a);
})

In the above example, all the numbers in the array will be logged.

Array.find

Array.find will return the element in the array with the given condition. For example, if you want to get certain numbers from the array, you do this:

const array = [1,2,3];
const num = array.find(a => a == 2); // returns 2

find returns a single result.

Array.findIndex

Array.findIndex will return the index of the element in the array with the given condition. It takes a callback function that returns a given condition. For example, if you want to get the index of a certain number from the array, you do this:

const array = [1,2,3];
const num = array.findIndex(a => a == 2); // returns 1

Array.filter

Array.filter will return an array of items that meet the given condition. It takes a callback function that returns a given condition. filter returns a new array.

For example, if you want to get the index of a certain number from the array, you do:

const array = [1,2,3];
const numArray = array.filter(a => a == 2); // returns [2]

Array.includes

Array.includes checks if an item exists in an array. It takes a number or string which the function can compare.

const array = [1,2,3];
const includesTwo = array.includes(2); // returns true

Array.some

Array.somechecks if some items meet the condition given. It takes a callback function which returns a boolean for the condition.

const array = [1,2,3];
const includesTwo = array.some(a => a == 2); // returns true
const includesFive = array.some(a => a == 5); // returns false

Array.every

Array.every checks if every item meets the condition given. It takes a callback function which returns a boolean for the condition.

const array = [1,2,3];
const everyElementIsTwo = array.every(a => a == 2); // returns false
const everyElementIsNumber = array.every(a => typeof a == 'number'); // returns true since every item in the array is a number

Array.isArray

Array.isArray checks if an object given is an array. It is a convenient way to check if an element is an array.

const array = [1,2,3];const notArray = {};
let objIsArray = Array.isArray(array); // true
objIsArray = Array.isArray(notArray); // false

Array.from(new Set(array))

Set is an object that cannot have duplicate entries. You can create a new Setfrom an array then convert it back to an array.

const array = [1,2,2,3];
const arrayWithDups = Array.from(new Set(array)); //returns new array without duplicates, [1,2,3]

Array.slice(startIndex, endIndex)

Returns a new array from startIndex to endIndex — 1 .

Example:

const arr = [1,2,3,4,5];
const newArr = arr.slice(0,2);
console.log(newArr); // returns [1,2]

Array.splice(index, numberOfItems)

Remove array item in place with the given index, and then numberOfItems after it.

For example:

const arr = [1,2,3,4,5];
arr.splice(0,2);
console.log(arr); // returns [3, 4, 5] since we specified that we remove item located at index 0 and 2 items after that.

Array.sort(sortFunction)

Array.sort sorts array in place according to the condition you return insortFunction .

The sortFunction should be in this format:

const sortFunction = (a, b) {
  if (a < b) {
    return -1;
  }
  if (a > b) {
    return 1;
  }
  // a must be equal to b
  return 0;
}

By default, if no sortFunction is specified, then the array items will be converted to a string and will be sorted according to the Unicode value of the string.

Array.fill(newElement, startIndex, endIndex)

Array.fill will add or replace the element with the element specified from startIndex to endIndex . If no startIndex is defined then it will start from 0. If no endIndex is defined, then it will change values up to the end of the array.

For example:

let array = [1, 2, 3, 4, 5];console.log(array.fill(0, 2, 4));
// array is now [1, 2, 0, 0, 0]console.log(array.fill(5, 1));
// array is now [1, 5, 5, 5, 5]console.log(array.fill(6));
// array is now [6, 6, 6, 6, 6]

Recursively Flatten Array

Array.flat function does not do a good job of recursively flatten arrays. The depth is limited and it does not flatten all kinds of nested array structures. The better way to do it is to write a recursive function to do it.

let arr1 = [1, 2, [3, 4], 5];
let arr2 = [1, 2, [3, 4], [5, [6,[7,]]]];const flatten = (items) => {
  const flat = [];  items.forEach(item => {
    if (Array.isArray(item)) {
      flat.push(...flatten(item));
    } else {
      flat.push(item);
    }
  });  return flat;
}console.log(flatten(arr1));
console.log(flatten(arr2));

Array.join(separator)

Array.join will return a string by concatenating the entries after they are converted to string with separator between each entry. Works best with string and number arrays.

Example:

const arr = [1,2,3];
console.log(arr.join(',')) // get '1,2,3'const arr = ['1',2,3];
console.log(arr.join(',')) // get '1,2,3'

Array.indexOf(elementToFind)

Array.indexOfwill return the first index of the elementToFind in the array. Works best with string and number arrays. If you want to find a non-string or number object, use Array.findIndex . Returns -1 is element is not found.

Example:

const arr = [1,2,3];
console.log(arr.indexOf(1)); // returns 0const arr2 = [1,1,2,3];
console.log(arr2.indexOf(1)) // still 0

Array.lastIndexOf()

Array.lastIndexOfwill return the last index of the elementToFind in the array. Works best with string and number arrays. Returns -1 is element is not found. The function also takes a starting index to start searching backward as a second parameter

Example:

const arr = [1,2,3];
console.log(arr.indexOf(1)); // returns 0const arr2 = [1,1,2,3];
console.log(arr2.indexOf(1)) // returns 1const arr3 = [3,1,2,3]
console.log(arr3.lastIndexOf(3, 2)) // returns 0, start searching backwards from index 2

Array.push(newElement)

Array.push adds a new element to an array.

Example:

let arr = [1,2,3];
arr.push(4);
console.log(arr) // [1,2,3,4]

Array.pop()

Array.pop removes the last element of the array.

Example:

let arr = [1,2,3,4];
arr.pop();
console.log(arr) // [1,2,3]

Array.map(mapFunction)

Array.map returns a new array which transforms the existing array’s element by calling the mapFunction . mapFunction takes one argument, which is the array element.

Example:

let arr = [1,2,3,4];
const newArr = arr.map(a=>a*2)
console.log(newArr) // [2,4,6,8]

Array.reduce(reduceFunction)

Array.reduce combines elements of an array to return a value by calling the reduceFunction on all the elements to combine them. reduceFunction takes two arguments, which is the current and next element in the array.

Example:

const arr = [1,2,3,4];
const sum = arr.reduce((a,b)=>a+b);
console.log(sum); // returns 10

Array.reverse()

Array.reverse returns a new array with the existing array’s elements in reverse order.

Example:

const arr = [1,2,3,4];
console.log(arr.reverse()) // [4,3,2,1]

Now that we learned about arrays, we can do a lot more in our JavaScript programs. There’s a big world ahead of us!

Categories
JavaScript Basics

JavaScript Cheat Sheet — JSON, Loops, and Promises

JavaScript is one of the most popular programming languages for web programming.

In this article, we’ll look at the basic syntax of modern JavaScript

JSON

We can create JSON strings from JavaScript objects with the JSON.stringify method:

const obj = {
  "name": "Jane",
  "age": 18,
  "city": "Chicago"
};
const json = JSON.stringify(obj);

And we can convert JSON strings back to JavaScript objects with JSON.parse :

const obj = JSON.parse(json);

We can use it to store data in local storage.

We’ve to convert objects into strings first to store them.

To store objects we call localStorage.setItem :

const obj = {
  "name": "Jane",
  "age": 18,
  "city": "Chicago"
};
const json = JSON.stringify(obj);
`localStorage.setItem('json', json);`

The first argument is the key.

And we can get data by their keys with getItem :

localStorage.getItem('json')

Loops

JavaScript comes with various kinds of loops.

One kind of loop is the for loop:

for (let i = 0; i < 10; i++) {
  console.log(i);
}

We can loop through any kind of iterable object with the for-of loop:

for (let i of custOrder) {
  console.log(i);
}

Some iterable objects include arrays, strings, and node lists.

Another kind of loop is the while loop:

let i = 1;
while (i < 100) {
  i *= 2;
  console.log(i);
}

There’s also the do-while loop:

let i = 1;
do {
  i *= 2;
  console.log(i);
} while (i < 100)

The break keyword lets us end the loop early:

for (let i = 0; i < 10; i++) {
  if (i == 5) {
    break;
  }
  console.log(i);
}

The continue keyword lets us skip to the next iteration:

for (let i = 0; i < 10; i++) {
  if (i == 5) {
    continue;
  }
  console.log(i);
}

Data Types

JavaScript comes with various data types.

They include:

let age = 18;                           // number
let name = "Jane";                      // string
let name = { first: "Jane", last: "Doe" };  // object
let truth = false;                      // boolean
let sheets = ["HTML", "CSS", "JS"];       // array
let a; typeof a;                        // undefined
let a = null;                           // value null

Objects

We can create an object with curly braces:

let student = {
  firstName: "Bob",
  lastName: "Doe",
  age: 18,
  height: 170,
  fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
};

It has properties and methods.

this is the student object itself.

We can call fullName with student.fullName() .

And we can assign values to properties with:

student.age = 19;

Promises

We can create promises with the Promise constructor:

function add(a, b) {
  return Promise((resolve, reject) => {
    setTimeout(() => {
      if (typeof a !== "number" || typeof b !== "number") {
        return reject(new TypeError("Inputs must be numbers"));
      }
      resolve(a + b);
    }, 1000);
  });
}

We can resolve to fulfill the promise with the sum.

And we call reject to reject the promise with an error.

Then we can call then to get the resolved value and catch to get the error values:

const p = sum(10, 5);
p.then((result) => {
  console.log(result)
}).catch((err) => {
  console.error(err);
});

Conclusion

We can work with JSON, local storage, promises, and loops with JavaScript.

Categories
JavaScript Basics

JavaScript Cheat Sheet — Numbers, Strings, and Regex

JavaScript is one of the most popular programming languages for web programming.

In this article, we’ll look at the basic syntax of modern JavaScript.

Numbers

The toFixed method lets us round a number:

(3.14).toFixed(0);  // returns 3

The toPrecision method lets us round a number:

(3.14).`toPrecision`(1);  // returns 3.1

The valueOf method returns a number:

(3.14).valueOf();

The Number function lets us convert anything to a number:

Number(true);

parseInt converts non-numeric values to an integer:

parseInt("3 months");

parseFloat converts non-numeric values to a floating-point number:

parseFloat("3.5 days");

The Number function also comes with some constant properties.

They include:

  • Number.MAX_VALUE — largest possible JS number
  • Number.MIN_VALUE — smallest possible JS number
  • Number.NEGATIVE_INFINITY —  negative infinity
  • Number.POSITIVE_INFINITY — positive infinity

Math

We can do various mathematical operations with the Math object.

Math.round rounds a number to an integer:

Math.round(4.1);

Math.pow raises a base to an exponent:

Math.pow(2, 8)

Math.sqrt takes the square root of a number:

Math.sqrt(49);

Math.abs takes the absolute value of a number:

Math.abs(-3.14);

Math.ceil takes the ceiling of a number:

Math.ceil(3.14);

Math.floor takes the floor of a number:

Math.floor(3.14);

Math.sin takes the sine of a number:

Math.sin(0);

Math.cos takes the cosine of a number:

Math.cos(0);

Math.min returns the minimum number in the list:

Math.min(1, 2, 3)

Math.max returns the max number in the list:

Math.max(1, 2, 3)

Math.log takes the natural log of a number:

Math.log(1);

Math.exp raises e to the given power:

Math.exp(1);

Math.random() generates a number between 0 and 1 randomly:

Math.random();

We can generate any random number by using Math.floor and Math.random together:

Math.floor(Math.random() * 5) + 1;

5 is the max number and 1 is the min.

Global Functions

We can use the String function to convert non-string values to strings:

String(23);

We can also call toString on primitive values and objects to do the same:

(23).toString();

The Number function lets us convert non-numbers to numbers:

Number("23");

decodeURI unescapes URLs:

decodeURI(enc);

encodeURI encodes URLs:

encodeURI(uri);

We can decode URI components with decodeURIComponent:

decodeURIComponent(enc);

And we can encode a string into a URI string with encodeURIComponent :

encodeURIComponent(uri);

isFinite lets us check whether a number is finite.

isNaN lets us check whether a value is NaN .

parseFloat lets us parse a value into a floating-point number.

parseInt lets us parse non-number values to integers.

Regex

JavaScript regex has the following modifiers:

  • i — perform case-insensitive matching
  • g — perform a global match
  • m — perform multiline matching

And they can have the following patterns:

  • “ — Escape character
  • d — find a digit
  • s — find a whitespace character
  • b — find a match at the beginning or end of a word
  • n+ — contains at least one n
  • n* — contains zero or more occurrences of n
  • n? — contains zero or one occurrence of n
  • ^ — start of string
  • $ — end of string
  • uxxxx — find the Unicode character
  • . — Any single character
  • (a|b) — a or b
  • (...) — Group section
  • [abc] — In range (a, b or c)
  • [0–9] — any of the digits between the brackets
  • [^abc] — Not in range
  • s — White space
  • a? — Zero or one of a
  • a* — Zero or more of a
  • a*? — Zero or more, ungreedy
  • a+ — One or more of a
  • a+? — One or more, ungreedy
  • a{2} — Exactly 2 of a
  • a{2,} — 2 or more of a
  • a{,5} — Up to 5 of a
  • a{2,5} — 2 to 5 of a
  • a{2,5}? — 2 to 5 of a, ungreedy
  • [:punct:] — Any punctu­ation symbol
  • [:space:] — Any space character
  • [:blank:] — Space or tab

Conclusion

JavaScript comes with many useful functions.

We can use regex to match patterns in strings.

Categories
JavaScript Basics

JavaScript Cheat Sheet — Errors and Strings

JavaScript is one of the most popular programming languages for web programming.

In this article, we’ll look at the basic syntax of modern JavaScript.

Errors

We can use the try-catch block to catch errors from code that may raise errors:

try {
  undefinedFunction();
} catch (err) {
  console.log(err.message);
}

We can run code regardless of whether an error is thrown with the finally block:

try {
  undefinedFunction();
} catch (err) {
  console.log(err.message);
} finally {
  console.log('done');
}

We can throw errors by writing:

throw new Error('error')

JavaScript comes with various kinds of error classes:

  • RangeError — A number is out of range
  • ReferenceError — An illegal reference has occurred
  • SyntaxError — A syntax error has occurred
  • TypeError — A type error has occurred
  • URIError — An encodeURI() error has occurred

Input Values

We can get the entered value from an input element with the value property:

const val = document.querySelector("input").value;

NaN

We can check for NaN values with isNaN :

isNaN(x)

Run Code After a Delay

We can run code after a delay with the setTimeout function:

setTimeout(() => {

}, 1000);

Functions

We can declare functions with the function keyword:

function addNumbers(a, b) {
  return a + b;;
}

Update DOM Element Content

We can update DOM element content by setting the innerHTML property:

document.getElementById("elementID").innerHTML = "Hello World";

Output Data

To log data to the console, we call console.log :

console.log(a);

We can also show an alert box with alert :

alert(a);

Also, we can show a confirm dialog box by calling confirm :

confirm("Are you sure?");

We can ask the user for inputs with the prompt function:

prompt("What's your age?", "0");

Comments

We can add comments to our JavaScript code with // :

// One line

And we can add a multiline comment with:

/* Multi line
comment */

Strings

We can declare strings with quotes:

let abc = "abcde";

Also, we can add a new line character with n :

let esc = 'I don't n know';

We get the length of a string with the length property:

let len = abc.length;

We get the index of a substring in a given string with indexOf :

abc.indexOf("abc");

Also, we can get the last occurrence of a substring in a string with lastIndexOf :

abc.lastIndexOf("de");

We can get a substring between the given indexes with the slice method:

abc.slice(3, 6);

The replace method lets us replace a substring with another substring:

abc.replace("abc","123");

We can convert a string to upper case with toUpperCase :

abc.toUpperCase();

We can convert a string to upper case with toLowerCase :

abc.toLowerCase();

We can combine one string with another with concat :

abc.concat(" ", str2);

And we can get the character at the given index with charAt or [] :

abc.charAt(2);
abc[2];

The charCodeAt method lets us get the character code at the given index:

abc.charCodeAt(2);

The split method lets us split a string by the given separator:

abc.split(",");

We can split a string by an empty string:

abc.split("");

to split a string into an array of characters.

And we can convert a number to a string with the given base with toString :

128.toString(16);

Conclusion

We can throw and catch errors with JavaScript.

And we can use various methods to work with strings.