Categories
JavaScript Tips

Useful JavaScript Tips — Casting and Internationalization

Like any kind of apps, JavaScript apps also have to be written well. Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.

Converting String to Number

The Number function can be used to convert strings to numbers.

For instance, if we write:

Number('1')

Then we get 1.

Strings are trimmed before they’re converted to numbers, so Number(“ 1 “) returns the same result.

Any empty string results in 0.

Also, Number works with decimals. So Number(“1.2”) returns 1.2.

Converting Booleans to a Number

Booleans can also be converted to numbers.

For instance, we can write:

Number(true)

then it returns 1.

If we write:

Number(false)

it returns 0.

Converting Dates to a Number

We can pass a Date instance to a number. Passing a Date instance to Number would return a UNIX timestamp.

For instance, we can write:

Number(new Date(2020, 0, 1))

and it returns 1577865600000.

Converting Special Values to Number

We can pass in special values to Number to convert it to a number.

For instance, we can write:

Number(null)

then it returns 0.

Number(undefined) returns NaN , and Number(NaN) returns NaN .

Converting to Booleans

The Boolean converts any values to a boolean.

Any falsy values will return false . Otherwise, it return true .

For instance, the following all returns false :

Boolean(false)
Boolean(0)
Boolean(NaN)
Boolean("")
Boolean(null)
Boolean(undefined)

All other values returns true .

instanceof Operator

The instanceof operator lets us check value to see if it’s an instance of a constructor,

For instance, we can write:

class Animal {}
class Dog extends Animal {}

Then the following will return true :

const dog = new Dog()
dog instanceof Animal
dog instanceof Dog

It’ll return true for a subclass instance if the right operand is the parent class or subclass.

new Operator

We can use the new operator to create a new object from a constructor.

For instance, we can write:

const date = new Date();

We can also create our own constructor and use the new operator with it:

function Dog(breed, color) {
  this.breed = breed;
  this.color= color;
}

Then we can write:

const dog = new Dog('poodle', 'white');

typeof Operator

We can use the typeof operator to check the type of a value.

For instance, we can write:

typeof 1

and we get 'number' .

typeof '1'

returns 'string' .

typeof { name: 'james' }
typeof [1, 2, 3]

return 'object' .

typeof true

returns 'boolean' .

typeof undefined

returns 'undefined' .

typeof (() => {})

returns 'function' and

typeof Symbol()

returns 'symbol' .

Internationalization

JavaScript’s standard library has its own internationalization API.

The Intl.Collator object gives us access to language-sensitive comparison features.

Intl.DateTimeFormat lets us format dates in a language-sensitive manner.

Intl.NumberFormat lets us format numbers in a language-sensitive manner.

Intl.PluralRules lets us format plurals in a language-sensitive manner.

Intl.RelativeTimeFormat lets us access language-sensitive time formatting features.

Then Intl.getcanonicalLocales lets us check if a locale is valid.

It takes a string or an array of strings.

For instance, we can write:

Intl.getCanonicalLocales('en')

or:

Intl.getCanonicalLocales(['en-us', 'en-gb'])

They both return true since they’re valid locale strings.

On the other hand, if we have:

Intl.getCanonicalLocales('en_gb')

that’ll return false since it’s not a valid locale.

Intl.Collator

The Intl.Collator is a constructor that we can pass in a locale to and then do comparisons based on that locale.

For instance, we can write:

const collator = new Intl.Collator('en-gb')
collator.compare('a', 'c')

Then we get -1, so the strings are in ascending order.

On the other hand, if we have:

collator.compare('d', 'c')

Then 1 is returned, so they are in descending order.

Intl.DateTimeFormat

The Intl.DateTimeFormat constructor lets us access language-sensitive date and time formatting features.

For instance, we can use it as follows:

const date = new Date();
const formatter = new Intl.DateTimeFormat('fr-ca');
const formatted = formatter.format(date);

In the example above, we have the Intl.DateTimeFormat constructor.

We just pass in a locale string into the constructor.

