One of the best and worst things about JavaScript is that there's often multiple ways to solve a problem.
I'm about to launch a full reboot of my Vanilla JS Academy workshops, and one of the things I'm adding is a collection of Q&A articles and videos of common questions I get from students.
This one—"How do I know if I've found the best solution to a coding problem?"—comes up a lot!
Usually, one approach isn't any better than the other. They just have different benefits and tradeoffs.
For example, imagine you want to loop over an array of items and create an unordered list (ul
) from them.
let wizards = ['Merlin', 'Ursula', 'Morgana', 'Radagast'];
You can do that with a for...of
loop and string concatentation, like this…
let listItems = ''; for (let wizard of wizards) { listItems += `<li>${wizard}</li>`; } let list = `<ul>${listItems}</ul>`;
Or you could use the Array.prototype.map()
and Array.prototype.join()
methods, like this…
let listItems = wizards.map(function (wizard) { return `<li>${wizard}</li>`; }).join(''); let list = `<ul>${listItems}</ul>`;
Some developers like the brevity of using .map()
and .join()
. Others like the more explicit readability of using a for...of
loop.
Neither option is "right." They're just different. What's better for one developer maybe worse for another.
As a general rule of thumb, if your code is working and one approach isn't perceivably more performant than the other, choose the one that's easiest for you to read, understand, and maintain.
Is there a JavaScript or web development topic you'd like to learn more about? Hit reply to this email and let me know.
Cheers,
Chris
Want to share this with others or read it later? View it in a browser.
0 Komentar untuk "[Go Make Things] How do I know if I've found the best solution to a coding problem?"