MyDaftQuestions
MyDaftQuestions

Reputation: 4691

How can a parameter exist when no argument is passed?

I'm new to Javascript, although I have a .net background. Typically in .NET (as well as many other languages), if a method requires a parameter to be passed, you have to pass it (or else compiler error due to incorrect signature). This also appears to be the case in JavaScript, but not all cases it would appear.

This doesn't appear to be the case in Javascript.

As a working example, please refer to line 61

http://www.humblesoftware.com/flotr2/#!basic-axis

Line 61 is tickFormatter: ticksFn,

I understand that tickFormatter is calling a function called ticksFn but line 29 shows

function ticksFn(n) {
    return '(' + n + ')';
}

'ticksFn' requires a value (n) to be passed, yet, we never pass it.

Despite that, javascript still gets it right and I can't find out how, nor can I work/understand what to search for to do more research

Upvotes: 0

Views: 198

Answers (2)

Mohammed R. El-Khoudary
Mohammed R. El-Khoudary

Reputation: 1203

In javascript it is not required to pass the parameters for a function as a value of undefined is passed if you don't.

So a function:

function ticksFn(n) {
return '(' + n + ')';
}

Can be invoked:

ticksFn();

Without any problem and the value of the n will be undefined..

Alternatively a function defined with no arguments:

function ticksFn() {
return '(' + arguments[0] + ')';
}

And calling:

ticksFn(10);

arguments[0] will be 10. and accordingly you can read any number of arguments.

That was a quick tutorial about javascript functions.. now about your code.. javascript is a function oriented language and so writing the function name without parentheses actually hands reference on the function rather than calling the function itself..

Upvotes: 0

Quentin
Quentin

Reputation: 943220

You never call it at all. You pass the function itself as an argument (or rather as the value of a property of an object that is an argument).

graph = Flotr.draw(container, [ /* ... */], {
      xaxis : {
        noTicks : 7,              // Display 7 ticks.
        tickFormatter : ticksFn,  // Displays tick values between brackets.
        // …

Your third party library code is responsible for actually calling that function, and it does so with an argument.

Upvotes: 1

Related Questions