#### Archived

This topic is now archived and is closed to further replies. # function within a function within a function wrapped in a puzzle...

## Recommended Posts

I recently filled out a job application for a web developer position. In addition to the usual 'tell us about yourself' questions, I was presented with this one. After searching the web and hacking at it for nearly an hour. I just punched in 5. I'm sure it's wrong. Anyway, I was wondering if someone could give me some clarification on what is happening here:

<?php
/* What value should you replace the '?' with to make the output read 10? */
var x = 6;
var y = 4;
var a = function(b) { return function© { return y + b + c; } };
x = 2;
y = 5;
var fn = a(x);
x = 1;
y = 3;
var unknown = ?;
console.log(fn(unknown));*
?>

Am I reading correctly that the value of var a is equal to the value returned by function(b) which is equal to the value returned by function© which is y + b + c? I concluded that the value of var a = 4 + 2b + 2c. But since var b and var c are not defined how would I go about getting a strictly numeric value as output?

Pardon my ignorance, but I have faced questions like this for other job apps and I am tired of staring at the screen like an idiot! Any clarification would be greatly appreciated!

##### Share on other sites

I also just realized that the original was actually Javascript and not PHP. Still, the basic logic should be the same from one to the other. replace var with \$ and it should be the same, right?

##### Share on other sites

5 is correct.

The last executed statement reads as:

console.log(fn(5) => { y=3 + b=2 + 5 });

y is a reference inside the function and b has the local value 2 from x.

##### Share on other sites

Am I reading correctly that the value of var a is equal to the value returned by function(b) which is equal to the value returned by function© which is y + b + c?

`a` is equal to the function itself, not it's return value. a(x) is equal to the return value of function(b) which is itself another function.

```var fn = a(x);
```
That line locks `b` in as the current value of x, which is 2. So `fn` gets assigned the value `function(c){ return y + 2 + c; }`

```console.log(fn(unknown));
```
When fn is executed there, `c` comes from `unknown` and `y` takes the value of the global `y` definition, which at that moment is 3, so the equation would look like: `3 + 2 + c`. So then it's just a matter of solving for c

```10 = 3 + 2 + c;
10 = 5 + c;
10 - 5 = c;
5 = c;
```

×

• #### Activity

• Chat
×
• Create New...

## Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.