Then we call the format method to call date on it to format the date.

So formatted will be “2020–05–12” .

We can also call the formatToParts function to return an object with the formatted date parts.

For instance, we can write:

const date = new Date();
const formatter = new Intl.DateTimeFormat('fr-ca');
const parts = formatter.formatToParts(date);

Then we get:

[
  {
    "type": "year",
    "value": "2020"
  },
  {
    "type": "literal",
    "value": "-"
  },
  {
    "type": "month",
    "value": "05"
  },
  {
    "type": "literal",
    "value": "-"
  },
  {
    "type": "day",
    "value": "12"
  }
]

as the value of parts .

Conclusion

JavaScript’s standard library has many useful internationalization features.

Also, there are many functions to convert data types.

Categories
JavaScript Tips

Useful JavaScript Tips — Functions and Casting

Like any kind of apps, JavaScript apps also have to be written well.

Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.

Function Parameters

A JavaScript function can accept zero or more parameters.

For instance, we can write:

const foo = () => {
  //...
}

or:

const bar = (a) => {
  //...
}

or:

const baz = (a, b) => {
  //...
}

Starting with ES6, we can set default values for parameters,

For instance, we can write:

const baz = (a = 1, b = 2) => {
  //...
}

Then if we don’t pass in anything when we call baz then a is 1 and b is 2.

Since ES2018, trailing commas are allowed for function parameters.

This helps reduce bugs because of missing commas around parameters.

For instance, we can write:

const baz = (a = 1, b = 2,) => {
  //...
}

We can also call a function with trailing commas:

baz(3, 4,)

Also, we can use the spread operator to spread array entries into arguments.

For instance, we can write:

const args = [2, 'foo'];
baz(...args);

We can also destructure object parameters into variables so that we don’t have to remember the order that arguments have to be passed in.

We can write:

const baz = ({ a = 1, b = 2 }) => {
  //...
}

We destructure the properties into variables.

If the property isn’t set, then we set the default value given.

Switch Statements

An alternative to the if-else statements is to use the switch statement.

For instance, we can write:

switch(a) {
  case 1:
    //do something
    break;
  case 2:
    //do something
    break;
  case 3:
    //do something
    break;
}

We check the value of a and then do something given those values.

We need a break statement at the end of each case so that the code below a matching case won’t run.

Alternatively, we can use return :

switch(a) {
  case 1:
    return 'foo';
  case 2:
    return 'bar';
  case 3:
    return 'baz';
}

Also, we can provide a default case which runs if none of the values of a matches.

For instance, we can write:

switch(a) {
  case 1:
    //do something
    break;
  case 2:
    //do something
    break;
  case 3:
    //do something
    break;
  default:
    break;
}

if and else

The if statement makes a program run something if a condition is true .

For instance, the following always runs:

if (true) {
  // do something
}

And this never runs:

if (false) {
  // never runs
}

We can add an else block below an if block if we need to do something if a condition is false .

For instance, we can write:

if (foo) {
  // do something
} else if (bar) {
  // do something else
} else {
  // fallback case
}

delete Operator

The delete operator lets us remove a property from an object.

For instance, we can write:

const dog = {
  breed: 'chow chow',
  color: 'brown'
}

Then we can remove the color property by writing:

delete dog.color;

We can also write:

delete dog['color'];

Converting to Strings

We can call the toString method on primitive values and objects to get the string representation of it.

Converting Number to String

To convert a number to a string, we can use the String function or the toString method.

For instance, we can write:

String(100);

which returns '100', or:

(100).toString();

which returns the same thing.

Convert Boolean to String

Likewise, we can use the String function or toString method to convert booleans to a string.

If we write:

String(true)

or:

true.toString()

we get true .

We can do the same with false .

Convert Date to String

The String function and toString method can also be used to convert Date instances to strings.

For instance, we can write:

String(new Date(2020, 0, 1))

Then we get:

"Wed Jan 01 2020 00:00:00 GMT-0800 (Pacific Standard Time)"

