Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Difference between findPos("divThis") and findPos(divThis)

27 views
Skip to first unread message

Cal Who

unread,
Nov 13, 2011, 9:51:51 AM11/13/11
to
I find that either of the two approches below work.I'd appreciate getting a
little insight into what is going on and the good and bad aspects of each
approach.Thanksfunction findPos(obj) {
var w = document.getElementById(obj).offsetWidth;
var h = document.getElementById(obj).offsetHeight;called with:
findPos("divThis")Orfunction findPos(obj) {
var w = obj.offsetWidth;
var h = obj.offsetHeight;called with: findPos(divThis)


Thomas 'PointedEars' Lahn

unread,
Nov 13, 2011, 12:25:28 PM11/13/11
to
Your OP was hard to read and not even syntactically valid; I have
reformatted it and completed it. Please take more care next time.

Both approaches work in Internet Explorer and perhaps elsewhere in *Quirks
Mode*. That is so because MSHTML, probably to make DOM scripting easier,
elements with IDs are explicitly represented in the DOM by properties of the
same name of the object referred to by `window'.

That object (`window' object for short) is in the scope chain. So if you
use the `divThis' identifier and no other object in the scope chain has a
property of that name, it will be resolved to the property of the `window'
object. The result is a reference to the DOM element object which
represents the element.

You should not rely on this proprietary behavior, and you should avoid
triggering Quirks Mode.

That findPos() function call really is pointless, as the local variables
will not be visible outside the function here. So unless you want to
support IE/MSHTML 4 and NN 4, for which you would need a wrapper function,
KISS:

var o = document.getElementById("divThis");
var w = o.offsetWidth;
var h = o.offsetHeight;

But do not rely on that either; read the discussion about element dimensions
three days ago. (In general: search, read, post.)

BTW, findPos() does not what its name says.


PointedEars
--
Anyone who slaps a 'this page is best viewed with Browser X' label on
a Web page appears to be yearning for the bad old days, before the Web,
when you had very little chance of reading a document written on another
computer, another word processor, or another network. -- Tim Berners-Lee

Cal Who

unread,
Nov 13, 2011, 1:58:03 PM11/13/11
to

"Thomas 'PointedEars' Lahn" <Point...@web.de> wrote in message
news:4775241.y...@PointedEars.de...
> Cal Who wrote:
>
>> I find that either of the two approches below work.I'd appreciate getting
>> a little insight into what is going on and the good and bad aspects of
>> each approach. Thanks
>>
>> function findPos(obj)
>> {
>> var w = document.getElementById(obj).offsetWidth;
>> var h = document.getElementById(obj).offsetHeight;
...
>>
>> called with: findPos("divThis")
>>
>> Or
>>
>> function findPos(obj)
>> {
>> var w = obj.offsetWidth;
>> var h = obj.offsetHeight;
...
>
>> called with: findPos(divThis)
>
> Your OP was hard to read and not even syntactically valid; I have
> reformatted it and completed it.

Also, I should have included the "..." that (I just added) to make cleared
that there was more code.

> Both approaches work in Internet Explorer and perhaps elsewhere in *Quirks
> Mode*. That is so because MSHTML, probably to make DOM scripting easier,
> elements with IDs are explicitly represented in the DOM by properties of
> the
> same name of the object referred to by `window'.
>
> That object (`window' object for short) is in the scope chain. So if you
> use the `divThis' identifier and no other object in the scope chain has a
> property of that name, it will be resolved to the property of the `window'
> object. The result is a reference to the DOM element object which
> represents the element.

I don't have the backgroung to understand the above paragraph.
Is the first approch (var w = document.getElementById(obj).offsetWidth) the
better one?

>
> You should not rely on this proprietary behavior, and you should avoid
> triggering Quirks Mode.
>
> That findPos() function call really is pointless, as the local variables
> will not be visible outside the function here. So unless you want to
> support IE/MSHTML 4 and NN 4, for which you would need a wrapper function,
> KISS:
>
> var o = document.getElementById("divThis");
> var w = o.offsetWidth;
> var h = o.offsetHeight;
>
> But do not rely on that either; read the discussion about element
> dimensions
> three days ago. (In general: search, read, post.)

I did search. That's where I got the code I asked about.

If you are refering to: "How to Determine Positions of Elements"

I had read it and in fact have copied it and pasted into my file for later
testing, but he did not, I don't believe, mentioned this method which is
simpler and since I don't know why I should not rely on it I thought I'd try
it.

>
> BTW, findPos() does not what its name says.

Good catch but I'm still developing " findPosAndSize"


Thanks

Thomas 'PointedEars' Lahn

unread,
Nov 13, 2011, 2:26:47 PM11/13/11
to
Cal Who wrote:

> "Thomas 'PointedEars' Lahn" wrote […]:
>> Your OP was hard to read and not even syntactically valid; I have
>> reformatted it and completed it.
>
> Also, I should have included the "..." that (I just added) to make cleared
> that there was more code.

ACK.

>> Both approaches work in Internet Explorer and perhaps elsewhere in
>> *Quirks Mode*. That is so because MSHTML, probably to make DOM scripting
>> easier, elements with IDs are explicitly represented in the DOM by
>> properties of the same name of the object referred to by `window'.
>>
>> That object (`window' object for short) is in the scope chain. So if you
>> use the `divThis' identifier and no other object in the scope chain has a
>> property of that name, it will be resolved to the property of the
>> `window' object. The result is a reference to the DOM element object
>> which represents the element.
>
> I don't have the backgroung to understand the above paragraph.

I will answer specific, *smart* questions you may have. (So do not ask,
for example, "What is a scope chain?", unless you want a "STFW" answer.)

<http://www.catb.org/~esr/faqs/smart-questions.html>

But I will still ignore you if you (continue to) post with an invalid
From/Reply-To header field value. Usenet can only work if communication
works both ways.

> Is the first approch (var w = document.getElementById(obj).offsetWidth)
> the better one?

Yes and no. It is the better one if you pass the element's ID string for
`obj'. It is not better if you call document.getElementById(obj) twice in
the process. There are also cases where you do not need to call
document.getElementById(); in that case it would be better not to call it.

> If you are refering to: "How to Determine Positions of Elements"

I was referring to the thread started with
<news:bd12b66f-33f5-43d2...@n14g2000vbn.googlegroups.com>,
Subject "David Mark's Javascript Tip Du Jour - Volume #1 - Tip #1234 - How
to Measure Element Dimensions", which is what your posted code does.

> I had read it and in fact have copied it and pasted into my file for later
> testing, but he did not, I don't believe, mentioned this method which is
> simpler and since I don't know why I should not rely on it I thought I'd
> try it.

Your posted code has nothing to do with the posting you are referring to.


Please trim your quotes to the relevant minimum next time.

<http://jibbering.com/faq/notes/posting>

HTH

PointedEars
--
Prototype.js was written by people who don't know javascript for people
who don't know javascript. People who don't know javascript are not
the best source of advice on designing systems that use javascript.
-- Richard Cornford, cljs, <f806at$ail$1$8300...@news.demon.co.uk>

Cal Who

unread,
Nov 13, 2011, 3:04:48 PM11/13/11
to
>
> But I will still ignore you if you (continue to) post with an invalid
> From/Reply-To header field value. Usenet can only work if communication
> works both ways.

I have no idea what it is about. I use IE Express and reply with "Reply
Group"
Do I have something set up wrong?
'
>
>> Is the first approch (var w = document.getElementById(obj).offsetWidth)
>> the better one?
>
> Yes and no. It is the better one if you pass the element's ID string for
> `obj'. It is not better if you call document.getElementById(obj) twice in
> the process. There are also cases where you do not need to call
> document.getElementById(); in that case it would be better not to call it.
>

That's what I'll do then.

Thanks


J.R.

unread,
Nov 13, 2011, 3:55:32 PM11/13/11
to
I always use obj as a reference to an element of the DOM. But I admit
there are cases in which you would like to receive either a string or an
element reference as the function's argument. In this case, try this code:

function getOuterDimensions(obj) {
var el = (typeof obj == 'string') ? document.getElementById(obj) :
obj,
w = el.offsetWidth;
h = el.offsetHeight;
...

}

Please, have a look at the post called "David Mark's Javascript Tip Du
Jour - Volume #1 - Tip #1234 - How to Measure Element Dimensions".

--
Joao Rodrigues (J.R.)

J.R.

unread,
Nov 13, 2011, 3:59:48 PM11/13/11
to
Correcting a typo:

var el = (typeof obj == 'string') ? document.getElementById(obj) :
obj,
w = el.offsetWidth, // , instead of ;
h = el.offsetHeight;

Cal Who

unread,
Nov 13, 2011, 5:10:07 PM11/13/11
to
>
> var el = (typeof obj == 'string') ? document.getElementById(obj) :
> obj,
> w = el.offsetWidth, // , instead of ;
> h = el.offsetHeight;
>
That's neat.

Except for the commas!

I looked up comma operator but am still confused.

Wouldn't this be OK (better?)

var el = (typeof obj == 'string') ? document.getElementById(obj) : obj;

J.R.

unread,
Nov 13, 2011, 5:49:25 PM11/13/11
to
No, because the ";" marks the end of the variable declaration list. In
the above code, you are indeed creating an implied global variable
called h, instead of creating a private variable in the function scope.

it is one of the JavaScript best practices to declare all of the
variables used in a function at the top of the function body. You may
have many variables separated by commas, e.g

var el = ...,
h = ...,
w = ...,
i, j, len, ..., z;

You must not use multiple var statements such as:
var el;
var h = ...;
var z;

--
Joao Rodrigues (J.R.)

Cal Who

unread,
Nov 13, 2011, 8:00:36 PM11/13/11
to

"J.R." <group...@yahoo.com.br> wrote in message
news:j9phhk$s3i$1...@speranza.aioe.org...
Thanks a lot


Denis McMahon

unread,
Nov 13, 2011, 9:37:38 PM11/13/11
to
On Sun, 13 Nov 2011 20:49:25 -0200, J.R. wrote:

> it is one of the JavaScript best practices to declare all of the
> variables used in a function at the top of the function body. You may
> have many variables separated by commas, e.g

> var el = ...,
> h = ...,
> w = ...,
> i, j, len, ..., z;

> You must not use multiple var statements such as:
> var el;
> var h = ...;
> var z;

Rubbish.

You can use as many var statements as you like. Nothing in the standards
or the implementation prevents this, so "must not" is incorrect.

Some people think all variables should be declared in a single statement.
Some people use a different statement for each type of variable, where
type is the sort of data that it will be used to hold (array, string,
integer, float, object etc).
Some people just use one variable per var.

These are all permitted by the various standards, and they all work.
There is no reason that you "must" or "must not" do any of these.

Also, "best practice" is invariably "in the opinion of the author of the
website / book / blog / whatever" that said example of best practice
appears in. As a matter of interest, what's your reference for "best
practice"? If I write a book or start a blog called "Javascript - Best
Practice" does that make it true?

Rgds

Denis McMahon

J.R.

unread,
Nov 14, 2011, 12:14:20 AM11/14/11
to
On 14/11/2011 00:37, Denis McMahon wrote:
> On Sun, 13 Nov 2011 20:49:25 -0200, J.R. wrote:
>
>> it is one of the JavaScript best practices to declare all of the
>> variables used in a function at the top of the function body. You may
>> have many variables separated by commas, e.g
>
>> var el = ...,
>> h = ...,
>> w = ...,
>> i, j, len, ..., z;
>
>> You must not use multiple var statements such as:
>> var el;
>> var h = ...;
>> var z;
>
> Rubbish.
>
> You can use as many var statements as you like. Nothing in the standards
> or the implementation prevents this, so "must not" is incorrect.

"must not" was exaggerated on purpose, because using many var statements
is an antipattern in JavaScript.

> Some people think all variables should be declared in a single statement.
> Some people use a different statement for each type of variable, where
> type is the sort of data that it will be used to hold (array, string,
> integer, float, object etc).
> Some people just use one variable per var.

The advantages of using the Single var Pattern at the top of your
functions are:
- there's a single place to look for all the local variables needed by
the function;
- prevention of logical errors when a variable is used before it’s defined;
- Helps you remember to declare variables and therefore minimize globals;
- only one var statement means less code to type and a reduction in the
file size.


> These are all permitted by the various standards, and they all work.
> There is no reason that you "must" or "must not" do any of these.
>
>
> Also, "best practice" is invariably "in the opinion of the author of the
> website / book / blog / whatever" that said example of best practice
> appears in.

There are patterns in any programming language usually adopted by
programmers as "best coding practices". And it happens to other fields
of study too. See <http://en.wikipedia.org/wiki/Best_Coding_Practices>

If you get a bunch of authors (books, blogs, etc.) that state the same
"best practices" in any programming language, then you can bet who is
wrong or right...

> As a matter of interest, what's your reference for "best
> practice"? If I write a book or start a blog called "Javascript - Best
> Practice" does that make it true?

No, it doesn't, although I know you're a very experienced and smart
programmer. However, if you published some evidence such as performance
tests, etc., then you could state that some practice should be either
considered a good one or avoided altogether.

--
Joao Rodrigues (J.R.)

Thomas 'PointedEars' Lahn

unread,
Nov 14, 2011, 7:00:53 AM11/14/11
to
Cal Who wrote:

> >
>> But I will still ignore you if you (continue to) post with an invalid
>> From/Reply-To header field value. Usenet can only work if communication
>> works both ways.
>
> I have no idea what it is about. I use IE Express

You mean _Outlook_ Express, as it says in the `X-Newsreader' header field of
your postings [1].

> and reply with "Reply Group"
> Do I have something set up wrong?
> '

Yes. One cannot send e-mail to your sender (`From') "address" (which
therefore isn't one). This violates NetNews/Internet standards and
disregards Netiquette (network etiquette).

(And a comparably minor thing: There is a leading space in your "name",
which should be your real name.)


F'up2 poster (i. e., please reply by e-mail *only*; check headers before you
send, as your outdated program has a bug there – by default it sends to the
newsgroup, too [2]. TIA.)

PointedEars
___________
[1]
<http://email.about.com/od/outlookexpresssourceview/qt/Display_all_Header_Lines_Windows_Live_Mail_Outlook_Express.htm>
[2] <http://insideoe.com/>

Thomas 'PointedEars' Lahn

unread,
Nov 14, 2011, 7:15:55 AM11/14/11
to
J.R. wrote:

> On 13/11/2011 20:10, Cal Who wrote:
>>>
>>> var el = (typeof obj == 'string') ? document.getElementById(obj) :
>>> obj,
>>> w = el.offsetWidth, // , instead of ;
>>> h = el.offsetHeight;
>>>
>> That's neat.
>>
>> Except for the commas!
>>
>> I looked up comma operator but am still confused.
>>
>> Wouldn't this be OK (better?)
>>
>> var el = (typeof obj == 'string') ? document.getElementById(obj) : obj;
>> w = el.offsetWidth ;
>> h = el.offsetHeight;
>> ...
>>
>
> No, because the ";" marks the end of the variable declaration list. In
> the above code, you are indeed creating an implied global variable
> called h,

No, it creates, if it succeeds (and does not throw an exception, as observed
in some instances with MSHTML before, and required in ECMAScript Ed. 5
strict mode), a property with that name of the ECMAScript Global object or
overwrites a property with that name of an object in the scope chain.

> instead of creating a private variable in the function scope.

The proper terminology here is "_local_ variable", not what you wrote.
Visibility modifiers do not exist in these implementations; privacy can
only be achieved implicitly, through closures. So far there is no closure
in that code regarding those variables.

> it is one of the JavaScript best practices to declare all of the
> variables used in a function at the top of the function body. You may
> have many variables separated by commas, e.g
>
> var el = ...,
> h = ...,
> w = ...,
> i, j, len, ..., z;
>
> You must not use multiple var statements such as:
> var el;
> var h = ...;
> var z;

Wrong. In fact, it turns out that syntactically *correct*, adjacent `var'
statements work better with editors capable of refactoring, such as Eclipse
JSDT. And they help to avoid the problem that you encountered, because it
would likely be a syntax error if you mistyped the semicolon, and automatic
semicolon insertion would take place if you forgot to type the semicolon at
all.

Cal Who

unread,
Nov 14, 2011, 8:48:09 AM11/14/11
to

"Denis McMahon" <denismf...@gmail.com> wrote in message
news:4ec07ef1$0$28711$a826...@newsreader.readnews.com...
Thanks


Denis McMahon

unread,
Nov 14, 2011, 9:03:29 AM11/14/11
to
On Mon, 14 Nov 2011 03:14:20 -0200, J.R. wrote:

> The advantages of using the Single var Pattern at the top of your
> functions are:

I'm not objecting to the suggestion that best practice includes defining
all your variables with var statements at the start of a function. I
agree that this is indeed best practice.

I am, however, objecting to (a) your assertion that it "must" be done, or
(b) that best practice requires the use of a single var statement.

Rgds

Denis McMahon

Thomas 'PointedEars' Lahn

unread,
Nov 14, 2011, 9:04:54 AM11/14/11
to
J.R. wrote:

> On 14/11/2011 00:37, Denis McMahon wrote:
>> On Sun, 13 Nov 2011 20:49:25 -0200, J.R. wrote:
>>> it is one of the JavaScript best practices to declare all of the
>>> variables used in a function at the top of the function body. You may
>>> have many variables separated by commas, e.g
>>
>>> var el = ...,
>>> h = ...,
>>> w = ...,
>>> i, j, len, ..., z;
>>
>>> You must not use multiple var statements such as:
>>> var el;
>>> var h = ...;
>>> var z;
>>
>> Rubbish.
>>
>> You can use as many var statements as you like. Nothing in the standards
>> or the implementation prevents this, so "must not" is incorrect.
>
> "must not" was exaggerated on purpose, because using many var statements
> is an antipattern in JavaScript.

In your humble opinion (which may not even be your opinion but that of the
author of some botched book you read instead, and now you think you know the
language and its "best practices").

>> Some people think all variables should be declared in a single statement.
>> Some people use a different statement for each type of variable, where
>> type is the sort of data that it will be used to hold (array, string,
>> integer, float, object etc).
>> Some people just use one variable per var.
>
> The advantages of using the Single var Pattern at the top of your
> functions are:

You are confusing two concepts here.

> - there's a single place to look for all the local variables needed by
> the function;

The comma operator does not help with this.

> - prevention of logical errors when a variable is used before it’s
> defined;

The comma operator does not help with this.

> - Helps you remember to declare variables and therefore minimize
> globals;

The comma …

> - only one var statement means less code to type and a reduction
> in the file size.

Sometimes. Because for readable code, you will have to indent the second,
third aso. line. In particular, with the style you used above, you do not
save or add *any* byte. If this is not obvious to you, look more carefully:

var.el.=....,.........
....h =....,..........
....w.=....,..........
....i,.j,.len,....,.z;

vs.

var.el.=....;.........
var.h.=....;..........
var.w.=....;..........
var.i,.j,.len,....,.z;

At any rate, the potential savings are so very small compared to what
trimming comments, minimization and gzipping can achieve that this is not a
convincing argument. Taking my current local object.js as an example:

awk '
BEGIN {
total = 0;
var_lines = 0;
print;
}

/^[[:space:]]*var/ {
total += length();
var_lines++;
}

END {
print "LOCs: " NR;
print "var LOCs: " var_lines;
print "avg(length(var LOCs)): " total/var_lines " bytes";
savings = 2 * var_lines;
print "Potential savings (best case): " savings " bytes (2 * " var_lines
")";
"wc -c " FILENAME | getline wc_out;
split(wc_out, data);
filesize = data[1];
print "File size: " filesize " bytes";
print "Potential savings (best case): " savings/filesize * 100 " %";
}' \
object.js

LOCs: 2009
var LOCs: 66
avg(length(var LOCs)): 27.8788 bytes
Potential savings (best case): 132 bytes (2 * 66)
File size: 55694 bytes
Potential savings (best case): 0.237009 %
----

2 bytes per `var' line because changing

var.foo;\n
var.bar;\n

to

var.foo,\n
..bar;\n

saves two characters on the second, third etc. line per variable
declaration. However, it should be noted that the more readable form is

var\n
..foo,\n
..bar;\n

which saves *nothing* with \n = <LF> but *adds* one byte with \n = <CR><LF>
as it means removing a space [−1] and adding a newline [+1|+2] on the first
line, adding two spaces [+2] on the second line, and removing "var" (3 bytes
[−3]) and adding a space [+1] on the third line).

With tab indentation, it is a change of

var.foo;\n
var.bar;\n

to

var\n
<HT>foo,\n
<HT>bar;\n

which means removing one space [−1] and adding one newline [+1|+2] on the
first line, adding one <HT> [+1] on the second line and saving 3 bytes [−3]
on the second line (a total of only 1 or two 2 saved bytes). (However, tab
indentation may require additional adjustments at the reader's, and is
therefore also not recommended for posting to Usenet.)

>> These are all permitted by the various standards, and they all work.
>> There is no reason that you "must" or "must not" do any of these.
>>
>> Also, "best practice" is invariably "in the opinion of the author of the
>> website / book / blog / whatever" that said example of best practice
>> appears in.
>
> There are patterns in any programming language usually adopted by
> programmers as "best coding practices". And it happens to other fields
> of study too. See <http://en.wikipedia.org/wiki/Best_Coding_Practices>
>
> If you get a bunch of authors (books, blogs, etc.) that state the same
> "best practices" in any programming language, then you can bet who is
> wrong or right...
>
>> As a matter of interest, what's your reference for "best
>> practice"? If I write a book or start a blog called "Javascript - Best
>> Practice" does that make it true?
>
> No, it doesn't, although I know you're a very experienced and smart
> programmer. However, if you published some evidence such as performance
> tests, etc., then you could state that some practice should be either
> considered a good one or avoided altogether.

Your logic is flawed: <http://en.wikipedia.org/wiki/Ipse_dixit>


PointedEars
--
var bugRiddenCrashPronePieceOfJunk = (
navigator.userAgent.indexOf('MSIE 5') != -1
&& navigator.userAgent.indexOf('Mac') != -1
) // Plone, register_function.js:16

J.R.

unread,
Nov 14, 2011, 10:03:03 AM11/14/11
to
On 14/11/2011 10:15, Thomas 'PointedEars' Lahn wrote:

>>> var el = (typeof obj == 'string') ? document.getElementById(obj) : obj;
>>> w = el.offsetWidth ;
>>> h = el.offsetHeight;
>>> ...
>>>
>>
>> No, because the ";" marks the end of the variable declaration list. In
>> the above code, you are indeed creating an implied global variable
>> called h,
>
> No, it creates, if it succeeds (and does not throw an exception, as observed
> in some instances with MSHTML before, and required in ECMAScript Ed. 5
> strict mode), a property with that name of the ECMAScript Global object or
> overwrites a property with that name of an object in the scope chain.

Considering only the given code by Cal, it creates two implied global
variables (w and h), according to ECMA-262 3rd, section 12.2:

"If the variable statement occurs inside a FunctionDeclaration, the
variables are defined with function-local scope in that function, as
described in s10.1.3. Otherwise, they are defined with *global scope*
(that is, they are created as members of the global object, as described
in 10.1.3) [...]"

>
>> instead of creating a private variable in the function scope.
>
> The proper terminology here is "_local_ variable", not what you wrote.

As written above, the correct terminology is indeed "variable defined in
the function-local scope".

> Visibility modifiers do not exist in these implementations; privacy can
> only be achieved implicitly, through closures. So far there is no closure
> in that code regarding those variables.

ACK, except for the *only*.

>> it is one of the JavaScript best practices to declare all of the
>> variables used in a function at the top of the function body. You may
>> have many variables separated by commas, e.g
>>
>> var el = ...,
>> h = ...,
>> w = ...,
>> i, j, len, ..., z;
>>
>> You must not use multiple var statements such as:
>> var el;
>> var h = ...;
>> var z;
>
> Wrong. In fact, it turns out that syntactically *correct*, adjacent `var'
> statements work better with editors capable of refactoring, such as Eclipse
> JSDT.

It's not wrong, it's a different approach instead. ECMAScript permits
using either a single var or many var statements as one wishes. I prefer
the single var pattern.

And I don't care about Eclipse - I'm talking about JavaScript not JAVA.
Personally, I prefer Python / Django but it doesn't matter to this
discussion anyway.

> And they help to avoid the problem that you encountered, because it
> would likely be a syntax error if you mistyped the semicolon, and automatic
> semicolon insertion would take place if you forgot to type the semicolon at
> all.

ACK.

--
Joao Rodrigues (J.R.)

J.R.

unread,
Nov 14, 2011, 11:14:50 AM11/14/11
to
You are right, I should have not used the "must not" as it expresses
prohibition in English, and a code pattern is not necessarily one of the
"best coding practices", although, in many cases, they seem to walk hand
in hand. And sticking to a strict coding style is usually considered one
of the best practices in many programming languages.

Examples of "best practices" in JS:
<http://dev.opera.com/articles/view/javascript-best-practices/>

The above link is propped up by the Mozilla Developer Network
<https://developer.mozilla.org/en-US/learn/javascript>, and there are
other pages at MDN concerning to best practices in other aspects of
development (extensions, security, ect.).

Cheers,
Joao Rodrigues (J.R.)

Thomas 'PointedEars' Lahn

unread,
Nov 14, 2011, 11:24:15 AM11/14/11
to
J.R. wrote:

> On 14/11/2011 10:15, Thomas 'PointedEars' Lahn wrote:
>>>> var el = (typeof obj == 'string') ? document.getElementById(obj) : obj;
>>>> w = el.offsetWidth ;
>>>> h = el.offsetHeight;
>>>> ...
>>>>
>>>
>>> No, because the ";" marks the end of the variable declaration list. In
>>> the above code, you are indeed creating an implied global variable
>>> called h,
>>
>> No, it creates, if it succeeds (and does not throw an exception, as
>> observed in some instances with MSHTML before, and required in ECMAScript
>> Ed. 5 strict mode), a property with that name of the ECMAScript Global
>> object or overwrites a property with that name of an object in the scope
>> chain.
>
> Considering only the given code by Cal, it creates two implied global
> variables (w and h),

No. What happens is what I described, which is compliant with ECMAScript
Edition 3 Final, sections 11.13.1 and 8.6.2, and Editions 5 and 5.1,
sections 11.13.1 and 8.7.2, respectively.

> according to ECMA-262 3rd, section 12.2:

The current edition of ECMAScript is 5.1, June 2011 CE; not Edition 3
(Final), December 1999/March 2000 CE.

> "If the variable statement occurs inside a FunctionDeclaration, the
> variables are defined with function-local scope in that function, as
> described in s10.1.3. Otherwise, they are defined with *global scope*
> (that is, they are created as members of the global object, as described
> in 10.1.3) [...]"

That section's second sentence refers to *variable statements* outside of a
FunctionDeclaration, as made obvious by its first sentence.

>>> instead of creating a private variable in the function scope.
>> The proper terminology here is "_local_ variable", not what you wrote.
>
> As written above, the correct terminology is indeed "variable defined in
> the function-local scope".

No, a "variable defined *with* function-local scope" is something else than
"a variable defined *in* the function-local scope" (which you also did not
say before). The proper term for such a variable is _local_ variable, _not_
a "private" variable (whereas you said the latter before).

>> Visibility modifiers do not exist in these implementations; privacy can
>> only be achieved implicitly, through closures. So far there is no
>> closure in that code regarding those variables.
>
> ACK, except for the *only*.

Please name a counter-example using ECMAScript-conforming code where a
`private'-like property visibility is achieved explicitly.

>>> it is one of the JavaScript best practices to declare all of the
>>> variables used in a function at the top of the function body. You may
>>> have many variables separated by commas, e.g
>>>
>>> var el = ...,
>>> h = ...,
>>> w = ...,
>>> i, j, len, ..., z;
>>>
>>> You must not use multiple var statements such as:
>>> var el;
>>> var h = ...;
>>> var z;
>>
>> Wrong. In fact, it turns out that syntactically *correct*, adjacent
>> `var' statements work better with editors capable of refactoring, such as
>> Eclipse JSDT.
>
> It's not wrong, it's a different approach instead.

No, it is wrong to say "must not use". "Must not" in English means "is not
allowed to". It is certainly allowed to use that syntactical construct, as
it constitutes nothing more than consecutive statements.

> ECMAScript permits using either a single var or many var statements as one
> wishes.

That is not what you said before.

> I prefer the single var pattern.

That is also not what you said before.

> And I don't care about Eclipse - I'm talking about JavaScript not JAVA.

Will you please at least *try* get yourself educated before you post?
Eclipse JSDT is the Eclipse _JavaScript_ Development Tools plugin.

> Personally, I prefer Python / Django but it doesn't matter to this
> discussion anyway.

Yes, it matters how a commonly used JavaScript IDE can deal with either of
those syntactical constructs.


PointedEars
--
Danny Goodman's books are out of date and teach practices that are
positively harmful for cross-browser scripting.
-- Richard Cornford, cljs, <cife6q$253$1$8300...@news.demon.co.uk> (2004)

John G Harris

unread,
Nov 14, 2011, 10:05:02 AM11/14/11
to
On Sun, 13 Nov 2011 at 20:26:47, in comp.lang.javascript, Thomas
'PointedEars' Lahn wrote:

<snip>
>But I will still ignore you if you (continue to) post with an invalid
>From/Reply-To header field value. Usenet can only work if communication
^^^^^^
>works both ways.
<snip>

What have e-mail addresses got to do with Usenet communication ?

John
--
John Harris

John G Harris

unread,
Nov 14, 2011, 10:13:03 AM11/14/11
to
On Mon, 14 Nov 2011 at 15:04:54, in comp.lang.javascript, Thomas
'PointedEars' Lahn wrote:
>J.R. wrote:

<snip>
>> - there's a single place to look for all the local variables needed by
>> the function;
>
>The comma operator does not help with this.
<snip>

It's not the comma *operator* here; that can only separate expressions.
The commas here are just part of the syntax of a variable declaration
list.

John
--
John Harris

Eric Bednarz

unread,
Nov 14, 2011, 11:52:09 AM11/14/11
to
Thomas 'PointedEars' Lahn <Point...@web.de> writes:

>>> On Sun, 13 Nov 2011 20:49:25 -0200, J.R. wrote:
>>>> it is one of the JavaScript best practices to declare all of the
>>>> variables used in a function at the top of the function body. You may
>>>> have many variables separated by commas, e.g
>>>
>>>> var el = ...,
>>>> h = ...,
>>>> w = ...,
>>>> i, j, len, ..., z;

> The comma operator does not help with this.

> The comma operator does not help with this.

> The comma …

RTFM. Anyhow, the earlier everybody exclusively uses the single var
pattern, the earlier the shitty Eclipse JSDT will get fixed. :-)

J.R.

unread,
Nov 14, 2011, 12:07:54 PM11/14/11
to
On 14/11/2011 12:04, Thomas 'PointedEars' Lahn wrote:
> J.R. wrote:
>
>> On 14/11/2011 00:37, Denis McMahon wrote:
>>> On Sun, 13 Nov 2011 20:49:25 -0200, J.R. wrote:
>>>> it is one of the JavaScript best practices to declare all of the
>>>> variables used in a function at the top of the function body. You may
>>>> have many variables separated by commas, e.g
>>>
>>>> var el = ...,
>>>> h = ...,
>>>> w = ...,
>>>> i, j, len, ..., z;
>>>
>>>> You must not use multiple var statements such as:
>>>> var el;
>>>> var h = ...;
>>>> var z;
>>>
>>> Rubbish.
>>>
>>> You can use as many var statements as you like. Nothing in the standards
>>> or the implementation prevents this, so "must not" is incorrect.
>>
>> "must not" was exaggerated on purpose, because using many var statements
>> is an antipattern in JavaScript.
>
> In your humble opinion (which may not even be your opinion but that of the
> author of some botched book you read instead, and now you think you know the
> language and its "best practices").
>

I still have a long and winding road to go until I get a thorough
comprehension about JavaScript. But what about you?

>>> Some people think all variables should be declared in a single statement.
>>> Some people use a different statement for each type of variable, where
>>> type is the sort of data that it will be used to hold (array, string,
>>> integer, float, object etc).
>>> Some people just use one variable per var.
>>
>> The advantages of using the Single var Pattern at the top of your
>> functions are:
>
> You are confusing two concepts here.

No, I am not.

>
>> - there's a single place to look for all the local variables needed by
>> the function;
>
> The comma operator does not help with this.
>
>> - prevention of logical errors when a variable is used before it’s
>> defined;
>
> The comma operator does not help with this.
>

Read again and notice that I was writing about adopting the Single var
Pattern, instead of writing many var statements. It's not about using
commas.

>> - Helps you remember to declare variables and therefore minimize
>> globals;
>
> The comma …
>
>> - only one var statement means less code to type and a reduction
>> in the file size.
>
> Sometimes. Because for readable code, you will have to indent the second,
> third aso. line. In particular, with the style you used above, you do not
> save or add *any* byte. If this is not obvious to you, look more carefully:
>
> var.el.=....,.........
> ....h =....,..........
> ....w.=....,..........
> ....i,.j,.len,....,.z;
>
> vs.
>
> var.el.=....;.........
> var.h.=....;..........
> var.w.=....;..........
> var.i,.j,.len,....,.z;
>

Yes, it is obvious to anyone. But what if we minify our code
<http://en.wikipedia.org/wiki/Minification_(programming)>, leaving out
unnecessary spaces? Code Minification is one of the best practices in
Javascript.

> At any rate, the potential savings are so very small compared to what
> trimming comments, minimization and gzipping can achieve that this is not a
> convincing argument. Taking my current local object.js as an example:
>
> [snip]
>
> which saves *nothing* with \n =<LF> but *adds* one byte with \n =<CR><LF>
> as it means removing a space [−1] and adding a newline [+1|+2] on the first
> line, adding two spaces [+2] on the second line, and removing "var" (3 bytes
> [−3]) and adding a space [+1] on the third line).
>
> [snip]
>
> which means removing one space [−1] and adding one newline [+1|+2] on the
> first line, adding one<HT> [+1] on the second line and saving 3 bytes [−3]
> on the second line (a total of only 1 or two 2 saved bytes). (However, tab
> indentation may require additional adjustments at the reader's, and is
> therefore also not recommended for posting to Usenet.)

Obviously, you are not considering a file with hundreds, perhaps
thousands of lines. Code minification is a good practice, supported by
renowned JS developers and browser-vendors no matter how hard you try to
deny it just because you want do disqualify my statement. I really think
that you do not believe in your own words.

>
>>> These are all permitted by the various standards, and they all work.
>>> There is no reason that you "must" or "must not" do any of these.
>>>
>>> Also, "best practice" is invariably "in the opinion of the author of the
>>> website / book / blog / whatever" that said example of best practice
>>> appears in.
>>
>> There are patterns in any programming language usually adopted by
>> programmers as "best coding practices". And it happens to other fields
>> of study too. See<http://en.wikipedia.org/wiki/Best_Coding_Practices>
>>
>> If you get a bunch of authors (books, blogs, etc.) that state the same
>> "best practices" in any programming language, then you can bet who is
>> wrong or right...
>>
>>> As a matter of interest, what's your reference for "best
>>> practice"? If I write a book or start a blog called "Javascript - Best
>>> Practice" does that make it true?
>>
>> No, it doesn't, although I know you're a very experienced and smart
>> programmer. However, if you published some evidence such as performance
>> tests, etc., then you could state that some practice should be either
>> considered a good one or avoided altogether.
>
> Your logic is flawed:<http://en.wikipedia.org/wiki/Ipse_dixit>
>

When there is nothing left to say, you really enjoy finishing a
discussion off with this sort of Mr. Spock citation (Your logic is
flawed). Very characteristic.

--
Joao Rodrigues (J.R.)

Richard Cornford

unread,
Nov 14, 2011, 12:18:09 PM11/14/11
to
On Nov 14, 5:14 am, J.R. wrote:
> On 14/11/2011 00:37, Denis McMahon wrote:
>> On Sun, 13 Nov 2011 20:49:25 -0200, J.R. wrote:
>
>>> it is one of the JavaScript best practices to declare all of the
>>> variables used in a function at the top of the function body. You
>>> may have many variables separated by commas, e.g
>
>>> var el = ...,
>>> h = ...,
>>> w = ...,
>>> i, j, len, ..., z;
>
>>> You must not use multiple var statements such as:
>>> var el;
>>> var h = ...;
>>> var z;
>
>> Rubbish.
>
>> You can use as many var statements as you like. Nothing in the
>> standards or the implementation prevents this, so "must not" is
>> incorrect.
>
> "must not" was exaggerated on purpose, because using many var
> statements is an antipattern in JavaScript.

<URL: http://en.wikipedia.org/wiki/Anti-pattern > describes an
antipattern as:-

"In software engineering, an anti-pattern (or antipattern) is a
pattern that may be commonly used but is ineffective and/or
counterproductive in practice."

- which seems to require ineffective and/or counterproductive, both of
which could be demonstrated if true. However, ineffective is obviously
not relevant to variable declarations, as they are effective, with
near zero difference in behaviour between single variable declaration
statements and multiple variable declaration statements. So it is
counterproductive that seems pertinent, and given that this thread has
already demonstrated that continuing a statement across multiple lines
with each line except the last terminated with a comma is far from an
error resistant practice, the 'productivity' balance seems to already
have tipped away from this practice..

Personally I think that the comma is too visually indistinct and also
too visually similar to a semicolon to be a good candidate for source
code line termination. That is, it is not easy to see that you have
done the right thing while writing it, and it is also not easy for a
later reader to see what the code is attempting to do (and doing it
correctly or not). I tend to see opaque source code text as
counterproductive in itself.

>> Some people think all variables should be declared in a single
>> statement.

That would be ridiculously dogmatic of them.

>> Some people use a different statement for each type
>> of variable, where type is the sort of data that it will be used
>> to hold (array, string, integer, float, object etc).
>> Some people just use one variable per var.

And some people put variable declarations on a single line until that
line starts to get too long (for some arbitrary definition of too long
(or a formal coding standard if applicable) and the start a new
variable declaration statement on the next line.

> The advantages of using the Single var Pattern at the top of your
> functions are:
> - there's a single place to look for all the local variables needed
> by the function;

This is not an advantage over multiple consecutive variable
declaration statements at the top of that same function. And since a
single statement could become very long or extended over multiple
lines that is likely to become difficult to read and understand,
negating some of the advantage of only looking in a single place.

> - prevention of logical errors when a variable is used before it’s
> defined;

This is not an advantage over multiple consecutive variable
declaration statements at the top of that same function. And what do
"logical errors" consist of in this context? If variables are declared
they are declared as an execution context is entered.

In my experience when people have made a case for declaring variables
at the top of a function body it is on order that the structure/order
of the source code reflect the way in which the javascript engine is
going to behave (handling the declarations before any actual code
execution). It would seem an unjustified misapplication of this
justification to insist that those variable declarations be confined
to a single statement (especially since that same recommendation wants
the inner function declarations to appear at the top of the function
body as well, and they cannot be combined into a single statement).

> - Helps you remember to declare variables and therefore minimize
> globals;

This is not an advantage over multiple consecutive variable
declaration statements at the top of that same function.

> - only one var statement means less code to type and a reduction
> in the file size.

So it would be (at best) the opportunity to save half a dozen bytes
that is the only factor left that could justify the "antipattern"
assertion, on the grounds of the alternatives being
counterproductive. I won't be buying that argument as this would be
neutralised by zipping the resource to be sent to the client, while
the potential added obscurity in the source code looks too negative to
me.

>> These are all permitted by the various standards, and they all
>> work. There is no reason that you "must" or "must not" do any
>> of these.
>
>> Also, "best practice" is invariably "in the opinion of the author
>> of the website / book / blog / whatever" that said example of best
>> practice appears in.
>
> There are patterns in any programming language usually adopted
> by programmers as "best coding practices". And it happens to
> other fields of study too. See
> <http://en.wikipedia.org/wiki/Best_Coding_Practices>

Maybe, but a high proportion of "best practices" that have been
proposed for javascript have been pretty much BS. Misunderstandings/
miscomprehensions abound, but the people looking for rules that will
supposedly help them cannot easily tell. I always recommend that no
"best practice" should be taken seriously unless it is presented
alongside a reasoned justification, and that that justification stands
up to critical scrutiny. For anything that really is a "best practice"
that should be an achievable requirement.

And having seen your reasoning for only using a single variable
declaration statement per function body, it didn’t stand up.

> If you get a bunch of authors (books, blogs, etc.) that state the
> same "best practices" in any programming language, then you can
> bet who is wrong or right...

Not with javascript. Nonsense propagates like wildfire in this field.
Hence the need to look at the actual reasoning and not be impressed by
any argument from numbers.

>> As a matter of interest, what's your reference for "best
>> practice"? If I write a book or start a blog called "Javascript
>> - Best Practice" does that make it true?
>
> No, it doesn't, although I know you're a very experienced and
> smart programmer.

Do you really know that? (and should it matter anyway as in isolation
that would only make for an argument from authority?)

> However, if you published some evidence such
> as performance tests, etc.,

Yes, test cases are really good at demonstrating a point. Indeed if
properly designed are much more convincing than reasoned argument. So
can the alternatives to using a single variable declaration statement
at the start of a function body be demonstrated to be
counterproductive with some test case?

> then you could state that some practice
> should be either considered a good one or avoided altogether.

Performance isn't everything. In practice most javascript performs
just fine (and ironically better and better as CPUs and javascript
engines get faster). It will be useful to know what factors impact
performance, so as to be able to achieve it when necessary or avoid
squandering it, but it has long been the case that the biggest expense
in software production is accounted for by code maintenance, making
source code clarity (readability, understandably and self-documenting-
ness) a completely valid subject for "best practices", and putting the
variable declarations at the top of a function body was originally
primarily about code clarity.

Richard.

Thomas 'PointedEars' Lahn

unread,
Nov 14, 2011, 12:19:31 PM11/14/11
to
Yes, you are. One, declaring variables either on top of a function body or
anywhere. Two, using either consecutive `var' statements or one `var'
statement with a list.

>>> - there's a single place to look for all the local variables needed by
>>> the function;
>>
>> The comma operator does not help with this.
>>
>>> - prevention of logical errors when a variable is used before it’s
>>> defined;
>>
>> The comma operator does not help with this.
>
> Read again and notice that I was writing about adopting the Single var
> Pattern, instead of writing many var statements. It's not about using
> commas.

Apparently you don't even know what you write.

>>> - Helps you remember to declare variables and therefore minimize
>>> globals;
>>
>> The comma …
>>
>>> - only one var statement means less code to type and a reduction
>>> in the file size.
>>
>> Sometimes. Because for readable code, you will have to indent the
>> second, third aso. line. In particular, with the style you used above,
>> you do not save or add *any* byte. If this is not obvious to you, look
>> more carefully:
>>
>> var.el.=....,.........
>> ....h =....,..........
>> ....w.=....,..........
>> ....i,.j,.len,....,.z;
>>
>> vs.
>>
>> var.el.=....;.........
>> var.h.=....;..........
>> var.w.=....;..........
>> var.i,.j,.len,....,.z;
>>
>
> Yes, it is obvious to anyone.

Not to you, obviously, as you were claiming that your approach would save
space. It doesn't.

> But what if we minify our code>
> <http://en.wikipedia.org/wiki/Minification_(programming)>, leaving out
> unnecessary spaces?

A good minifier should indeed be capable to make one variable statement out
of consecutive ones. Minification becomes relevant when serving resources,
not when storing them.

> Code Minification is one of the best practices in Javascript.

Says who? The same person who says you must not use consecutive variable
statements? I see.

>> At any rate, the potential savings are so very small compared to what
>> trimming comments, minimization and gzipping can achieve that this is not
>> a convincing argument. Taking my current local object.js as an example:
>>
>> [snip]
>>
>> which saves *nothing* with \n =<LF> but *adds* one byte with \n
>> =<CR><LF> as it means removing a space [−1] and adding a newline [+1|+2]
>> on the first line, adding two spaces [+2] on the second line, and
>> removing "var" (3 bytes [−3]) and adding a space [+1] on the third line).
>>
>> [snip]
>>
>> which means removing one space [−1] and adding one newline [+1|+2] on the
>> first line, adding one<HT> [+1] on the second line and saving 3 bytes
>> [−3]
>> on the second line (a total of only 1 or two 2 saved bytes). (However,
>> tab indentation may require additional adjustments at the reader's, and
>> is therefore also not recommended for posting to Usenet.)
>
> Obviously, you are not considering a file with hundreds, perhaps
> thousands of lines.

Obviously you can't read.

Perhaps I should take David Mark's approach instead, and simply send you to
bed from time to time. Currently at least, your higher brain functions do
not appear to be very active.

Thomas 'PointedEars' Lahn

unread,
Nov 14, 2011, 12:27:03 PM11/14/11
to
John G Harris wrote:

> Thomas 'PointedEars' Lahn wrote:
>> J.R. wrote:
>>> - there's a single place to look for all the local variables needed by
>>> the function;
>> The comma operator does not help with this.
>
> It's not the comma *operator* here; that can only separate expressions.
> The commas here are just part of the syntax of a variable declaration
> list.

ACK, thanks.

J.R.

unread,
Nov 14, 2011, 12:44:59 PM11/14/11
to
On 14/11/2011 15:19, Thomas 'PointedEars' Lahn wrote:

>> Code Minification is one of the best practices in Javascript.
>
> Says who? The same person who says you must not use consecutive variable
> statements? I see.

I would not say one person, but *many* experienced and renowned JS
developers and all major browser-vendors. Google and find by yourself.

>>> At any rate, the potential savings are so very small compared to what
>>> trimming comments, minimization and gzipping can achieve that this is not
>>> a convincing argument. Taking my current local object.js as an example:
>>>
>>> [snip]
>>>
>>> which saves *nothing* with \n =<LF> but *adds* one byte with \n
>>> =<CR><LF> as it means removing a space [−1] and adding a newline [+1|+2]
>>> on the first line, adding two spaces [+2] on the second line, and
>>> removing "var" (3 bytes [−3]) and adding a space [+1] on the third line).
>>>
>>> [snip]
>>>
>>> which means removing one space [−1] and adding one newline [+1|+2] on the
>>> first line, adding one<HT> [+1] on the second line and saving 3 bytes
>>> [−3]
>>> on the second line (a total of only 1 or two 2 saved bytes). (However,
>>> tab indentation may require additional adjustments at the reader's, and
>>> is therefore also not recommended for posting to Usenet.)
>>
>> Obviously, you are not considering a file with hundreds, perhaps
>> thousands of lines.
>
> Obviously you can't read.
>
> Perhaps I should take David Mark's approach instead, and simply send you to
> bed from time to time. Currently at least, your higher brain functions do
> not appear to be very active.

