Does const always go at the top?

I would like to open this up to the forum and try and get as many people’s thoughts on this.

Basically what I’m trying to find out is,
Is it better to group the selector together, or not.

Does keeping the selectors that match the handlers make more sense?

Like how this one is set up?
https://jsfiddle.net/192h0w85/123/

(function iife() {
    "use strict";
    const player = document.getElementById("player");
    const button = document.getElementById("button");
   
    button.addEventListener("click", function () {
        if (player.paused) {
            player.play();
        } else {
            player.pause();
        }
    }); 
    
    const value = document.getElementById("input");
    const sent = document.getElementById("sent");

    sent.addEventListener("click", function () {
        player.volume = 1.0;
        player.src = value.value;
    });
}());

As opposed to this?

Which would be grouping them altogether.
https://jsfiddle.net/192h0w85/122/

(function iife() {
    "use strict";
    const player = document.getElementById("player");
    const button = document.getElementById("button");
    const value = document.getElementById("input");
    const sent = document.getElementById("sent");
    
    button.addEventListener("click", function () {
        if (player.paused) {
            player.play();
        } else {
            player.pause();
        }
    });
    
    sent.addEventListener("click", function () {
        player.volume = 1.0;
        player.src = value.value;
    });
}());

I’m not sure what “best practice” would be for this, but I’ve tried it both ways and I find it easier to read when all the document./*pick your selection method*/("hook");'s are at the top.

1 Like

Its best practise to keep all declared variables in the top of functions.

1 Like

Not always. I prefer it too, but this is not a place for a blanket statement. It depends on the style guide you are following. For example, all AirBnB says is to assign variables where you need them but be reasonable.

Meant generally consts and cached DOM elements. If you need a let before a loop its okay to declare it close to the loop for readability. Most of the times the functions should stay relative short, so then I would prefer to keep used variables togheter in the top of the function.

I’m a full-time web developer. It’s really all about preference. Personally I prefer them defined where they’re used. With that said, you function shouldn’t be so big that you can’t find it.

1 Like