Categories
JavaScript Tips

Useful JavaScript Tips — Emails and Exceptions

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.

Validating Emails

We can validate emails with a simple regex.

For instance, we can write:

const expression = /\S+@\S+/
expression.test('abc@example.com'.toLowerCase())

\S stands for any non-whitespace character.

+ stands for at least one of the characters types preceding it.

@ is the ampersand sign.

This is a simple regex that can let us check for most email addresses.

We can use this without trouble.

Quotes

JavaScript allows 3 kinds of quotes.

We can write single quotes, double quotes, and backticks.

Single and double quotes are the same.

Backticks are for template strings.

JavaScript Classes

We can create classes, which are syntactic sugar for constructors.

For instance, we can write:

class Person {
  constructor(name) {
    this.name = name
  }

  greet() {
    return `hi, ${this.name}`;
  }
}

We have the Person constructor.

It has the constructor method to initialize the Person instance.

greet is a method that we can reference this .

this is the Person instance.

So we can write:

const joe= new Person('joe');
console.log(joe.greet());

Then we get 'hi, joe' logged in the console.

Class Inheritance

We can use the extends keyword to inherit a parent class.

For instance, we can write:

class Student extends Person {
  greet() {
    return `Hi, ${this.name}. I am a student.`;
  }
}

We have the Student class that’s a subclass of Person .

We have overridden the greet method from Person .

For instance, we can write:

const joe = new Person('joe');
console.log(joe.greet());

Then we’ll see:

'Hi, joe. I am a student.'

logged in the console.

Static Methods

Classes can have static methods.

We can write:

class Person {
  static greet() {
    return 'hi';
  }
}

The method is shared among all instances of a class.

Then we can write:

Person.greet()

to call the method.

Getters and Setters

We can add getters and setters in a class.

For instance, we can write:

class Person {
  constructor(name) {
    this._name = name
  }

  set name(value) {
    this._name = value
  }

  get name() {
    return this._name
  }
}

We have the _name field, which we use the name setter to set.

Setters are indicated with the set keyword.

Getters are indicated with the get keyword.

We can have a field that only has a getter.

For instance, we can write:

class Person {
  constructor(name) {
    this._name = name
  }

  get name() {
    return this._name
  }
}

Then we can only get the value of name but not set it.

We can also have a field that only has a setter.

For instance, we can write:

class Person {
  constructor(name) {
    this._name = name
  }

  set name(value) {
    this._name = value
  }
}

Then we can only set name but not get its value.

Getters and setters are handy for creating properties that are derived from other properties.

Exceptions

JavaScript code can throw exceptions like many programming languages.

It has the throw keyword to let us throw exceptions.

For instance, we can write:

throw value

where value can be any value.

Handling Exceptions

We can handle exceptions with the try-catch block.

For instance, we can write:

try {
  // code that may throw exceptions
} catch (e) {

}

Then we can catch any exceptions that are thrown within the try block.

e has the value that’s thrown by throw .

The finally block contain the code that’s executed regardless of the program flow.

We can use finally without catch .

It serves as a way to clean up any resources opened in the try block.

try blocks can be nested.

In this case, the nearest exception is handled.

For instance, we can write:

try {
  // code

  try {
    // more code
  } finally {
    // more code
  }

} catch (e) {

}

Conclusion

We can use getters and setters to get and set properties.

Also, we can throw and handle errors with exceptions.

JavaScript classes make inheritance easier. They’re equivalent to constructors.

Categories
JavaScript Tips

Useful JavaScript Tips — Arrays, Strings, and Links

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.

Check if a value is an Array

We can use the Array.isArray method to check if a value is an array.

For instance, we can write:

const arr = [1, 2, 3];
Array.isArray(arr);

Then the isArray method returns true since arr is an array.

Join 2 Arrays

There are multiple ways to join multiple arrays.

One way is the spread operator. For instance, we can write:

const arr = [...arr1, ...arr2];

Given than arr1 and arr2 are arrays, we used the spread operator to spread the array entries from both one after the other.

We can also use the concat method to concatenate 2 arrays.

For instance, we can write:

const arr = arr1.concat(arr2);

The concat method also returns an array.

Therefore, arr has the same value as the first example.

Join 2 Strings

There are a few ways to join 2 strings together.

We can use the + operator to concatenate 2 strings.