LOL. Very entertaining.

--
Joao Rodrigues (J.R.)

Thomas 'PointedEars' Lahn

unread,
Nov 14, 2011, 1:01:41 PM11/14/11
to
J.R. wrote:

> On 14/11/2011 15:19, Thomas 'PointedEars' Lahn wrote:
>>> Code Minification is one of the best practices in Javascript.
>> Says who? The same person who says you must not use consecutive variable
>> statements? I see.
>
> I would not say one person, but *many* experienced and renowned JS
> developers and all major browser-vendors. Google and find by yourself.

There we have the "ipse dixit" fallacy again.

J.R.

unread,
Nov 14, 2011, 1:22:20 PM11/14/11
to
Yes, I do.

> (and should it matter anyway as in isolation
> that would only make for an argument from authority?)

No, it shouldn't matter because of the "fallacy of authority"
<http://www.constitution.org/col/logical_fallacies.htm>

>> However, if you published some evidence such
>> as performance tests, etc.,
>
> Yes, test cases are really good at demonstrating a point. Indeed if
> properly designed are much more convincing than reasoned argument. So
> can the alternatives to using a single variable declaration statement
> at the start of a function body be demonstrated to be
> counterproductive with some test case?
>
>> then you could state that some practice
>> should be either considered a good one or avoided altogether.
>
> Performance isn't everything. In practice most javascript performs
> just fine (and ironically better and better as CPUs and javascript
> engines get faster). It will be useful to know what factors impact
> performance, so as to be able to achieve it when necessary or avoid
> squandering it, but it has long been the case that the biggest expense
> in software production is accounted for by code maintenance, making
> source code clarity (readability, understandably and self-documenting-
> ness) a completely valid subject for "best practices", and putting the
> variable declarations at the top of a function body was originally
> primarily about code clarity.

