JavaScript: dot vs bracket notation

During linting my code jshint gave me the “hint” that I should prefer dot notation over bracket notation.

"testcase": data.finding["testcase"], [‘testcase’] is better written in dot notation.

What is that?

  • Accessing members with “.” is called “dot notation”.
  • Accessing them with [] is called “bracket notation”.

 

KnockoutJS: passing parameters to components

HTML

<my-component params='from: "foo"'></my-component>

JS

class MyViewModel {
    constructor(params) {
        console.log(params["from"]);
    }
}

ko.components.register('table-edit', {
    template:
        ``,

    viewModel: {
        createViewModel(params) {
            return new TableViewModel(params);
        },
    }
});

Inefficient jQuery Selectors

My PyCharm IDE warns me if I use inefficient jQuery selectors:

As I am a bit nosy I wanted to know “how” inefficient these selectors are. So I compared the inefficient

$("#items tbody");

with the optimized

$("#items").find("tbody");

Here is the test code:

window.onload = function () {
    test("unoptimized", function () {
        for(var i = 0; i < 100000; i++){
            $("#items tbody");
        }
        assert(true, "Test finished");
    });
    test("optimized", function () {
        for(var i = 0; i < 100000; i++){
            $("#items").find("tbody");
        }
        assert(true, "Test finished");
    });
};

I used the little test framework from the book Adventures of the JavaScript Ninja

The results vary from run to run but the optimized version just takes around 55% of the time which makes it almost twice as fast. Though the single execution is in the nanosecond range, if you heavily rely on using jQuery, it might be worthwhile to optimize your selector statements.

Code on GitHub