For instance, we can write:

const fullName = firstName + lastName;

Then the 2 strings are combined together with the + operator.

The += operator adds a second string to the first.

For instance, we can write:

name += lastName;

Then we concatenate lastName to name .

Like arrays, strings also have the concat method.

For instance, we can write:

const fullname = firstName.concat(lastName);

firstName is concatenated with lastName and then return a new string.

So fullName would have the concatenated string.

Run JavaScript Code from a Link

If we want to run JavaScript code from a link, then we cal set the value of the href attribute by using javascript:void(0) .

Then in the handler then we can write our JavaScript code.

For instance, we can write the following HTML:

<a href="javascript:void(0)" onclick="handleClick()">click me</a>

Then in our JavaScript file, we can write:

const handleClick = () => {
  alert('clicked');
  return false;
}

We return false in our handleClick function so that the browser won’t scroll back to the top when the function is run.

let and var Variables

There are great differences between let and var variables.

let creates variables that are block-scoped.

var creates a variable that is function scoped. They’re also hoisted.

Block-scoped variables are only available within the block, which is what we want most of the time.

There won’t be any confusion with block scoped.

The hoisting feature of var variables are confusing, and their value is sometimes not what we expect.

Don’t Modify Built-in Prototypes

We should never modify object prototypes.

If we modify them, then we’ll get unexpected results since people don’t expect us to change the prototypes.

If we want to add functionality, we should just create and modify our own code.

There may be conflicts if we modify built-in prototypes.

Add an Item to a Specific Index

To add an item to a specific index, we can use the splice method to add an entry to an array with the given index.

For instance, if we have:

const colors = ['green', 'red'];

and we want to insert 'orange' into index 1, we can write:

colors.splice(1, 0, '`orange`');

The first argument is the starting index that we want to change.

0 means that we don’t want to delete anything.

'orange' is the item we want to insert between 'green' and 'red' .

splice changes an array in place, so we get that colors is [“green”, “orange”, “red”] .

If we want to add multiple entries in between 'green' and 'red' , we can write:

colors.splice(1, 0, 'orange', 'blue');

We just pass in as many arguments as we want after the 2nd one to insert them all into the position we want.

So colors would be [“green”, “orange”, “blue”, “red”] .

Conclusion

We can run code from a link by setting the href value to javascript:void(0) so we can run code that we want by attaching handlers to event handling attributes.

With splice , we can add items starting at a specific index.

There are multiple ways to join 2 strings or arrays together.

Categories
JavaScript Tips

Useful JavaScript Tips — Various Tricks

As with any kind of app, JavaScript apps have to be written well otherwise we will 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.

Empty a JavaScript Array

To empty a JavaScript array, we can set its length property to 0.

For instance. we can write:

const arr = ['a', 'b', 'c'];
arr.length = 0;

Then arr would be an array with no length.

Likewise, we can just assign it an empty array:

const arr = ['a', 'b', 'c'];
arr.length = [];

Hide DOM Elements Dynamically

DOM elements can be done dynamically using JavaScript.

We can use the stykle.display property to do it.

For instance, we can write:

element.style.display = 'none';

It’s the same as setting display: 'none' .

If we want to toggle them element back on, we can write:

element.style.display = 'block'

Get the Index of Iteration in the for-of Loop

We can get the index of iteration of the for-of loop with the entries method of the array.

Then we can combine that with a destructuring assignment.

For instance, we can write:

for (const [i, v] of ['foo', 'bar', 'baz'].entries()) {
  console.log(i, v);
}

i is the index and v is the value.

Generate a Random Number Between 2 Numbers

We can generate a random number between 2 numbers with some arithmetic and the Math.random method.

For example, we can write:

Math.floor(Math.random() * 10 + 1)

Then we generate numbers between 1 and 10.

Math.floor rounds the generated number down to the nearest integer.

Using map with async Functions

The array instance map method can be used with the Promise.all to return a promise with an array of items mapped to a promise.

For instance, we can write:

const getData = async () => {
  return Promise.all(arr.map(item => asyncFunc(item)))
}

Assuming that asyncFunc is a function that returns a promise, we return an array of promises with the map call.

Therefore, we can use Promise.all on it so that we can invoke them in parallel.

Initialize an Array with Values

We can use the Array constructor with the fill method to create an array and fill it with items.

For instance, we can write:

Array(20).fill(10)

to create an array with 20 empty slots, then fill the slots with 10.

Get the Current URL

The window.location object has various properties about the current URL.

Since window is the global object, we can omit it and just use location .

location.href has the whole URL.

location.hostname has the hostname.

location.origin has the originating URL.

location.hash has the part after the # sign.

location.pathname has the path after the hostname.

location.port has the port number.

location.protocol has the protocol.

location.search has the query string.

Create a Multiline String

A multiline string can be created easily with template literals.

For instance, we can write:

const multilineStr = `hello
world`

Then the string will stay in 2 lines.

Check if a String Starts with a Given String

JavaScript strings have the startsWith method to check if a string starts with a given string.

We can call it by using:

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

Then it would return true .

It also takes a second argument, which lets us specify the index of which character we want to start checking.

For instance, we can write:

'jane, joe and alex'.startsWith('jane', 8)

Then startsWith starts searching at index 8, so it returns false .

Get Unique Values of an Object Property in Array Entries

We can get the unique values of an object in array entries by mapping the values to an array.

Then we use the Set constructor, and then use the spread operator to convert that back to an array.

For example, we can write:

const bills = [{
    date: '2020-01-20',
    amount: '70',
    category: 'phone'
  },
  {
    date: '2020-01-20',
    amount: '20',
    category: 'gas'
  },
  {
    date: '2020-02-20',
    amount: '75',
    category: 'phone'
  }
]

Then we can write:

const categories = [...new Set(bills.map(bill => bill.category))]

Then categories would be [“phone”, “gas”] .

Conclusion

We can get the current URL with the location global object. To empty an array, we can set the length property to 0. Promise.all can be used to run multiple promises in parallel.

Categories
JavaScript Tips

Useful JavaScript Tips — Objects, Undefined, and Month Names

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.

Nullish Coalescing

The bullish coalescing operator is better for returning default values than the || operator.

|| returns the right expression if the left expression is falsy.

?? only returns the right expression if the left expression is null or undefined .

Therefore, instead of writing:

const favoriteColor = color || 'green';

We write:

const favoriteColor = color ?? 'green';

It’s going to be available in ES2020, which should be released any minute.

Replace Whitespace Inside a String

We can replace whitespace inside a string with the replace method and some simple regex.

To make the replacement, we write:

const str = 'hello world ';
const noSpace = str.replace(/s/g, '')

Then we get that str ‘s whitespaces are removed since s stands for whitespaces.

The new string with the spaces removed is returned, then we can assign it to something else.

Optional Chaining

We can use the optional chaining operator to allow us to navigate nested object properties safely.

For instance, instead of writing:

const color = dog && dog.color && dog.color.name;

to check if each nested property is defined.

We can just write:

const color = dog?.color?.name

The ?. will check if the nested property is defined automatically return undefined automatically if any nested property in the chain isn’t defined.

It’s available in ES2020, and browser support is being added for it.

Dynamic Imports

We don’t have to import modules statically.

There’s the import function to let us import modules dynamically.

We can write:

const module = await import('module');

to import a module with the import function, which returns a promise.

This is why we have the await keyword before the calling import .

With support for top-level await coming, we can have this line on its own.

To do a default import, we can write:

const module = (await import('module')).default()

Calling the default method will resolve to the default export.

Iterate Over Object Properties

We can iterate over object properties in various ways.

We can use the for-in loop to loop over object properties.

For instance, we can write:

for (const key in obj) {
  console.log(key)
}

This will loop over both non-inherited and inherited properties of obj .

The Object.entries method returns the key-value pairs of an object as an array.

It returns the non-inherited properties.

For instance, we can write:

Object.entries(items).forEach(item => {
  console.log(item)
})

or:

for (const item of Object.entries(items)) {
  console.log(item)
}

Both of them will loop through the key-value pairs.

Wait for Multiple Promises to Resolve

If we have 2 or more unrelated promises that we want to wait to resolve, then we use Promise.all to do that.

For instance, we can write:

const data = await Promise.all([promise1, promise2])

Assuming that promise1 and promise2 aren’t dependent on each other, we can get the resolved data of each in an array.

data has an array of resolved values of all the promises.

Get the Month Name of a JavaScript Date

We can get the month name of a JavaScript date by writing:

const date = new Date(2020, 0, 1);
const monthName = date.toLocaleString('default', { month: 'long' });

The toLocaleString method returns the month name for us.

Therefore, monthName is 'January' .

'long' means we return the long name.

Get the Last Element of an Array

We can get the last element of an array with the index arr.length — 1 where arr is an array.

For instance, we can write:

const arr = ['red', 'blue', 'green'];
const last = arr[arr.length - 1];

Then last would be 'green' .

Conclusion

We can use the nullish coalescing operator to return the default value.

The optional chaining operator can be used for safe navigation.

Also, we can get month names, object entries, and the last item of the array easily.

We can do dynamic imports with the import function. It imports modules asynchronously.

If we have multiple independent promises, we should use Promise.all to run them in parallel.

Categories
JavaScript Tips

Useful JavaScript Tips — Formatting Numbers and Objects

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.

Intl.NumberFormat

We can use the Intl.NumberFormat constructor to format numbers.

For instance, we can write:

const formatter = new Intl.NumberFormat('fr-ca', {
  style: 'currency',
  currency: 'CAD'
})
const price = formatter.format(100);

Then price is “100,00 $” since we set the locale to Canadian French and the currency is Canadian dollars.

We can also set the minimumFractionDigits property to set the minimum number of fractional digits in the return number string.

For instance, we can write:

const formatter = new Intl.NumberFormat('fr-ca', {
  style: 'currency',
  currency: 'CAD',
  `minimumFractionDigits: 2
`})
const price = formatter.format(100);

We set the minimumFractionDigits to 2 so that we’ll always show those digits.

Intl.PluralRules

The Intl.PluralRules constructor lets us return the name of the plural rule to use.

For instance, we can write:

const pr = new Intl.PluralRules('en-gb', {
  type: 'ordinal'
})

Then we can use the select method on pr as follows:

pr.select(0)

Then we get 'other' . If we write pr.select(1) we get 'one' .

pr.select(2) returns 'two' and pr.select(3) returns 'few' .

Now, we can create an object to get the proper ordinal suffix for the language.

For instance, we can write:

const suffixes = {
  'one': 'st',
  'two': 'nd',
  'few': 'rd',
  'other': 'th'
}

So we can format a number by writing:

const format = number => `${number}${suffixes[pr.select(number)]}`

Then we can call the format function with the proper number by writing:

format(0)

Then we get '0th' . format(1) returns '1st' and so on.

Objects

There are many ways to create objects, we can create an object literal, use the Object constructor or use Object.create .

For instance, we can write:

const dog = {};

or:

const dog = Object();

or:

const dog = Object.create();

Object.create is used to create an object with its own prototype.

Object literal is the preferred way if we don’t need to set our own prototype.

We can also create a constructor function to create multiple objects of the same type.

For instance, we can write:

function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName= lastName;
}

Then we can use the new operator by running:

const person = new Person('james', 'smith');

Objects are always passed by reference.

If we assign it to a variable, then the variable references the original object.

Built-in Object Properties

Most objects have built-in properties.

It has a prototype that has the Object.prototype object, which most objects inherit from.

All objects that aren’t created with a null prototype inherits from Object.prototype .

Object valueOf() Method

JavaScript objects have the valueOf method to return the primitive representation of an object.

For instance, we can write:

const person = { name: 'joe' };
const val = person.valueOf();

Then we get back the object.

However, the value of it is that we can override the method to return what we want.

Object toString() Method

The toString method returns a string representation of an object.

For example, we can write:

const person = { name: 'joe' };
const val = person.valueOf();

Then we get ‘[object Object]' , but we can override it to give us the string value we want.

Check if an Object is Enumerable

The enumerability of an object indicates whether we can traverse an object property.

For instance, we can write:

const person = { name: 'james' }

Object.defineProperty(person, 'age', {
  value: 27,
  enumerable: false
})

Then we can use the propertyIsEnumerable method to check if the property can be traversed.

For instance, we can write:

person.propertyIsEnumerable('name')

and returns true .

And:

person.propertyIsEnumerable('age')

returns false .

So if we use a for-in loop to loop through person , then we’ll see name but not age .

Conclusion

We can create objects with object literals, the Object constructor, and the Object.create method.

To check if an object property is enumerable, then we can use the propertyIsEnumerable method.

There are also methods to format numbers in a language-sensitive manner.