Dear Richard,
Besides being a gentleman while writing your brilliant ideas down, you
were impeccable in your above comments! I must agree with you. Thank you
very much indeed.

PS. It's a pity that Thomas Lahn is not well educated and polite as you
and many others in this newsgroup. Although he really knows a lot about
JavaScript, his responses are usually unpleasant and aggressive. Also he
has a stupefying habit of changing his points of view just to discredit
someone.

--
Joao Rodrigues (J.R.)

Denis McMahon

unread,
Nov 14, 2011, 1:31:30 PM11/14/11
to
On Mon, 14 Nov 2011 14:14:50 -0200, J.R. wrote:

> On 14/11/2011 12:03, Denis McMahon wrote:
>> On Mon, 14 Nov 2011 03:14:20 -0200, J.R. wrote:
>>
>>> The advantages of using the Single var Pattern at the top of your
>>> functions are:
>>
>> I'm not objecting to the suggestion that best practice includes
>> defining all your variables with var statements at the start of a
>> function. I agree that this is indeed best practice.
>>
>> I am, however, objecting to (a) your assertion that it "must" be done,
>> or (b) that best practice requires the use of a single var statement.

> You are right, I should have not used the "must not" as it expresses
> prohibition in English, and a code pattern is not necessarily one of the
> "best coding practices", although, in many cases, they seem to walk hand
> in hand. And sticking to a strict coding style is usually considered one
> of the best practices in many programming languages.
>
> Examples of "best practices" in JS:
> <http://dev.opera.com/articles/view/javascript-best-practices/>

