How are JavaScript objects used?

Hey guys, today I am writing about one of the scariest kinds of features in JavaScript objects or object-oriented programming. As we all know, objects are the most used data types in JavaScript programming and are no doubt the closest representation of real-world variables. For example if I want to buy a dress that looks somewhat like this:

image
image

I can easily explain that in terms of an object:

const dress = {
color: "Red",
fabric: "silk",
length: "100m",
size: "medium"
}

We already know that we can create classes out of these objects and manipulate them according to our program.

You can read about the basic concepts of object-oriented programming herehttps://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Classes_in_JavaScript.

However, in this shot, I will discuss a practical use-case/project where we will actually make use of the classes and methods inside the classes and learn how we can simplify our code using the OOP part of javascript. By the end of this shot, you’ll understand the practical approach of objects.

Creating a movie database application

We will now build a small Movies Database application that will allow us to create a list of movies, delete them, and display the entries (all of which can be done using classes and objects).

Implementing index.html

First, create a new index.html file. I will be using bootswatch and font awesome (for icons). The basic structure of our index file looks like this:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" />
<link rel="stylesheet" href="https://bootswatch.com/4/yeti/bootstrap.min.css" />
<link rel="stylesheet" href="/styles.css" />
<title>Movies Database App</title>
</head>
<body>
<div class="container mt-4">
<h1 class="display-4 text-center">
<i class="fas fa-video" style="color: blue;"></i> Movies<span class="text-primary">Database</span>List
</h1>
<form id="movie-form">
<div class="form-group">
<label for="title">Title</label>
<input type="text" id="title" class="form-control" />
</div>
<div class="form-group">
<label for="author">Director</label>
<input type="text" id="director" class="form-control" />
</div>
<div class="form-group">
<label for="isbn">Year</label>
<input type="text" id="year" class="form-control" />
</div>
<input type="submit" value="Add Movie" class="btn btn-primary btn-block" />
</form>
<table class="table table-striped mt-5">
<thead>
<tr>
<th>Title</th>
<th>Director</th>
<th>Year</th>
<th></th>
</tr>
</thead>
<tbody id="movie-list"></tbody>
</table>
</div>
<script src="/script.js"></script>
</body>
</html>

Implementing script.js

Once we are done with the index.html file, we will move to the script.js file and do all the JavaScript logic there.

First, we will create a Movie class that will enable us to add movies. Later on, this class will have a constructor function that will be used to define and initialize the objects and their features. This constructor will consist of a title, director, and the year that the movie was released:

class Movie {
constructor(title, director, year) {
this.title = title
this.director = director
this.year = year
}
}

To start with, we have created a defaultMovies array so that we have something to display before the user starts adding his/her records:

const defaultMovies = [
{
title: 'Jurassic Park',
director: 'John Doe',
year: '1990'
},
{
title: 'The Dead Pool',
director: 'Mathew Albison',
year: '2014'
}
]

Next, we will create a UI class where we will handle the display, adding, and deleting movies functions in the DOM:

class UI{
static displayMovies = () =>{
defaultMovies.forEach(movie=>UI.addMovieToList(movie))
}
static addMovieToList = (movie) => {
const list = document.getElementById('movie-list');
const row = document.createElement('tr')
row.innerHTML=`
<td>${movie.title}</td>
<td>${movie.director}</td>
<td>${movie.year}</td>
<td><a href="#" class="btn btn-danger btn-sm delete">X</a></td>`
list.appendChild(row)
}
static deleteMovie(movie){
if(movie.classList.contains('delete')){
movie.parentElement.parentElement.remove()
}
}
}
UI.displayMovies()

Now, we will deal with the ‘Add Movie’ button; when a user enters the input values and clicks the add button, the following addAMovie function will be called. This function will store the input values in their respective variables and instantiate a new Movie object that will add the movie object to the UI class:

// Event: Add a Movie
document.querySelector('#movie-form').addEventListener('submit', addAMovie, false)
function addAMovie(e) {
// prevent actual submission
e.preventDefault()
// Get Form Values
const title =document.querySelector('#title').value;
const director =document.querySelector('#director').value;
const year =document.querySelector('#year').value;
// Instantiate a new Book object
const movie = new Movie(title,director,year)
// Add book object to UI
UI.addMovieToList(movie)
UI.showAlert("Movie Added", 'success')
UI.clearFields();
}

Next, we have to take care of clearing the fields after a user has added the record; this can be done by defining a clearFields method in the UI class:

static clearFields(){
document.querySelector('#title').value="";
document.querySelector('#director').value="";
document.querySelector('#year').value="";
}

We will show alert messages on adding, deleting, and invalid input values through a showAlert method in the UI class that will take two arguments as input (the message to be shown based upon user’s action and the class to be added on the alert).

static showAlert(message,className){
const div = document.createElement('div')
div.innerText = message
div.className = `alert alert-${className}`
document.getElementById('movie-form').prepend(div)
setTimeout(()=>document.querySelector('.alert').remove(),2000)
}

We can also add a validation in the addAMovie method if a user enters any record with empty input values:

if(!title || !director || !year){
UI.showAlert("Please enter correct details", "danger")
return
}

This brings us to the end of our simple application that demonstrates the use of classes and methods in an OOP manner.I hope you will find this application useful.

Happing coding and have a nice day!

Disclaimer: I know this may not be the best approach for this problem. However, the purpose here is only to demonstrate the use of objects and classes; that’s why I have picked up this solution. You are always welcome to come up with your ideas.

Free Resources