Type something to search...
Javascript Tidbits
Photo by Dylan Gillis on Unsplash

Javascript Tidbits

A list of javascript concepts that one must know or have some tricks - like call/apply.

Call function

In javascript, methods of an object can be bound to another object at runtime. In short, javascript allows an object to borrow the method of another object:

account = {
  balance: 1000,
  getBalance: function() {
    console.log("Balance: " + this.balance);
  },
};

loan = {
  balance: 5000,
};

// Note that loan has no getBalance method.
// But we may "borrow" from account:

account.getBalance.call(loan); // will log a message with 'Balance: 5000'

The call and apply methods of function objects (in javascript functions are objects as well) allows you to do this.

Array.prototype.slice.call(document.querySelectorAll(selector));

Therefore, in above statement, Nodelist returned by the querySelectorAll() is borrowing an array’s slice method. What does the conversion is the fact that slice returns another array as it’s result. (src)

bind() also works in a same fashion. However, call() gets executed immediately, while bind() just gets the binding done.

Converting an Array of strings to comma separated values

There are different ways to generated the comma sepated values in an array of strings such as:

const names = ["Amit", "Ron", "Akon", "Ram", "Shaym"];
names.join(", ");
// 'Amit, Ron, Akon, Ram, Shaym'

However, what if you want to add “and” before the last item:

names.slice(0, -1).join(", ").concat(", and ", names.slice(-1));
// 'Amit, Ron, Akon, Ram, and Shaym'

However, there is better way to do it: Intl.ListFormat. It also takes care of internationlization.

new Intl.ListFormat('en').format(names);
// 'Amit, Ron, Akon, Ram, and Shaym'
new Intl.ListFormat('fr').format(names)
// 'Amit, Ron, Akon, Ram et Shaym'
new Intl.ListFormat('de').format(names)
// 'Amit, Ron, Akon, Ram und Shaym'

Related Posts

Java Recipes - Part 1

Java Recipes - Part 1

You can store large JSON/String objects in RDBMS with blob. Oracle recommends blob for storing JSON objects. In this article, we'll learn it how to handle it using JPA.

read more
CSS Animation Notes

CSS Animation Notes

CSS Animation basic rules and principles.

read more
Handling of blob in JPA and JDBC

Handling of blob in JPA and JDBC

You can store large JSON/String objects in RDBMS with blob. Oracle recommends blob for storing JSON objects. In this article, we'll learn it how to handle it using JPA.

read more