Yep, read that.

> The above link is propped up by the Mozilla Developer Network
> <https://developer.mozilla.org/en-US/learn/javascript>, and there are
> other pages at MDN concerning to best practices in other aspects of
> development (extensions, security, ect.).

Noted that.

Can't see the bit about combining all the variable declarations into a
single var statement though.

Psst, jslint doesn't seem to want that either, it's quite happy as long
as (a) all variables are defined (b) at the start of the function.

Minimisation is good, but the following:

var a = "df";
var b = 17;
var c = [{s:'monkey',x:'male',a:3},{s:'elephant',x:'female',a:7},
{s:'mule',x:'neuter',a:1}];
var c1 = ["alpha","beta","gamma"];
var c2 = {o:'peter',f:'grass',z:'oregon',d:[{x:'male',q:3},
{x:'female',q:4}]};
var d = "mary had a little lamb";
var e = f = g = 0;

is going to be much easier to maintain than a single minimised statement:

var a="df",b=17,c=[{s:'monkey',x:'male',a:3},
{s:'elephant',x:'female',a:7},{s:'mule',x:'neuter',a:1}],c1=
["alpha","beta","gamma"],c2={o:'peter',f:'grass',z:'oregon',d:
[{x:'male',q:3},{x:'female',q:4}]},d="mary had a little lamb",e=f=g=0;

