Saeid Mohadjer

Frontend Developer in Freiburg, Germany

Tips on Frontend Development

Finding out whether an element is empty or not

Do not use jQuery's $(element).is(':empty') to detect whether an element is empty or not, because if your element contains white space or HTML comments it wouldn't be considered empty. Instead use:

if ($(element).children().length > 0) {
	console.log('Element is not empty');
}

Use reverse looping to remove items from an array

var myArr = [1, 2, 2, 3, 4];
var i = myArr.length;
while (i--) {
    if (myArr[i] === 2) {
        myArr.splice(i, 1);
    }
}
// myArr will be [1, 3, 4]

// A normal for loop will fail to remove all items equal to 2 from array!
for (var i=0; i < myArr.length; i++) {
    if (myArr[i] === 2) {
        myArr.splice(i, 1);
    }
}
// myArr will be [1, 2, 3, 4]

Copying arrays of objects by value rather than by reference

If an array contains no objects, making a clone is as simple as: var clonedArray = myArray.slice(0);, but this will create a shallow clone meaning that changing object in one array would affect the other array. If you wish to make changes to new array that should not affect the original array (for example by using array.filter() method) and your array objects do not contain functions, you can create a deep clone using JSON methods:

var clonedArray = JSON.parse(JSON.stringify(oldArray));

Or you can use jQuery var clonedArray = $.extend(true, [], oldArray); to deep clone your array before making changes to it.

//data is an array of objects [{name: 'Germany', isocode: 'de'}, {name: 'France', isocode: 'fr'}, ...]
getCountryData: function(data, isocode) {
	var self = this;
	var companies = data.companies.filter(function(item) {
		return item.isocode.toLowerCase() === isocode;
	});
	var temp = $.extend(true, [], companies); // we must deep copy array since it contains objects
	return temp;
}

Removing duplicate items from an array

https://stackoverflow.com/a/39886008/884177

//remove duplicate coordinates
var myArr = [{lat: 23, lng:31}, {lat:12, lng:21}, {lat:23, lng:31}, {lat:23, lng:31}];
var occurances = [];
var uniqueLocations = myArr.filter(function(item) {
	if (occurances.indexOf(item.lat + item.lng) !== -1) {
		return false;
	}
	occurances.push(item.lat + item.lng);
	return true;
});

Iterating objects in Handlebars

It is possible to iterate objects in handlebars templates. In below example countries is an object of key:value pairs where key is letter of alphabet and value is an array of countries whose name starts with that letter. @key returns key and “this” returns value for that key. It’s possible to use “../“ to access parent properties.

<dl>
	{{#each countries}}
		<dt>{{toUpperCase @key}}</dt>
		<dd>
			<ul>
			{{#each this}}
				<li><a href="{{../../url}}?country="{{country_name}}>{{country_name}}</a></li>
			{{/each}}
			</ul>
		</dd>
	{{/each}}
</dl>

Handlebars.registerHelper('toUpperCase', function(str) {
	return str.toUpperCase();
});

Useful one-liners!

myArray.indexOf(arrayItem); //retruns -1 if item is not found in array
myArray.filter(function(arrayItem) { return condition; }); // returns new array with array items that pass the condition

myString.charAt(0); //returns first letter of string
myString.toUpperCase();
myString.toLowerCase();
myString = originalString.replace(‘hello’, ‘world’); //replacing something that occurs only once
myString = oldString.replace(/,/g, '-‘); //replacing all occurrences of comma with a dash using regex
myString = oldString.split(‘,’).join(‘-‘); //replacing all occurrences of comma with a dash without using regex

delete myObject[propertyName]; //to remove a property from an object

{{units.[0].location}} // To access an array item by index in Handlebars template