0

I often like to say that JS is not my home language and that's led me to this question.

import Dropzone from "dropzone";

let myDropzone = Dropzone({
  paramName: "file", // The name that will be used to transfer the file
  maxFilesize: 2, // MB
  accept: function(file, done) {
    if (file.name == "justinbieber.jpg") {
      done("Naha, you don't.");
    }
    else { done(); }
  }
});

The preceding code is from Dropzone website about their great file upload tool.

The else done() confuses me. How would you know that's a function if you were calling this? Done sports appears to be a parameter to me. If I'm using a good IDE, would I be directed as such? If not how do I know?

Paul Duer
  • 1,100
  • 1
  • 13
  • 32
  • 1
    Well, you would know by reading the documentation, I would hope. Otherwise, you could always use the `typeof` operator on it to find out `if (typeof done === 'function') { done(); }`. The title question is a bit odd; it becomes a function call when you invoke it as a function call, using parentheses. Functions are variables just like any other. – Heretic Monkey Mar 07 '22 at 03:44
  • the documentation for the `accept` property passed to `Dropzone` function would specify that `accept` is a function that takes a `file` as the first argument, and a callback function as the second - and (perhaps internally?) the accept function is called with the correct arguments - do you ever call that `accept` method or is it purely an internal method for `Dropzone` to use when required? – Bravo Mar 07 '22 at 03:47
  • If you were using TypeScript or JSDocs, you would get an error in your IDE – Samathingamajig Mar 07 '22 at 03:47
  • @Samathingamajig - if I had 4 wheels and an engine I'd be a car - what's your point – Bravo Mar 07 '22 at 03:48
  • @Bravo what do you mean? – Samathingamajig Mar 07 '22 at 03:49
  • OP isn't using TypeScript or JSDocs, and who knows if his IDE even would show an error (not all IDE's are created equal) so your comment doesn't help the question at all – Bravo Mar 07 '22 at 03:50

2 Answers2

0

In Javascript, every function is an object, and can be used just like an object.

You can call

console.log(typeof done)

to see that the parameter is a function.

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
0

JS uses duck typing, which in this case means that the value of done is checked just before trying to call it. If it's callable, everything is good. If not, an error is thrown at runtime.

As to whether your IDE will tell you about this, that will depend on how good your IDE is at doing static typechecks, but I'd assume it's not a common feature. Duck typing is very permissive, making it generally difficult to determine whether some code will throw an error without running it.

RShields
  • 316
  • 1
  • 8