javascriptfunctionarguments-object

Using arguments pseudo-parameter as a writeable thing


In javascript, there is such thing as arguments pseudo-parameter, which allows to interact with function arguments dynamically. Now, while I'm listening to the lecture about javascript fundamental things & standards, there was a phrase:

"Don't use arguments as a writable structure, always treat is as a read-only thing"

I never used arguments to write there, so it's not a problem for me - but, really - I want to ask my

Question: are there any real use-cases when using arguments to write there is justified? If not, then why shouldn't arguments be used to write there?


Solution

  • Let's suppose you're mad and you want to customize console.log so that doing

    console.log("window.innerWidth");
    

    would log

    window.innerWidth = 775 
    

    which seems more convenient than doing

    console.log("window.innerWidth =", window.innerWidth);
    

    You could do it "properly", by building a new array or you could reuse arguments :

    (function(){
      var stdlog = console.log;
      console.log = function(){
        if (arguments.length===1 && typeof arguments[0]==="string") {
          try {
           arguments[1] = eval('('+arguments[0]+')');
           arguments[0] += " =";
           arguments.length = 2;
          } catch (e) {} // in case it can't be evaled, do the normal thing
        }
        stdlog.apply(console, arguments);
      };
    })();
    
    console.log("window.innerWidth"); // window.innerWidth =  775 
    console.log("Hello"); // Hello
    

    Reusing arguments here would have the advantage of not having to build an array when you don't need it and not repeating the call to stdlog. The code would be less dry without that hack.

    Now, why you should not do this kind of things :

    Here's a case in which the strict mode changes everything :

    function incrNumber(v) {
      arguments[0]++;
      console.log(v)
    }
    

    In strict mode, the passed value is logged. In non strict mode, the incremented value is logged. And that's the specified behavior.