and we can do the same with toString :

(new Date(2020, 0, 1)).toString()

Converting Special Values to String

The String function can also convert null , undefined , or NaN to a string.

If we write:

String(null)

and we get 'null' .

If we write String(undefined) and we get 'undefined' .

String(NaN) returns ‘NaN' .

Conclusion

JavaScript functions can take zero or more function parameters.

We can set default values for them.

The delete operator can be used to remove a property.

Categories
JavaScript Tips

Useful JavaScript Tips — Checking Strings and Styling Elements

Like any kind of apps, JavaScript apps also have to be written well.

Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.

Get the Last Occurrence of a Substring in a String

The lastIndexOf method returns the index of the last occurrence of a substring in a string.

For instance, we can write:

'jane, joe, and joe'.lastIndexOf('joe')

Then we get 15.

It returns -1 if the substring isn’t found.

Get the First Occurrence of a Substring in a String

The indexOf method returns the index of the first occurrence of a substring in a string.

For instance, we can write:

'jane, joe, and joe'.indexOf('joe')

Then we get 6.

It returns -1 if the substring isn’t found.

Check if a Substring is in a String

We can check if a substring is in a string with the includes method.

For instance, we can write:

'jane, joe, and alex'.includes('joe')

Then it returns true .

Otherwise, if we have:

'jane, joe, and alex'.includes('foo')

then it returns false .

It also takes a second argument to indicate which index we want to start the search.

For example, we can write:

'jane, joe, and alex'.includes('joe', 10)

then it returns false .

Check if a String Ends with a Substring

The endsWith method lets us check if a string ends with a substring.

For example, we can write:

'jane, joe, and alex'.`endsWith`('alex')

then it returns true .

We can also pass in an integer to search for a substring with the given length of the string.

For example, we can write:

'jane, joe, and alex'.`endsWith`('alex', 5)

Then it returns false since 'alex' isn’t in the first 5 characters of the string.

Combining 2 or More Strings

The concat method lets us combine 2 or more strings.

For instance, we can write:

'jane'.concat(' ', 'smith');

to get 'jane smith' .

Also, we can write:

'jane'.concat(' ').concat('smith');

to get the same thing.

Get the Unicode Character Code of a Character

The charCodeAt method lets us get the character code of a character./

For instance, if we have:

'a'`.charCodeAt(0)`

Then we get 97 .

We can also use the codePouintAt method:

'a'`.codePointAt(0)`

to get the same result.

Get a Character from a String by Index

The charAt method lets us get the character by its index.

For example, we can write:

'jane'.charAt(0)

to return 'j' .

Find the Location of a Substring that Matches a Given Pattern

The search method lets us search for a substring with the given pattern.

For instance, we can write:

'jane, joe, and alex'.`search`('jane')

Then we get 0.

We can also search with a regex.

For example, we can write:

'jane, joe, and alex'.search(/\b\[a-z\]{3}\b/)

Then we get 6.

If no match is found, then -1 is returned.

Replace a String with the Given Pattern with Another String

The replace method lets us replace a substring with the given pattern with the given substring.

For instance, we can write:

'jane, joe, and alex'.replace(/\b\[a-z]{3}\b/, 'may')

Then we get “jane, may, and alex” .

List All Methods of an Object

We can get all the methods of an object with Object.keys and the typeof operator.

For example, we can write:

const getMethods = (obj) => Object.keys(obj).filter(key => typeof obj\[key\] === 'function')

Object.keys only get noninherited string properties of an object.

So if we have:

const person = {
  name: 'james',
  eat() {},
  drink() {}
}

Then we can call getMethods by writing:

`getMethods(`person)

And get [“eat”, “drink”] .

Style a DOM Element

We can style an element in various ways.

We can add or remove classes from an element.

Also, we can add inline styles to it.

Given that we have the following element:

const element = document.querySelector('#foo')

We can use the classList property of the element to add and remove classes:

element.classList.add('fancy')
element.classList.remove('fancy')

