Categories
JavaScript Tips

JavaScript Tips — Parsing URLs, Reading Files, and More

Like any kind of apps, there are difficult issues to solve when we write JavaScript apps.

In this article, we’ll look at some solutions to common JavaScript problems.

Parse a URL into Hostname and Path

To parse a URL string into its hostname and path, we can use the URL constructor.

For instance, we can write:

new URL("http://example.com/foo/bar")

Then that returns an object with the hostname and pathname properties.

hostname is the hostname.

pathname is the pathname.

Format JavaScript Date as yyyy-mm-dd

We can format a date as a string in yyyy-mm-dd format with a few date methods.

For instance, we can write:

const d = new Date(date);
let month = (d.getMonth() + 1).toString();
let day = (d.getDate()).toString();
const year = d.getFullYear();

if (month.length < 2) {
  month = `0${month}`;
}

if (day.length < 2)  {
  day = `0${day}`;
}

const formattedDate = [year, month, day].join('-');

We create a date object from the Date constructor.

Then we call getMonth to get the month.

We’ve to add 1 because the month is zero-based.

We get the day of the month with getDate .

Also, we get the 4 digit year with getFullTear .

If the month or day is a single digit, then we put a zero before it.

Then we join the year, month, and day together with '-' .

A simpler solution would be to use the toISOString method.

For example, we can write:

const formattedDate = new Date().toISOString().slice(0, 10);

We convert the date to a string and extract the year, month, and day parts.

Check if Element is Visible in DOM

We can check if an element is visible in the DOM in a few ways.

One way is to use the offsetParent property to check for visibility.

The property will return null whenever it or its parents are hidden via the display style property.

This will be true if there are no fixed elements on the page.

If there are no fixed elements on the page, then we write:

el.offsetParent === null

where el is the element to check for visibility, to check for it.

We can also call getComputedStyle with an element as its argument to get its computed display style.

So we can write:

cpnst style = window.getComputedStyle(el);
const isInvisibie = style.display === 'none';

We check that the style.display property is 'none' .

Convert a String to a Character Array

We can split a string to a character array with the split method.

For example, we can write:

const output = "foo bar".split('');

Then we get:

["f", "o", "o", " ", "b", "a", "r"]

as the value of output .

Get Array of Object’s Keys

To get an array of an object’s keys, we can use the Object.keys method.

For example, we can write:

const obj = {
  foo: 1,
  bar: 2
};

const keys = Object.keys(obj);

Then we keys is ['foo', 'bar'] .

Create an Empty Object with {} or new Object()

There are no benefits with using new Object() .

And using {} is more compact and readable.

Therefore, we should use the object literal syntax rather than the Object constructor.

Read a Local Text File

We can read a local text file with client-side JavaScript.

To do this, we can use the FileReader constructor to do it.

We can let users select a file and read the selected text file.

For instance, we can add a file input:

<input type='file' accept='text/plain' onchange='openFile(event)'>

Then we can write:

const openFile = (event) => {
  const input = event.target;
  const reader = new FileReader();
  reader.onload = () => {
    const text = reader.result;
    consr node = document.getElementById('output');
    node.innerText = text;
    console.log(reader.result);
  };
  reader.readAsText(input.files[0]);
};

We created the openFile function which takes a event parameter.

We get the input element with event.target .

Then we get the selected file with files[0] .

Next, we create a FileReader instance and call readAsText on it with the file as the argument.

Then the onload callback will run and we get the result with reader.result .

Conclusion

We can use the URL constructor to parse a URL into its parts.

The FileReader lets us read text files.

To format dates without a library, we can use toISOString or methods to get the date parts.

There are several ways to check if an element is visible.

Categories
JavaScript Tips

Useful JavaScript Tips — Object Freezing

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 the Prototype of an Object

We can use the isPrototypeOf method of an object to check if another object is a prototype of an object.

For instance, if we have:

const animal = {
  name: 'james'
}

const dog = Object.create(animal);

Then we can call isPrototypeOf by writing:

`animal`.isPrototypeOf(dog)

That expression would return true since we passed animal into Object.create .

On the other hand, if we have:

const cat = {};

Then:

animal.isPrototypeOf(cat)

returns false .

Check if an Object has a Given Property

We can check if an object has a given property by using the hasOwnProperty method.

It checks if a property is a non-inherited property of an object.

For instance, we can write:

const person = { name: 'james' };
const hasName = person.hasOwnProperty('name');

Then we can check if the name property is in the person object with hasOwnProperty .

The has hasName would be true since name is a property of person .

Get All the Property Values from an Object

We can get all the property values of an object with the Object.values() method.

For instance, we can write:

const person = { name: 'james', age: 7 };
const values = Object.values(person);

Then values would be [“james”, 7] .

Set the Prototype of an Object

The prototype of an object can be set after the object is created.

We can do that with the setPrototypeOf method.

For instance, we can write:

const dog = {
  breed: 'poodle'
};

const animal = {
  name: 'james',
  age: 7
};

Object.setPrototypeOf(dog, animal);

setPrototypeOf is a static method of Object .

dog is the object that we want to set the prototype of.

animal is the prototype that we want to set dog to.

Therefore, we can write:

console.log(dog.name);

Then we have 'james' as the value of dog.name since dog inherits properties from animal .

Sealing the Object

Sealing an object means that we prevent an object from accepting new properties.

Also, we prevent properties from being removed.

We can use the Object.seal method to prevent properties from changing.

For instance, we can write:

const dog = {
  breed: 'poodle'
};

Object.seal(dog);

dog is sealed so we can’t add or remove properties from it.

There’s also the Object.freeze method that does less than seal .

It doesn’t make properties non-writable in addition to what seal does.

For example, we can write:

const dog = {
  breed: 'poodle'
};

Object.freeze(dog);

There’s also the preventExtensions method to disallow adding properties.

We call it the same way as seal and freeze .

Getting Non-inherited String Keys with the Object.keys Method

We can get non-inherited string keys from an object with the Object.keys method.

For instance, we can use it by writing:

const dog = {
  breed: 'poodle'
};
const keys = Object.keys(dog);

Then the value of keys is [“breed”] .

It’s an array so we can do whatever we want with them like other arrays.

Check if an Object is Sealed

The Object.isSealed method lets us check if an object is sealed.

For instance, we can write:

const dog = {
  breed: 'poodle'
};
const isSealed = Object.`isSealed`(dog);

Then we get isSealed is false since we didn’t call Object.seal on dog .

Once an object is sealed, it can’t be unsealed.

Check if an Object if Frozen

We can use the Object.isFrozen method to check if an object is frozen.

For instance, we can write:

const dog = {
  breed: 'poodle'
};
const isFrozen = Object.isFrozen(dog);

Now we can check if an object is frozen.

isFrozen should be false since dog isn’t frozen.

Check if we can add a Property to an Object

The Object.isExtensible method lets us check if we can add a property to an object.

Unless an object is passed into the Object.freeze , Object.seal , or Object.preventExtensions methods, we can add properties to it.

For instance, we can call isExtensible by writing:

const dog = {
  breed: 'poodle'
};
const isExtensible = Object.isExtensible(dog);

Then isExtensible is true since we didn’t seal or freeze dog .

Conclusion

There are many things we can do with objects that we may have missed.

We can prevent objects from changing or adding/removing properties.

Also, we can check if objects can be changed.

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.