JavaScript rules
Use enums
Use Object.freeze to create enums:
const Month = Object.freeze({
January: 1,
Feb: 2,
March: 3
});
if (month === Month.January) {
...
}You can also use enums for text values:
const UserRole = Object.freeze({
User: 'user',
Admin: 'admin'
});
if (roles.includes(UserRole.Admin)) {
...
}Use strict equality operators
Always use the strict equality operators (=== and !==) instead of regular equality operators (== and !=).
The only exception - you can use val != null to check for both null and undefined.
Truthy and Falsy values
Read these resources to understand what are Truthy and Falsy:
What are Truthy and Falsy values in JavaScript
Is there a standard function to check for null, undefined, or blank variables?
Always use simple truthy/falsy checks to check whether a variable has a value or not, regardless of its type:
if (val) {
...
}
if (!val) {
...
}To check an array for values, use:
if (arr?.length) {
...
}Templaters
If you have to generate HTML with JavaScript, be sure to use a templater like handlebars.js.
Correct:
<script id="actions-template" type="text/x-handlebars-template">
<div class="btn-group">
<a class="btn" href="@Url.Action("Edit", "Participant")/{{Id}}" title="Manage">
<i class="icon-pencil"></i>
</a>
<a class="btn" data-participant-id="{{Id}}" href="#" title="Deactivate">
{{#if isActive}}
<i class="icon-ban"></i>
{{else}}
<i class="icon-ok"></i>
{{/if}}
</a>
</div>
</script>
<script type="text/javascript">
var actionsTemplate = Handlebars.compile($("#actions-template").html());
function getActions(data)
{
return actionsTemplate({ id: data.Id, isActive: data.IsActive });
}
</script>Wrong:
function getActions(data)
{
var html = "<div class=\"btn-group\">";
html += "<a class=\"btn\" href=\"@Url.Action("Edit", "Participant")/" + data.Id + "\" title=\"Manage\"><i class=\"icon-pencil\"></i></a>";
html += "<a class=\"btn";
var icon;
if (data.IsActive) {
icon = "ban";
}
else {
icon = "ok";
}
html += "\" data-participant-id=\"" + data.Id + "\" href=\"#\" title=\"Deactivate\"><i class=\"icon-";
html += icon;
html += "-circle\"></i></a>";
html += "</div>";
return html;
}At the same time, templaters are overkill if you want to generate a very simple and short HTML.