Also, we can access the style property as follows.

We can write:

element.style.color = 'green';

Adding and removing classes are preferred because it’s faster than changing styles on the fly.

Conclusion

We can add styles to an object by using the styles property.

The classList property lets us add or remove classes from an element.

There are string methods to get the info we need from a string.

Also, we can replace and search for substrings.

Categories
JavaScript Tips

Useful JavaScript Tips — Variables, File Names, and Console

Like any kind of apps, JavaScript apps also have to be written well. Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.

var and let

var is function scoped and let is block-scoped.

var is hoisted and let isn’t.

Only the variable is hoisted, but the value isn’t.

For instance, if we have:

console.log(x);
var x = 1;

then x would be undefined since var x is hoisted but 1 is not.

On the other hand, we can’t do the same thing with let :

console.log(x);
let x = 1;

We’ll get an error with the code above since we can’t use let variables unless they’ve been declared.

To reduce confusion, we should use let variables.

Breaking the forEach Iteration

We can return true inside the callback that we pass into forEach to skip an itreration.

This way, we can have the same functionality as continue .

For instance, we can write:

[0, 1, 2, 3, 4].forEach((val, i) => {
  if (val === 2) {
    return true;
  }
  console.log(val);
});

The code about would skip 2 since when val is 2, then we returned true .,

So we skipped the console log that’s below it.

Using Slice

The slice method can be used to get array entries from an array.

We can start with a negative index to return array entries from the right instead of the left.

So if we have:

const arr = [1, 2, 3];

Then:

arr.slice(-1)

returns [3] .

arr.slice(-2))

returns [2, 3] .

and:

arr.slice(-3)

returns the original array.

This is because -1 is the index of the last element of the array.

-2 is the second last and so on.

Short Circuit Conditionals

Short circuit conditionals are handy since we can do things with && and || that we might not have thought of.

For instance, instead of writing:

if(condition){
    dosomething();
}

We can write:

condition && dosomething();

since the doSomething is only run when condition is truthy with the && operator.

Likewise, we can take advantage of short-circuiting with the || operator.

For instance, we can write:

a = a || 'default';

since a is assigned to a if a is truthy.

Otherwise, 'default' is assigned to a .

Use Optional Arguments

We can make arguments optional with the default parameter syntax.

For instance, we can write:

const divide = (a, b = 1) => a / b;

Then b would be assigned to 1 if we skipped the argument.

So divide(2) would be 2.

Copy Things to the Clipboard

We can get the element from a clipboard and copy its contents by writing:

document.querySelector('#foo').select();
document.execCommand('copy');

The first line selects the element with ID foo .

Then the second line does the copying.

Extract File Extension from a File Name

There are a few ways that we can extract the file extension from the file name

Regex

For instance, we can write:

const getExt = (filename) => {
  return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename)[0] : undefined;
}

We have a regex to split the file name by the dot. Then we get the part after the dot with /[^.]+$/.exec(filename)[0] or undefined if there’s no dot.

split

Also, we can use the split method to split a file name by the dot.

For example, we can write:

const getExt = (filename) => {
  return filename.split('.').pop();
}

A string has the split method which can split a string by a separator and returns it as an array of strings.

Then we call pop to remove the last part of the split string and returns it.

Therefore, we get the extension.

Console Logging Trick

We can use the && to run console log before evaluating the expression after it.

Since console.log returns undefined the right operand will always be evaluated.

So we can write:

console.log(foo) && false

We logged the value of foo and return false all in one expression.

Print a Function to a Console

We can convert a function to a string to print out the function’s code.

For instance, we can write:

console.log(func.toString());

This way, we can see the code of the function in the console log.

Conclusion

We can log a function’s code in with the toString and console.log methods.

Also, we can use the && operator to log a value before evaluating some other expression.

There are also various ways to get the file extension from a file name.

Finally, we should use let to declare variables as much as possible.

Categories
JavaScript Tips

Useful JavaScript Tips — Strings

