Javascript Tidbits
- Staff Curator
- Web
- 30 Sep, 2018
- 03 Feb, 2022
- 2 min read
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)
also works in a same fashion. However, bind()call()gets executed immediately, whilebind()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'