even if you do use more sensible variable and property names than the
ones I've selected.

Rgds

Denis McMahon

Evertjan.

unread,
Nov 14, 2011, 1:36:46 PM11/14/11
to
Denis McMahon wrote on 14 nov 2011 in comp.lang.javascript:

> var e = f = g = 0;

This is not the same as:

var f;
var g;
var e = f = g = 0;

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)

Denis McMahon

unread,
Nov 14, 2011, 1:38:09 PM11/14/11
to
On Mon, 14 Nov 2011 09:18:09 -0800, Richard Cornford wrote:
> Joao Rodrigues (J.R.) wrote:
>> Denis McMahon wrote:

>>> As a matter of interest, what's your reference for "best practice"? If
>>> I write a book or start a blog called "Javascript - Best Practice"
>>> does that make it true?

>> No, it doesn't, although I know you're a very experienced and smart
>> programmer.

> Do you really know that? (and should it matter anyway as in isolation
> that would only make for an argument from authority?)

Personally I think of myself as reasonably competent, but I also know
that after some 34 years of computer programming I'm still learning.

Rgds

Denis McMahon

J.R.

unread,
Nov 14, 2011, 1:42:31 PM11/14/11
to
On 14/11/2011 16:01, Thomas 'PointedEars' Lahn wrote:
> J.R. wrote:
>
>> On 14/11/2011 15:19, Thomas 'PointedEars' Lahn wrote:
>>>> Code Minification is one of the best practices in Javascript.
>>> Says who? The same person who says you must not use consecutive variable
>>> statements? I see.
>>
>> I would not say one person, but *many* experienced and renowned JS
>> developers and all major browser-vendors. Google and find by yourself.
>
> There we have the "ipse dixit" fallacy again.

