I'll try to.
Code:
// This function accepts two arguments: 'o' an HTML element object and 'p' a string which represents a css property.
Using a variable of 'o' for an element can be confusing, and likewise 'p' for the css property. You don't need that comment when you use appropriately standard function variables that inform the person reading the code from the name of the variables themself.
For example:
Code javascript:
function style(el, prop) {
Code:
// It returns the value of the css property 'p' for element 'o'
Giving the function a more expressive name helps to remove the need for the above comment, such as getComputedStyle, or getCssValue
Code javascript:
function getCssValue(el, prop) {
Code:
// E.g. if 'o' is 'div#zoomout' and 'p' is 'display', it will return the current value of the display property for div#zoomout
Using a named variable to contain the value removed the need for the above comment
Code javascript:
var cssValue;
if (...) {
cssValue = ...;
} else {
cssValue = ...;
}
return cssValue;
Code:
// Get a reference to the element whose width we want to know
The above comment repeats in English what the code is already saying.
Do not write these sorts of comments. They are a waste and don't help to serve any explanatory purpose.
How could the code be improved so that the code is easily understandable, and comments don't end up serving a useless purpose?
Code javascript:
// The following code is an example of how to get the width of an element when the element may be potentially hidden.
function getCssValue(el, prop) {
var value = '';
if (el.currentStyle) {
value = el.currentStyle[prop.replace(/-/g, '')];
} else {
value = document.defaultView.getComputedStyle(el, null).getPropertyValue(prop.toLowerCase());
}
return value;
}
function getElementWidth(el) {
// The width of an element cannot be obtained from a potentially hidden element.
// We can get the width though by setting its display to block, after which we return its display back to what it initially had.
var originalDisplay = getCssValue(el, 'display'),
width;
el.style.display = 'block';
width = el.offsetWidth;
el.style.display = originalDisplay;
return width;
}
var el = document.getElementById('zoomout'),
width = getElementWidth(el);
alert(width);
Try to use comments to explain why things are happening. The use of good variable names go a long way to preventing the need for other wasteful comments. Commonly comments are used to explain about bad code. In such cases, fixing the code to remove the need for such comments and the programmers attention is no longer wasted by such comments, so that he can focus on the code instead.
Bookmarks