with Imagination: by Dustin Diaz

./with Imagination

A JavaScript, CSS, XHTML web log focusing on usability and accessibility by Dustin Diaz

Code choices: What’s better?

Tuesday, October 17th, 2006

Ala Snook prompt, which of the following sets of JavaScript do you prefer or think is better, and why?

Passing Objects

Method A

var o = {
  foo : 'bar',
  baz : true,
  bla : 1
};
fn(o);

Method B

fn({
  foo : 'bar',
  baz : true,
  bla : 1
});

Min-height

Method A


/* ala http://www.dustindiaz.com/min-height-fast-hack */
selector {
  min-height:500px;
  height:auto !important;
  height:500px;
}

Method B


selector {
  min-height:500px;
}
* html selector {
  height:500px;
}

DOM ‘load’ state

Method A

...
<style>
...
.dn {
  display:none;
}
...
</style>
<body>
...
<div class="dn">

Method B

<div style="display:none;">

Function Declaration

Method A

function fn() {
  // do stuff here
}

Method B

var fn = function() {
  // do stuff here
};

30 Responses to “Code choices: What’s better?”

  1. Kanashii

    1) B: I would assume it’s more efficient due to not needing a variable.
    2) B: You can label it a hack for easy viewing so you don’t have to dig to find it.
    3) A: Inline styles make me sad. If it’s for a javascript use only it should be inserted/hidden with javascript : ) otherwise hide it in the css part.
    4) B: Looks neater. And I’m not too familiar with Javascript scoping but I’m guessing it will be more efficient too.

  2. adam reitsma

    Thanks Dustin; always fun stuff to think about.

    Ok, my submissions are purely based on the code submitted, as submitted - I’m not going to infer any sort of context or anything like that, unless stated otherwise.

    Passing Objects:
    The only reason I would choose method a is if:
    - I was planning on re-using that object (passing it to other functions)
    - I were to name it something more descriptive (eg “animationProperties” instead of “o”)
    …otherwise, I would choose b.

    Min-height:
    Not Applicable.
    Firstly, this is not a set of javascript options, and these are not coding style choices.
    It’s a preference for hacks - choosing a lesser of evils, or whatever you may call it, but not worth going into. :)

    DOM ‘load’ state:
    Method a - simply because inline style declarations are uncool. (Seriously though, what if you decided you want to switch to ‘visibility:hidden’ for some reason?, I hope you’ll only have to change one style class entry!)

    Function Declaration:
    Whilst there could be reasons for choosing method b (such as if it was in another object/function), in this instance I would choose option a for readability.

  3. Andreas Næsager

    a, a, b, b

  4. Riddle

    Passing Objects: 1st one is nicer to me
    Min-height: Parser hacks are evil, full stop
    DOM ‘load’ state: Depends on how many times and where it would be put.
    Function Declaration: I got used to to 1st one

  5. Klaus Hartl

    Hi Dustin,

    1) Depends on if I want to reuse the object. If not I’d go for B, although it is less readable.

    2) B of course. I would also put the * html hack into an extra style sheet loaded inside of conditional comments (but still keep the hack to filter IE 7, which supports min-height). Another benefit from this: the basic style sheet is freed from hacks and smaller. Option A looks really ugly to me.

    3) B again. You cannot override inline styles (in IE, in other browsers it would work with !important), so I’d had no control over it in other media types like print. Also of course you end up in a maintenance nightmare with inline styles. Third if the plan is to change the state via scripting the element wouldn’t be visible to anyone with JavaScript disabled. In a nutshell, inline styles are really really bad-practice.

    4) I prefer A, because of readability and because I’m more used to it. But there are situations when I have to use B, for example for optional callbacks:

    
    var callback = null;
    if (typeof foo == 'function') callback = foo;
    

    Thanks Dustin, that was a nice way to start the day.

  6. Klaus Hartl

    PS: The style attribute is the new <font>.

  7. Andreas Stephan

    Min-height:
    This is my favourite solution for min-height/max-height. I use a conditional-comment to load an additional stylesheet for ie smaller than IE7:

    
    min{
      min-height:500px;
    }
    <!--[if lt IE7]>-->
    
        height: expression(this.height 
    
    

    The height is calculated using javascript. Of course, to make this fully unobtrusive you could still handle IE with JS turned of separately. The beauty of this solution is, that you can apply it to achieve the effect of many every css properties that are not supported by IE using DOM scripting, eg. switching styles accoring to an attribute of an element e.g.

    
    input{
      border: expression(this.type == 'radio' ? "1px solid red;": "none;");
    }
    

    For the other mentioned code choices I vote for first option.

  8. Mislav

    Is this followup a joke? Either none of the methods are good, or both methods are equally good, or it depends on what you are doing. There is no better/worse for each of these examples :-/

    DOM ‘load’ state: if you’re gonna show it with JavaScript then better hide it with JavaScript, too.

  9. Alex Leonard

    On the Min-Height point.. both look wrong to me.. Conditional Comments surely..

  10. Freddy

    Passing Objects: As many said before: depending on the re-use of the object.

    Min-height: Even if I tend to use Method A I usually choose between hacks (or if necessary against them) by looking at the circumstances.

    DOM Load State: I’d prefer Method A but usually rely on a JavaScript only solution.

    Function Declaration: Neither. I prefer JSON with no stray functions.

    (I am a pragmatist after all.)

  11. Peter Foti

    Passing Objects:
    Method C

    
    function myClass(foo,baz,bla) {
      this.foo = foo;
      this.baz = baz;
      this.bar = bar;
    }
    var o = new myClass('bar',true,1);
    fn(o);
    

    I’m not a big fan of object literals. :-)

  12. Peter Foti

    Min-height:
    I rarely find a need for min-height, but if I was to use it, I would probably use Method B (or the equivalent using conditional comments).

  13. Peter Foti

    DOM ‘load’ state:
    I’m not sure what *either* of those examples has to do with ‘load’ state! But of the 2, Method A looks better to me.
    I’m not a big fan of inline styles either. :-)

  14. Peter Foti

    Function Declaration:
    Method A. More readable in my opinion.

  15. stilist

    Passing objects: A; B isn’t scalable.

    Min-height: neither, because both assume IE messing up which isn’t guaranteed. A better solution is the “if IE” hack.

    DOM load state: I don’t know the intricacies of how this works, despite having read articles. Either way, I’m not sure why you’d automatically hide information, rather than hide it with JS or something. If you’re hiding it by default, it probably shouldn’t be there.

    Function declaration: It’s been my understanding that the “var fn = function () { }” style was more for JSON than function declarations.

  16. Justin Perkins

    Min-height/Max-height example is missing the most rock-solid solution:
    selector{
    min-height:500px;
    }
    /* via conditional comment */
    selector{
    height:expression(this.offsetHeight > 500 ? ‘500px’ : ‘auto’);
    }

    :)

  17. Elliot Swan

    Passing Objects: Probably A.
    Min-height: Something more similar to B, but I’d keep it in a IE-only stylesheet.
    DOM ‘load’ State: Best to set it with JavaScript using something like domready.js
    Function Declaration: Unless I’m creating an object, A is simpler.

  18. Sarven Capadisli

    @adam reitsma
    "what if you decided you want to switch to %u2018visibility:hidden%u2019 for some reason?"

    Inline styles has higher specificity then the external/internal styles, unless !important is attached to a property value. Javascript can override all these values as it is loaded after HTML and CSS. Therefore it doesn’t make any difference whether the style is defined in an internal stylesheet or inline.

    In my opinion, it is a better practice to not use inline styles for the sake of maintenance. As Klaus Hartl mentions above, in the case of no Javascript, it is still better to use external/inline stylesheets to degrade gracefully, as well as for specificity reasons.

  19. mike cravey

    Passing Objects: A, if for not other reason than modularity. I never know when I will want to reuse something later.

    Min-height: B, but only cause it allows me to put the whole block in a conditional style sheet.

    DOM ‘load’ State: A, for all the reasons that people have listed plus I try to use the least specific method necessary so that I can override it easily.

    Function Declaration: A, just cause it’s what I’ve always used.

  20. Klaus Hartl

    I think using dynamic properties to emulate min-height is a little over the top. Unless you don’t specify overflow other than visible, height is indeed min-height in IE6 - and that’s the most rock-solid solution I can think of. I assume you would put these dynamic properties in an extra style sheet as well as the simple hack, so what’s better:

    height: expression(this.offsetHeight > 500 ? ‘500px’ : ‘auto’);

    or

    height: 500px;

    :)

    I could also imagine that if you apply the expression to a whole lot of elements in the page it would significantly slow down the page (at least I made the experience with a whatever:hover solution of mine relying on dynamic properties solely - although a solution has been found for that).

    You also have to keep in mind, that toggling between a defined height and auto also toggles hasLayout, which can produce some nasty side effects on your layout. To prevent that you would have to add another declaration like “zoom: 1;” for example.

  21. Nathan Smith

    1. A - Passing Objects
    2. B - Min-height
    3. A - Dom Load
    4. B - Function Declaration

    Explanations:

    1. This way is best for passing objects, because then you don’t need to re-write the thing later if you need to reuse it.

    2. Sorry yo, but I don’t like your method for min-height because really that hack shouldn’t be in your primary CSS at all, and would be put in a different If-IE stylesheet.

    3. For DOM loading state - Are you kidding me? Anyone who uses an inline style for display: none; should be drug out and shot. That’s absolutely terrible for accessibility. I would probably link to an external stylesheet with document.write(), if it were something that should be visible with JS off though. That way they’re hidden with no messing up as the DOM loads, but are visible with JS off.

    4. I would chose to define a function as a variable, that way it can be used later within another function if it becomes necessary. Like in the first example, it doesn’t hurt anything to declare it that way, even if you’re not re-using it. Whereas, if you didn’t do it with re-usability in mind, you would find yourself going back through and making necessary changes later one - never fun.

  22. Justin Perkins

    Klaus, I find expressions to be the most reliable method of simulating max-height/min-height in IE. 9/10 when you’re using max-height, you are also doing something like:

    
    #element{
      width:400px;
      overflow-x:hidden;
      overflow-y:scroll;
      max-heigth:200px;
    }
    

    Or something similar, where the net goal is to allow content to flow naturally, but up to a finite point. Also, the typical usage is very specific to a certain element on the page, not just some global selector that would cause any sort of slow loading time. whatever:hover is no comparison whatsoever to using an ID selector for one expression() stataement. whatever:hover is quite a bit more complicated (calling an external file through an expression and applies itself globally to the body.

    In other words, in the *real world* expression()s work quite well when used wisely.

  23. Harmen Janssen

    Passing objects: Method A looks more well-organized, although method B saves a few bytes probably if your code is long and complex.

    Min-height: Usually method B (although not with hacks but Conditional Comments), but I have to say I like the look of your “min-height-fast-hack” :)

    DOM Load State: If the element only got something to do with Javascript, create and hide it with Javascript (Method B). If not, I just put the style rules in my stylesheet.

    Function Declaration: Method A. ‘Cause it looks better to me.

  24. Nicholas C. Zakas

    Passing objects: If you are creating the object just to pass it into a function, then method B is better because it minimizes the pointers to the object, ensuring the memory will be properly reclaimed. If you need the object after the function call, then method A is preferable.

    Min-height: Neither, try not to use min-height until it’s actually supported. :)

    DOM load state: Method B is preferrable because it’s easier to access via the JavaScript style object. Since the content is hidden using either method, screen reader accessibility really isn’t an issue.

    Function declaration: If the function is global, use method A. If the function is local (inside of another function), use method B. Keeps coding looking logical.

  25. Ross Hill

    As it is a personal site, whatever you find more friendly :) It has to be easily readable and updatable by you otherwise it won’t happen - and that is the common cause of a dead blog.

  26. Klaus Hartl

    Has anybody tested the expression for min-height? I found that it makes IE crash, I think it gets trapped in an infinite loop:

    
    height: expression(this.offsetHeight < 500 ? ‘500px’ : ‘auto’);
  27. Theodor Zoulias

    Function declaration: Method A has a practical advantage. It permits invocation before declaration.

  28. D-man

    Thanks for explaining the passing objects; I had trouble with understanding how and when exactly it can be reused.

  29. Ronin Oni

    Only in regards to inline styles, as I noted many people have strong objections to such. They do have a place. If you are hiding showing divs like windows, or using any number of dom-drag scripts they sorta require use of inline declaration of x/y positions and visibility/display properties.

    Also, I find inline usefull when there are a couple attributes I want to change for a specific element, which shares a class with other elements I don’t want to change the attributes of.

    Bassically I place everything I won’t be dynamically changing into the inline, and everything else I can into the css libraries. Just my 2 cents

    Oh yah, and avoid min/max height and width like the plague. Honestly Sizing and positioning for cross browser has become the bane of my existance of late. IE and Firefox are polar opposites in every aspect creating all kinds of spacing problems. and min/max doesn’t work in both (I forget exactly where the problems lie, because once I found it was unreliable i stripped it from my mind) But for other cross-browser problems, margins, borders, padding are all handeled differently. One places borders on the inside of the div (shrinking the actual space of the div) the other actually places it on the outside, increasing your height,width by double the border declaration. This of course varies in regards to margins and padding. I don’t know how many websites I have where FF has a lil to much blank space and IE is just a little tight becuase of these ridiculous inconsitancies

  30. Ronin Oni

    Almost forgot, there is a way around the border problem.

    
    
    
    

    This will create a 100×100 white box with a 2px gray “border” that is handeled the same by all browsers. Annoyingly stupid that browser incompatibility requires this, but it works

Leave a Reply

Phone Number:

If you're about to post code in your comment, please wrap your code with the tag-combo <pre><code>. Also please escape your html entities - otherwise they will be stripped out. I recommend using postable.

Get "JavaScript Design Patterns"

"As a web developer, you'll already know that JavaScript™ is a powerful language, allowing you to add an impressive array of dynamic functionality to otherwise static web sites. But there is more power waiting to be unlocked--JavaScript is capable of full object-oriented capabilities, and by applying OOP principles, best practices, and design patterns to your code, you can make it more powerful, more efficient, and easier to work with alone or as part of a team."

Buy JS Design Patterns from Amazon.com Buy JS Design Patterns from Apress

Flickr

Submit a Prototype

All content copyright © 2003 - 2007 under the Creative Commons License. Wanna know something? Just ask.

About | Archives | Blog Search

[x] close

Loading...

Submit a prototype

By checking this prototype I agree that I am not submitting false credentials, pornography, or a hate crime website. I also understand that by submitting my entry I may or may not be accepted, and if accepted, my entry may be taken down at any given time if I violate these terms.