Consistent Temporary Names
Normally, the variables should be descriptive and contain one or more words. But, this doesn’t necessarily apply to temporary variables. They can be as short as a single character.
Get Suresh Pattu’s stories in your inbox
Join Medium for free to get updates from this writer.
It is a good practice to use consistent names for your temporary variables that have the same kind of role. Here are a few examples that I tend use in my code
// $i for loop counters
for ($i = 0; $i < 100; $i++) {
// $j for the nested loop counters
for ($j = 0; $j < 100; $j++) {}
}
// $ret for return variables
function foo() {
$ret['bar'] = get_bar();
$ret['stuff'] = get_stuff();
return $ret;
}
// $k and $v in foreach
foreach($some_array as $k => $v) {}
// $q, $r and $d for mysql
$q = "SELECT * FROM table";
$r = mysql_query($q);
while ($d = mysql_fetch_assocr($r)) {}
// $fp for file pointers
$fp = fopen('file.txt', 'w');The == comparison operator always converts (to matching types) before comparison. The === operator forces comparison of values and type:
0 == ""; // true
1 == "1"; // true
1 == true; // true
0 === ""; // false
1 === "1"; // false
1 === true; // falsePrototype Chains
JavaScript gives us a built-in mechanism to share data across objects, called the prototype chain. When we access a property on an object, it can fulfill that request by delegating to some other object. We can use that and change our factory function so that each object it creates contains only the data unique to that particular object, and delegate all other property requests to a single, shared object.
var thingPrototype = {
f: function() {},
g: function() {}
};
function thing() {
var o = Object.create(thingPrototype);
o.x = 42;
o.y = 3.14;
return o;
}
var o = thing();In fact, this is such a common pattern that the language has built-in support for it. We don’t need to create our own shared object (the prototype object). Instead, a prototype object is created for us automatically alongside every function, and we can put our shared data there.
thing.prototype.f = function() {};
thing.prototype.g = function() {};
function thing() {
var o = Object.create(thing.prototype);
o.x = 42;
o.y = 3.14;
return o;
}
var o = thing();But there’s a drawback. This is going to result in some repetition. The first and last lines of the “thing” function are going to be repeated almost verbatim in every such delegating-to-prototype-factory-function.





