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

Discussion in 'Javascript' started by Cal Who, Nov 13, 2011.

  1. Cal Who

    Cal Who Guest

    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)
    Cal Who, Nov 13, 2011
    #1
    1. Advertising

  2. 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. 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
    Thomas 'PointedEars' Lahn, Nov 13, 2011
    #2
    1. Advertising

  3. Cal Who

    Cal Who Guest

    "Thomas 'PointedEars' Lahn" <> wrote in message
    news:...
    > 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


    >
    >
    > 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, Nov 13, 2011
    #3
  4. 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:>,
    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$>
    Thomas 'PointedEars' Lahn, Nov 13, 2011
    #4
  5. Cal Who

    Cal Who Guest

    >
    > 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
    Cal Who, Nov 13, 2011
    #5
  6. Cal Who

    J.R. Guest

    On 13/11/2011 18:04, 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 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
    >
    >


    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., Nov 13, 2011
    #6
  7. Cal Who

    J.R. Guest

    On 13/11/2011 18:55, J.R. wrote:
    > On 13/11/2011 18:04, 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 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
    >>
    >>

    >
    > 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;
    > ...
    >
    > }
    >


    Correcting a typo:

    var el = (typeof obj == 'string') ? document.getElementById(obj) :
    obj,
    w = el.offsetWidth, // , instead of ;
    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., Nov 13, 2011
    #7
  8. Cal Who

    Cal Who Guest

    >
    > 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;
    ...
    Cal Who, Nov 13, 2011
    #8
  9. Cal Who

    J.R. Guest

    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, 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.)
    J.R., Nov 13, 2011
    #9
  10. Cal Who

    Cal Who Guest

    "J.R." <> wrote in message
    news:j9phhk$s3i$...
    > 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,
    > 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.)



    Thanks a lot
    Cal Who, Nov 14, 2011
    #10
  11. 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
    Denis McMahon, Nov 14, 2011
    #11
  12. Cal Who

    J.R. Guest

    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.)
    J.R., Nov 14, 2011
    #12
  13. 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, Nov 14, 2011
    #13
  14. 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.


    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
    Thomas 'PointedEars' Lahn, Nov 14, 2011
    #14
  15. Cal Who

    Cal Who Guest

    "Denis McMahon" <> wrote in message
    news:4ec07ef1$0$28711$...
    > 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


    Thanks
    Cal Who, Nov 14, 2011
    #15
  16. 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
    Denis McMahon, Nov 14, 2011
    #16
  17. 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
    Thomas 'PointedEars' Lahn, Nov 14, 2011
    #17
  18. Cal Who

    J.R. Guest

    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., Nov 14, 2011
    #18
  19. 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, Nov 14, 2011
    #19
  20. Cal Who

    J.R. Guest

    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/>

    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.)
    J.R., Nov 14, 2011
    #20
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. jakk
    Replies:
    4
    Views:
    11,976
  2. Santa
    Replies:
    1
    Views:
    1,049
    Mark A. Odell
    Jul 17, 2003
  3. arnuld
    Replies:
    33
    Views:
    1,149
  4. PerlFAQ Server
    Replies:
    0
    Views:
    331
    PerlFAQ Server
    Jan 6, 2011
  5. PerlFAQ Server
    Replies:
    0
    Views:
    240
    PerlFAQ Server
    Apr 15, 2011
Loading...

Share This Page