Like any kind of apps, JavaScript apps also have to be written well.

Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.

Convert Strings to Uppercase

We can call toUpperCase to change the string characters to uppercase.

For instance, we can write:

'foo'.toUpperCase()

then it returns 'FOO' .

Convert Strings to Lowercase

To convert a string to lowercase, we can use the toLowerCase method.

For instance, we can write:

'FOO'.`toLowerCase`()

then it returns 'foo' .

Converting Strings to Uppercase in a Locale-Sensitive Way

We can use the toLocaleUpperCase method to convert a string into a locale-sensitive upper case string.

For instance, we can write:

'foo'.toLocaleUpperCase('tr');

Then we get “FOO” .

Converting Strings to Lowercase in a Locale-Sensitive Way

There’s the toLocaleLowerCase method to convert a string into a locale-sensitive lowercase string.

For instance, we can write:

'FOO'.toLocaleLowerCase('tr');

Then we get “foo” .

Extracting a Substring From a String

To extract a substring from a string, we can use the substring method.

It takes a start and ending index of a string.

For instance, we can write:

'jane, joe, and alex'.substring(5, 10);

and that returns “ joe,” .

The index can also be negative.

So we can write:

'jane, joe, and alex'.substring(-10, 4);

and get 'jane' .

Negative indexes start from -1 which is the index of the last character, -2 is the index of the 2n last character, and so on.

Check if a String Starts With Something

Strings have a startsWith method that we can use to check if a string starts with a given substring.

For instance:

'jane, joe, and alex'.`startsWith`('jane');

returns true .

On the other hand;

'jane, joe, and alex'.`startsWith`('foo');

returns false .

It also takes a second argument to make startsWith starts the search from a given index.

For instance, we can write:

'jane, joe, and alex'.`startsWith`('jane', 5);

Then startsWith starts searching with index 5.

Split a String According to a Separator

We can call split according to a separator.

For instance, we can write:

'jane, joe, and alex'.`split`(' ');

Then we split the string according to the space characters.

So we get [“jane,”, “joe,”, “and”, “alex”] as the result.

Extract a Slice of a String

The slice method can help with extracting a substring from a string.

It takes a start and end index.

For instance, we can write the following code:

'jane, joe, and alex'.`slice`(5, 10)

Then that returns the string “ joe,” .

It also takes negative indexes, with -1 being the last character, -2 being the 2nd last, and so on.

For instance, we can write:

'jane, joe, and alex'.`slice`(-10, -5)

and it returns “, and” .

Make a String Repeat

The repeat method can make a string repeat.

For instance, we can write:

'fooo'.repeat(3)

Then we get “fooofooofooo” .

Adding Characters to the Beginning of the String

The padStart method takes an argument for the target length of the string after padding.

The 2nd argument is the string to pad our string with.

For instance, we can write:

‘foo’.padStart(8, ‘abcd’)

Then it returns “abcdafoo” since it pads 'foo' with 'abcd' repeated until the returned string has 8 characters.

Adding Characters to the End of the String

The padEnd method takes an argument for the target length of the string after padding to the end.

The 2nd argument is the string to pad our string with.

For instance, we can write:

‘foo’.`padEnd`(8, ‘abcd’)

Then we return “fooabcda” since we add the string to the end of the string.

Removing Extra Unicode Characters

We can use normalize to remove extra characters by replacing them with single-character equivalents.

For instance, we can write:

'\u1E9B\u0323'.normalize()

Then we get “ẛ̣” .

Find the String Matches a Given Regex Pattern

The match method returns the matches of a given regex pattern.

For instance, we can write:

'foo'.match(/(foo|bar)/)

Then that would return [ "foo", "foo" ] .

Compare Strings by Using the Locale Compare

localeCompare compares the strings in a locale-sensitive way.

For instance, we can write:

'a'.localeCompare('à', 'fr-ca')

Then that returns -1 since ‘à’ is behind 'a' .

Conclusion

There are string methods that we can do many things with.

We can compare strings and pad them to a given length.