Skip to main content Accessibility Feedback

13 super rad web dev tricks you don't know about (but should)

Yesterday, I shared one of my talks from the State of the Browser conference on how to create your first Web Component in five minutes or less.

Today, I wanted to share another one of my talks: a collection of my favorite web dev tips and tricks.

If you’d rather read, here’s the transcript version…

Hi, Chris Ferdinandi, the VanillaJS guy here with one last speedy dev insight.

Here are my 13 favorite web developer tricks.

Tip 1. Event Delegation

If you need to listen for the same event on lots of elements, you can attach your listener to a parent element to catch all of them, and then filter out events that aren’t on the element that you care about.

document.addEventListener('click', function (event) {

	// If the clicked element doesn't have the .click class, ignore it
	if (!event.target.matches('.click')) return;

	console.log('You clicked a button');

});

Not only is this easier to manage as a developer, but it’s actually better for performance.

Tip 2. early return pattern.

Lots of nested if statements can quickly become unruly and hard to read.

As an alternative, you can check for the opposite of the desired state by prefacing your test with the bang or exclamation point operator. Then you run the return operator when that check returns true.

// ๐Ÿฆ„ Early return pattern
function handleClick (event) {

	// Make sure clicked element has the .save-data class
	if (!event.target.matches('.save-data')) return;

	// Get the value of the [data-id] attribute
	let id = event.target.getAttribute('data-id');
	if (!id) return;

	// Get the user token from localStorage
	let token = localStorage.getItem('token');
	if (!token) return;

	// Save the ID to localStorage
	localStorage.setItem(`${token}_${id}`, true);

}

For bigger functions, this results in code with far fewer indents and an easier to read structure.

Tip 3. Multiple Selectors

For methods that accept CSS selectors, you can pass in multiple selectors as a comma-separated string, just like you’d write them in CSS.

// Get all matches
let all = document.querySelectorAll('.tuna, .turkey, .mayo');

Tip 4. Data Attribute Selectors

Data attributes make fantastic selectors for your custom JavaScript and help prevent collisions with CSS classes.

You can use these attributes as standalone selectors.

// Target elements by selector
let form = document.querySelector('[data-submit="login"]');
form.addEventListener('submit', function (event) {
	event.preventDefault();
	alert('You logged in!');
});

You can also use this to make event delegation easier in bigger apps where you have different functions that run for the same event.

With this approach, you would store all of your event handlers in an object, and then you can use the handler name as the value of the data attribute.

// Use event delegation to get the callback function
let handlers = {

	sayHi () {
		alert('๐ŸŽ‰ Hello!');
	},

	sayBye () {
		alert('๐Ÿ‘‹ See you next time...');
	}

};

In my event listener, I can get the value of that attribute, and then I can pass that value in to run the matching function.

document.addEventListener('click', function (event) {

	// Get the function to run
	let fn = event.target.getAttribute('data-click');
	if (!fn) return;

	// Run the function
	handlers[fn](event);

});

Tip 5. Converting an object into a query string

To convert an object into a query string, you can pass it into the new URLSearchParams() constructor, and then run the toString() method on it.

let merlin = {
	job: 'Wizard',
	tool: 'Wand',
	age: 142,
	signatureSpell: 'Dancing Teacups'
};

let queryString = new URLSearchParams(merlin).toString();

Tip 6. Removing duplicates from an array

The Set object is a lot like an array, but each item in it must be unique.

If you pass an array of duplicate values into the new Set() constructor, and then convert the returned set object back into an array, you get a new array with all of the duplicates removed.

let wizards = [
	'Merlin',
	'Ursula',
	'Gandalf',
	'Merlin',
	'Morgana',
	'Radagast',
	'Ursula'
];

let deduped = Array.from(new Set(wizards));

Tip 7. Generating Random IDs

The crypto.randomUUID() method generates a random, cryptographically secure unique ID.

let id = crypto.randomUUID();

Tip 8. True Type Checking

Because so many JavaScript things are actually objects, the type of operator is unreliable for accurate type checking.

For example, plain objects, arrays, dates, regex patterns, and null all return object with the typeof operator.

For more accurate type checking, call the Object.prototype.toString() method on the item you want to check.

The returned value will start with [object followed by the actual object type.

// returns [object Array]
Object.prototype.toString.call([]);

Tip 9. Numeric separators

Big numbers can be difficult to read and work with in JavaScript and numbers cannot include thousand separators like commas but in modern JavaScript you can use underscores to break big numbers into smaller parts.

// Numeric separators make big numbers easier to read
let num = 1_234_567_890_987_654_321;

Tip 10. Looping over objects

A for in loop is often used to loop over objects.

To get the value of a particular key, you need to use bracket notation to get that key value on the object you’re looping over.

A cleaner way to loop over objects is by pairing the Object.entries() method, which converts an object into an array of key value pairs, with a for...of loop and array destructuring.

let merlin = {
	job: 'Wizard',
	tool: 'Wand',
	age: 142,
	signatureSpell: 'Dancing Teacups'
};

// ๐Ÿฆ„ The new way!
for (let [key, value] of Object.entries(merlin)) {
	console.log(key);
	console.log(value);
}

Tip 11. Object property shorthands

In modern JavaScript, if there is an existing variable with the same name as the property that you’re defining in the object, you can just use the variable name for the property and its value will be automatically assigned.

let name = 'Merlin';
let tool = 'wand';
let age = 142;

// ๐Ÿฆ„ The new way!
let obj2 = {name, tool, age};

Tip 12. Simpler Boolean Returns

A lot of my students will write code that explicitly returns true or false based on some condition.

// The verbose way
function isBig (num) {
	if (num > 10) {
		return true;
	} else {
		return false;
	}
}

And there’s nothing wrong with that. It totally works.

But if the conditional check that you’re running returns a Boolean itself, you can return the check itself rather than an explicit true false value because the check you’re running is doing that already.

// ๐Ÿฆ„ A simpler way
function isBig (num) {
	return num > 10;
}

And finally,

Tip number 13. ๐Ÿ™ˆ

The correct way to pronounce “Gif” is “Jif.”

You can access the source code from this talk and dig deeper into vanilla JavaScript over at gomakethings.com/sotb.