Javascript ES6 refactoring

Published: Tuesday, Nov 1, 2016 Last modified: Monday, May 27, 2024

Find loop

for (var i = 0; i < this.items.length; i++) {
	   if (this.$route.params.uuid == this.items[i].uuid) {
			   return this.items[i]

Can be written like this:

return this.items.find((item) => item.uuid === this.$route.params.uuid)

If you need to several items, use filter:

return this.items.filter(item => item.status === status)

As used in this Vue2 example

Arrow functions

If you ever find yourself writing code that looks like var that = this using arrow functions gets rid of that problem!

However if that still doesn’t work, you might need to bind this back in, like so:

fetch(url, obj)
	.then(function(res) {
			return res.json();
.then(function(resJson) {
		this.video_options = resJson
		}.bind(this)).catch(function (err) {


I find constructing Promises still a little tricky, but note that the Fetch API supports them natively.

Way better than XMLHttpRequest callback hell, especially for catching errors / writing robust code in poor networking situations which is all too common.