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.

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.