3

I got stuck at a problem in JavaScript which uses the concept of function scope. Particularly, this is what I need to solve:

Define a function named callFunc that takes one argument, a function f. It should return an array containing the values f(0), f(0), f(1), f(1). You can only call f twice.

My code so far is:

var f = function(x) {
    return x+2;
};

var callFunc = function (f) {
    return [f(0), f(1)];
};

I don't know how I can return an array of four elements using only two calls and the JavaScript function scope principles.

1 Answer 1

6

It's really quite simple:

function callFunc(f) {
    var f0, f1;
    f0 = f(0);
    f1 = f(1);
    return [f0,f0,f1,f1];
}

I'm... not entirely sure why you'd have trouble with that. Reducing the number of function calls is something you should be doing anyway (and it's why I cringe at most jQuery code that has $(this) in it like 20 times...)

Sign up to request clarification or add additional context in comments.

4 Comments

Relating to the note about calling $(this) 20 times: most front end code should execute asynchronously and perform only minimal work. Because the code generally isn't being executed as part of a UI loop, and instead is being called sporadically these sorts of micro-optimizations are largely unnecessary. In instances where optimization is important, reducing function calls is certainly one useful technique, but sometimes writing code clearly is more important than writing code that's as fast as it could possibly be.
@zzzzBov I mean when you see things like var t = $(this).text(); $(this).text(t+"123"); (over-simplification). Basically, repeated calls to $(this) when you could just do $this = $(this) up front and simply reference $this thereafter.
I'm not sure if your code is corect. Here is the link to the problem I'm trying to solve: Function scope
Oh yes, it was simpler than I thought. Thank you, I just started learning JavaScript yesterday.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.