JavaScript Best Practices
We've covered several introductory concepts for JavaScript programming in this course and how to debug your code. We'll review some coding guidelines and best practices you'll use as a JavaScript developer to ensure consistency, readability, security, and accessibility. Read this article to learn about some of the best practices for developing programs.
Strings
Use template literals
For inserting values into strings, use string literals.
Do this:
let myName = 'Chris'; console.log(`Hi! I'm ${myName}!`);
Not this:
let myName = 'Chris'; console.log('Hi! I\'m' + myName + '!');
Use textContent, not innerHTML
When inserting strings into DOM nodes, use Node.textContent
:
let text = 'Hello to all you good people'; const para = document.createElement('p'); para.textContent = text;
Not Element.innerHTML
let text = 'Hello to all you good people'; const para = document.createElement('p'); para.innerHTML = text;
textContent
is a lot more efficient, and less error-prone than innerHTML
.