Global Variables
In current code, the variables movieObj
, sum
, etc. are global. Global variables are bad and can create problems when the variable names collide with other developer's namespaces. This will be very difficult to debug in moderate-size projects.
See Why are global variables considered bad practice?
To make the variables and methods private, use Module pattern.
Naming Conventions
Use the descriptive variable names such that it'll give the idea of what it may contain, what is the purpose of it.
Example, the variable b
in the for...in
can be renamed to val
as it is the value of a key or movie
as the object stores the information of a movie.
Read Clean Code second chapter "Meaningful Names".
Overriding the prototype method
Always check if a particular method exists on the prototype. If it does not exists, then only add one. Also, regarding the name of method, I'll name the method as sum
instead of getSum
. Chances are, there will be method with same name and functionality in the future versions of ECMAScript and the code doesn't have to be changed.
if (!Array.prototype.sum) {
Array.prototype.sum = function () {
// Do something
};
}
for...in
vs Object.keys()
+ forEach
for...in
to iterate over object is slowerBenchmark. Use Object.keys()
to get the list of all keys in that object and use Array#forEach
on that array to iterate over it.
Object.keys(obj).forEach(function (key) {
// ...
});
this
inside method defined on prototype
this
inside the method on prototype refers to the variable on which the method is called. Example, when calling array.push
, this
inside the push()
will refer to the array
on which the method is called. So, there is no need to pass the array as parameter to the method.
Array.prototype.sum = function () {
console.log(this);
// Use `this` to refer to array
};
Bracket notation vs Dot notation
When the keys are known and are static and does not contain special characters, use the dot notation to access the value of that key in the object. Dot notation is faster and clear to read.
Instead of obj['moveName']
, use obj.moveName
.
See JavaScript property access: dot notation vs. brackets?
Typo
In the object, the keys for movie name has typo. It should be movieName
.
ECMAScript 2015
If the target environment support latest version of JavaScript, use the features provided by it.
Complete code:
if (!Array.prototype.sum) {
Array.prototype.sum = function () {
var sum = this.reduce(function (a, b) {
return a + b;
}, 0);
return sum / this.length;
};
}
(function () {
'use strict';
var movieObj = {
cat: {
movieName: 'Breath',
rating: [4, 5, 4, 3]
},
cat1: {
movieName: 'shallow',
rating: [5, 5, 5, 5, 4]
}
};
Object.keys(movieObj).forEach(function (key) {
var movie = movieObj[key];
if (movie.rating.sum() < 5) {
console.log(movie.movieName);
}
});
}());