No, it is more like "vox populi, vox Dei"...

--
Joao Rodrigues (J.R.)

Thomas 'PointedEars' Lahn

unread,
Nov 14, 2011, 1:53:06 PM11/14/11
to
IOW: Faith, not science. I rest my case.


PointedEars
--
When all you know is jQuery, every problem looks $(olvable).

Scott Sauyet

unread,
Nov 14, 2011, 1:54:22 PM11/14/11
to
Denis McMahon wrote:
> Minimisation is good, but the following:
>
> var a = "df";
> var b = 17;
> var c = [{s:'monkey',x:'male',a:3},{s:'elephant',x:'female',a:7}, {s:'mule',x:'neuter',a:1}];
> [ ... ]
>
> is going to be much easier to maintain than a single minimised statement:
>
> var a="df",b=17,c=[{s:'monkey',x:'male',a:3}, {s:'elephant',x:'female',a:7},{s:'mule',x:'neuter',a:1}],// [ ... ]
>
> even if you do use more sensible variable and property names than the
> ones I've selected.

Another contender is this:

var a = "df",
b = 17;
c = [{s:'monkey',x:'male',a:3},{s:'elephant',x:'female',a:7},
{s:'mule',x:'neuter',a:1}],
/* ... */;

Or, as Thomas suggests, this:

var
a = "df",
b = 17,
c = [{s:'monkey',x:'male',a:3},{s:'elephant',x:'female',a:7},
{s:'mule',x:'neuter',a:1}],
/* ... */;


These both compress well and are still readable. Richard's argument
against the comma are reasonable, and in choosing whether you want to
do this, you need to weigh the concerns he raises about commas making
the source more opaque against the ability to better minify the source
code.

-- Scott

Gene Wirchenko

unread,
Nov 14, 2011, 3:00:14 PM11/14/11
to
On Mon, 14 Nov 2011 03:14:20 -0200, "J.R." <group...@yahoo.com.br>
wrote:

>On 14/11/2011 00:37, Denis McMahon wrote:
>> On Sun, 13 Nov 2011 20:49:25 -0200, J.R. wrote:

[snip]

>>> You must not use multiple var statements such as:
>>> var el;
>>> var h = ...;
>>> var z;
>>
>> Rubbish.
>>
>> You can use as many var statements as you like. Nothing in the standards
>> or the implementation prevents this, so "must not" is incorrect.
>
>"must not" was exaggerated on purpose, because using many var statements
>is an antipattern in JavaScript.

Exaggerating to make a point is an anti-pattern of its own. It
means that anyone reading what you write can not simply take it at
face value, but now has to figure out whether the meaning to use is
the literal one or a weaker form of it.

[snip]

Sincerely,

Gene Wirchenko

Gene Wirchenko

unread,
Nov 14, 2011, 3:12:22 PM11/14/11
to
On Mon, 14 Nov 2011 09:18:09 -0800 (PST), Richard Cornford
<Ric...@litotes.demon.co.uk> wrote:

>On Nov 14, 5:14 am, J.R. wrote:

[snip]

>> The advantages of using the Single var Pattern at the top of your
>> functions are:
[snip]
>> - Helps you remember to declare variables and therefore minimize
>> globals;
>
>This is not an advantage over multiple consecutive variable
>declaration statements at the top of that same function.

In fact, it might be a disadvantage! Consider:
var a="somthing",
b="another"
c="YA"
which is correct but misleading code. c is not declared here. What
was intended was:
var a="somthing",
b="another",
c="YA"
(added a comma to the second line)

>> - only one var statement means less code to type and a reduction
>> in the file size.
>
>So it would be (at best) the opportunity to save half a dozen bytes
>that is the only factor left that could justify the "antipattern"
>assertion, on the grounds of the alternatives being
>counterproductive. I won't be buying that argument as this would be
>neutralised by zipping the resource to be sent to the client, while
>the potential added obscurity in the source code looks too negative to
>me.

I would rather type var a few more times and feel safer about my
code. See my example above. Sir Hoare said it well:

"I was eventually persuaded of the need to design programming
notations so as to maximize the number of errors which cannot be made,
or if made, can be reliably detected at compile time. Perhaps this
would make the text of programs longer. Never mind! Wouldn't you be
delighted if your Fairy Godmother offered to wave her wand over your
program to remove all its errors and only made the condition that you
should write out and key in your whole program three times!"

[snip]

>> There are patterns in any programming language usually adopted
>> by programmers as "best coding practices". And it happens to
>> other fields of study too. See
>> <http://en.wikipedia.org/wiki/Best_Coding_Practices>
>
>Maybe, but a high proportion of "best practices" that have been
>proposed for javascript have been pretty much BS. Misunderstandings/
>miscomprehensions abound, but the people looking for rules that will
>supposedly help them cannot easily tell. I always recommend that no
>"best practice" should be taken seriously unless it is presented
>alongside a reasoned justification, and that that justification stands
>up to critical scrutiny. For anything that really is a "best practice"
>that should be an achievable requirement.

Quite.

[snip]

Sincerely,

Gene Wirchenko

Denis McMahon

unread,
Nov 14, 2011, 7:18:11 PM11/14/11
to
On Mon, 14 Nov 2011 18:36:46 +0000, Evertjan. wrote:

> Denis McMahon wrote on 14 nov 2011 in comp.lang.javascript:
>
>> var e = f = g = 0;
>
> This is not the same as:
>
> var f;
> var g;
> var e = f = g = 0;

Yes, you're right, my example didn't actually define f and g, only e. You
seem to be the only person who spotted it. ;)

The "correct"[1] form is of course:

var e,f,g=e=f=0;

[1] in this context, "correct" means whatever I want it to mean!

Rgds

Denis McMahon

Richard Cornford

unread,
Nov 14, 2011, 8:23:20 PM11/14/11
to
Scott Sauyet wrote:
> Denis McMahon wrote:
>> Minimisation is good, but the following:
>>
>> var a = "df";
>> var b = 17;
<snip>
> Another contender is this:
>
> var a = "df",
> b = 17;
^ oops!

> c = [{s:'monkey',x:'male',a:3},{s:'elephant',x:'female',a:7},
> {s:'mule',x:'neuter',a:1}],
> /* ... */;
<snip>
> ... . Richard's argument against the comma are reasonable, ...
<snip>

;-)

Richard.

Scott Sauyet

unread,
Nov 16, 2011, 9:04:08 AM11/16/11
to
Richard Cornford wrote:
> Scott Sauyet wrote:
>> Denis McMahon wrote:
>>> Minimisation is good, but the following:
>
>>> var a = "df";
>>> var b = 17;
> <snip>
>> Another contender is this:
>
>> var a = "df",
>>     b = 17;
>
>             ^ oops!
>
>>     c = [{s:'monkey',x:'male',a:3},{s:'elephant',x:'female',a:7},
> <snip>
>> ... .  Richard's argument against the comma are reasonable, ...
> ;-)

Perhaps I should have said "are eminently reasonable"." :-)

-- Scott

Frobernik

unread,
Nov 17, 2011, 5:06:58 PM11/17/11
to
You could squeeze more out of the available space and avoid the use of a
var completely

Using the original example

function findPos(obj) {
var w = obj.offsetWidth;
var h = obj.offsetHeight;
}
findPos(divThis)

becomes :-

function findPos(obj, w, h) {
w = obj.offsetWidth;
h = obj.offsetHeight;
}
findPos(divThis)

another style/variant could be

function findPos(obj, name, colour, b, c) {
name = obj.name;
colour = obj.colour;
b = 17;
c = [{s:'monkey', x:'male', a:3}, {s:'elephant',x:'female',a:7}];
}
findPos({name:'df', colour:'green'})

Frobernik

Thomas 'PointedEars' Lahn

unread,
Nov 17, 2011, 5:54:08 PM11/17/11
to
Frobernik wrote:

> You could squeeze more out of the available space and avoid the use of a
> var completely
>
> Using the original example
>
> function findPos(obj) {
> var w = obj.offsetWidth;
> var h = obj.offsetHeight;
> }
> findPos(divThis)
>
> becomes :-
>
> function findPos(obj, w, h) {
> w = obj.offsetWidth;
> h = obj.offsetHeight;
> }
> findPos(divThis)
>
> another style/variant could be
>
> function findPos(obj, name, colour, b, c) {
> name = obj.name;
> colour = obj.colour;
> b = 17;
> c = [{s:'monkey', x:'male', a:3}, {s:'elephant',x:'female',a:7}];
> }
> findPos({name:'df', colour:'green'})

(Jorge, is it you?)

We have been over this.

Declaring arguments instead of local variables may be great for code golfing
(140 characters maximum), but it is a Really Bad Idea for all other code.
To begin with, by looking at the code you cannot tell whether you are
modifying an argument or not. Editors and linters which can differentiate
between arguments and local variables could not tell as well.


PointedEars
--
> If you get a bunch of authors […] that state the same "best practices"
> in any programming language, then you can bet who is wrong or right...
Not with javascript. Nonsense propagates like wildfire in this field.
-- Richard Cornford, comp.lang.javascript, 2011-11-14

Frobernik

unread,
Nov 18, 2011, 4:33:40 AM11/18/11
to
On 17/11/2011 22:54, Thomas 'PointedEars' Lahn wrote:
> Frobernik wrote:
>> function findPos(obj, name, colour, b, c) {
>> name = obj.name;
>> colour = obj.colour;
>> b = 17;
>> c = [{s:'monkey', x:'male', a:3}, {s:'elephant',x:'female',a:7}];
>> }
>> findPos({name:'df', colour:'green'})
>
> (Jorge, is it you?)

