javascriptcalling-conventionuse-strict

"use strict" and naming arguments in function calls


A colleague advised me to add "use strict"; to the top of my JS code to highlight any gaps in my definitions and potential reference errors, etc. I am very happy with it because it has identified several pieces of code which might have been a problem down the line.

However, another colleague advised me that when calling functions which take multiple arguments, it can be helpful to name the arguments as they are specified, especially if it's something like a bunch of booleans. To illustrate, here's a couple of function calls:

logData(data, target, preserveLog=true, changeClass=false, wrapLine=false);

...is a whole lot clearer than:

logData(data, target, true, false, false);

But "use strict"; hates this. everywhere I've done this, I get a reference error in the console. It still runs fine, as would be expected, but the console is now cluttered with all these apparently non-defined references.

Does anyone know if there's a way around this so that I can keep my coding conventions which my colleagues appreciate, or am I going to have to either stop using "use strict"; or go through all my code and remove the names of arguments?

Thanks.


Solution

  • However, another colleague advised me that when calling functions which take multiple arguments, it can be helpful to name the arguments as they are specified, especially if it's something like a bunch of booleans.

    This is terrible advice!

    Javascript doesn't actually support passing arguments by name this way. Each of the arguments you pass "by name" is actually being treated as an assignment to a global variable with that name, and "use strict" is correctly identifying this as an error.

    If you want to be more clear about what values you're passing, assign the values to real local variables and pass those, e.g.

    var preserveLog = true;
    var changeClass = false;
    var wrapLine = false;
    logData(data, target, preserveLog, changeClass, wrapLine);
    

    If you really wanted to keep using your original pattern, you could even assign to those variables in the function call, so long as you declare them as local variables first:

    var preserveLog, changeClass, wrapLine;
    logData(data, target, preserveLog=true, changeClass=false, wrapLine=false);
    

    (With a hat-tip to dav_i for this answer, which I based my recommendation off of.)