JavaScript is partly an object-oriented language.
To learn JavaScript, we got to learn the object-oriented parts of JavaScript.
In this article, we’ll look at some basic coding and design patterns.
Coding and Design Patterns
To organize our code in ways that we can work with them easily, we got to follow some patterns that allow that to happen.
Many people have thought of this problem, so we can follow existing patterns mostly.
Coding patterns are some best practices we can follow to improve our code.
Design patterns are language-independent patterns that are popularized by the Gang of Four book.
Separating Behavior
The building blocks of a web page includes HTML, CSS, and JavaScript code.
The content should be in the HTML code.
They have the markup to describe the meaning of the content.
For instance, we use ul
for lists and li
for list items and so on.
HTML code should be free from any formatting elements.
Visual formatting belongs to the presentation layer and should be achieved with CSS.
The style
attribute shouldn’t be used for formatting.
Presentational HTML tags also shouldn’t be used.
Tags should be used form their meaning.
So section
for dividing the text into sections, aside
for a sidebar etc. should be used instead of div
for everything.
Presentation
To make our pages presentable we can reset the browser defaults to be the same across all browsers.
Popular CSS frameworks like Bootstrap will do this.
Behavior
Any dynamic behavior should be written in the JavaScript code.
The JavaScript should be in scripts that are in external files in script tags.Inline attributes like onclick
, onmouseover
, etc. shouldn’t be used.
We should minimize the number of script tags so less JavaScript code has to be loaded.
Inline event handlers should be avoided to keep JavaScript code outside of HTML code.
CSS expressions shouldn’t ve used to keep compatibility.
To separate behavior, we can separate our form submission code from the form itself.
For example, we can write the following HTML:
<body>
<form id="nameForm" method="post" action="server.php">
<fieldset>
<legend>name</legend>
<input name="name" id="name" type="text" />
<input type="submit" />
</fieldset>
</form>
<script src="script.js"></script>
</body>
to create a form.
Then we can listen to the submit event in script.js
:
const nameForm = document.querySelector('#nameForm');
nameForm.addEventListener('submit', (e) => {
const el = document.getElementById('name');
if (!el.value) {
e.preventDefault();
alert('Please enter a name');
}
});
We get the form with querySelector
.
Then we listen to the submit
event with addEventListener
.
In the event handler, we get the name
field by its ID.
If there’s no value, we stop the submission with preventDefault()
.
And then we display an alert.
Conclusion
We should separate content, styling, and dynamic behavior in our code.