No its not

> We have been over this.

We have?

> Declaring arguments instead of local variables may be great for code golfing
> (140 characters maximum), but it is a Really Bad Idea for all other code.
> To begin with, by looking at the code you cannot tell whether you are
> modifying an argument or not. Editors and linters which can differentiate
> between arguments and local variables could not tell as well.

An editor or linters not going to know more about my code than me

Thomas 'PointedEars' Lahn

unread,
Nov 19, 2011, 10:05:34 AM11/19/11
to
Frobernik wrote:

> Thomas 'PointedEars' Lahn wrote:
>> Frobernik wrote:
>>> function findPos(obj, name, colour, b, c) {
>>> name = obj.name;
>>> colour = obj.colour;
>>> b = 17;
>>> c = [{s:'monkey', x:'male', a:3}, {s:'elephant',x:'female',a:7}];
>>> }
>>> findPos({name:'df', colour:'green'})
>>
>> We have been over this.
>
> We have?

Yes. We, the previous subscribers of this newsgroup, have. You should read
a fair amount of past discussions before you post to a newsgroup:

<http://jibbering.com/faq/notes/posting>

>> Declaring arguments instead of local variables may be great for code
>> golfing (140 characters maximum), but it is a Really Bad Idea for all
>> other code. To begin with, by looking at the code you cannot tell whether
>> you are modifying an argument or not. Editors and linters which can
>> differentiate between arguments and local variables could not tell as
>> well.
>
> An editor or linters not going to know more about my code than me

Whether that is true depends on what you *actually* know about your code.

I know at least one ECMAScript-supporting editor, which includes a linter,
that can differentiate between function arguments and local variables:
Eclipse JavaScript Developer Tools (JSDT).

It is rather obvious that this is possible for a machine because each
/FunctionDeclaration/ or /FunctionExpression/ has an argument list, and
identifiers need to be *declared* variable names in order to be *variable*
names. So the following heuristics can be applied to a standalone
/IdentifierName/ within a function body:

N¹ A V I B Meaning
-------------------------------------------------------------------------
− − − − + Probable ReferenceError (all modes)
− − − + + Possible "Implied global", i. e. property of an object in
the function scope's scope chain created; possible
ReferenceError (strict mode)
− − + − − Local variable, unused
− − + − + Local variable, used
− − + + + Local variable (initialized), used
– + − − – Function argument, unused
– + − − + Function argument, used
− + − + + Function argument (used), possible default value init.
− + + − − Local variable (unused), hiding a function argument
− + + − + Local variable (used, uninitialized), hiding a function
argument
− + + + + Local variable (used), hiding a function argument
+ − − − − Non-local property or variable
+ − − − + Property in the function scope's scope chain (perhaps
uninitialized), used
+ − − + + Property in the function scope's scope chain, used
+ − + − − Local variable (unused), hiding a property in the
function scope's scope chain
+ − + − + Local variable (used, uninitialized), perhaps hiding a
property in the function scope's scope chain
+ − + + + Local variable (used), hiding a property in the
function scope's scope chain
+ + − − – Function argument (unused), perhaps hiding a property in the
function scope's scope chain
+ + − − + Function argument (used), perhaps hiding a property in the
function scope's scope chain
+ + − + + Function argument (used, perhaps assigned to), perhaps hiding
a property in the function scope's scope chain
+ + + − − Local variable (unused), hiding a function argument,
which hides a property in the function scope's scope chain
+ + + − + Local variable (used), hiding a function argument,
which hides a property in the function scope's scope chain
+ + + + + Local variable (used, initialized), hiding a function
argument, which hides a property in the function scope's
scope chain
_____
¹) N: Non-local occurence
A: Occurence in function's argument list
V: VariableDeclaration in function body
I: Initialization/assignment in function body
B: Occurence in function body
+: Applies
−: Does not apply

In an implementation of similar heuristics, Eclipse JSDT allows function
arguments and variables to be displayed differently. For example, I have
set it up so that it would display argument declarations and references in
bluish italic characters; the identifier in variable declarations in regular
style, but underlined; and local variable references in normal-colored
italic characters. If I were to use your approach, I could not tell at a
glance if an identifier was an argument or a local variable name. I could
be ending up assigning to arguments, inadvertently altering the program flow
after that assignment. If someone would call my function, and I would
forget to assign to the argument but used it later, they could,
intentionally or accidentally, alter the inner workings of my function.

AISB, a Really Bad Idea for a number of reasons, another one being that in
an API you only expose to the world what needs to be exposed to it.


PointedEars
--
Use any version of Microsoft Frontpage to create your site.
(This won't prevent people from viewing your source, but no one
will want to steal it.)
-- from <http://www.vortex-webdesign.com/help/hidesource.htm> (404-comp.)

Thomas 'PointedEars' Lahn

unread,
Nov 19, 2011, 12:17:24 PM11/19/11
to
Thomas 'PointedEars' Lahn wrote:

>> Frobernik wrote:
>>> function findPos(obj, name, colour, b, c) {
>>> name = obj.name;
>>> colour = obj.colour;
>>> b = 17;
>>> c = [{s:'monkey', x:'male', a:3}, {s:'elephant',x:'female',a:7}];
>>> }
>>> findPos({name:'df', colour:'green'})
>
> […]
> In an implementation of similar heuristics, Eclipse JSDT allows function
> arguments and variables to be displayed differently. For example, I have
> set it up so that it would display argument declarations and references in
> bluish italic characters; the identifier in variable declarations in
> regular style, but underlined; and local variable references in
> normal-colored italic characters. If I were to use your approach, I could
> not tell at a glance if an identifier was an argument or a local variable
^ used as
> name. I could be ending up assigning to arguments, inadvertently altering
> the program flow after that assignment. […]

Frobernik

unread,
Nov 21, 2011, 3:01:15 PM11/21/11
to
On 19/11/2011 15:05, Thomas 'PointedEars' Lahn wrote:
> Frobernik wrote:
>>>> findPos({name:'df', colour:'green'})
>>>
>>> We have been over this.
>>
>> We have?
>
> Yes. We, the previous subscribers of this newsgroup, have. You
should read
> a fair amount of past discussions before you post to a newsgroup:
>
> <http://jibbering.com/faq/notes/posting>

Apologies but I (like a lot of others) haven't had the time to read
through the entire back history of this newsgroup from 1995/6-2011 let
alone find the specific thread, post or author to which you're referring

>>>> function findPos(obj, name, colour, b, c) {
>>>> <snip>
>>>> }
>>>> findPos({name:'df', colour:'green'})
>>
>> […]
>> In an implementation of similar heuristics, Eclipse JSDT allows function
>> arguments and variables to be displayed differently. For example, I have
>> set it up so that it would display argument declarations and references in
>> bluish italic characters; the identifier in variable declarations in
>> regular style, but underlined; and local variable references in
>> normal-colored italic characters. If I were to use your approach, I could
>> not tell at a glance if an identifier was an argument or a local variable
> ^ used as
>> name. I could be ending up assigning to arguments, inadvertently altering
>> the program flow after that assignment. […]

I use IntelliJ I *don't* use Eclipse - the last time I did it crashed
wiping an entire two days work

Just cause you don't use it doesn't mean to say its doesn't exist. I
don't like the pattern either but the codes smaller

Thomas 'PointedEars' Lahn

unread,
Nov 22, 2011, 6:50:26 AM11/22/11
to
Frobernik wrote:

> On 19/11/2011 15:05, Thomas 'PointedEars' Lahn wrote:
>> Frobernik wrote:
>>>>> findPos({name:'df', colour:'green'})
>>>> We have been over this.
>>> We have?
>> Yes. We, the previous subscribers of this newsgroup, have. You
>> should read a fair amount of past discussions before you post to a
>> newsgroup:
>>
>> <http://jibbering.com/faq/notes/posting>
>
> Apologies but I (like a lot of others) haven't had the time to read
> through the entire back history of this newsgroup from 1995/6-2011 let
> alone find the specific thread, post or author to which you're referring

You are not apologizing; you are rationalizing, and perhaps even trolling.
Fallacy: Reductio ad absurdum. "A fair amount" does not mean "everything".
IIRC, the last discussion on this subject cannot have taken place more than
six months ago. And there are ways to find that discussion quickly (enough
hints have been given), if you really want.

> I use IntelliJ I *don't* use Eclipse - the last time I did it crashed
> wiping an entire two days work

Few people know how Eclipse advances with each new version, that there is a
new major release every year, and how to configure Eclipse so that it runs
smoothly even with a number of plugins, although the basics are laid out in
the ReadMe.

A single Eclipse crash wiping two days work is doubtful at best. But if
that really happened, you have bigger problems than Eclipse crashes.

> Just cause you don't use it doesn't mean to say its doesn't exist.

You are not making sense.

> I don't like the pattern either but the codes smaller

That is why it serves code golfing. But small code becoming a purpose in
itself is a recipe for disaster.
0 new messages