0

I wrote a function with a closure within it and i also wrote another function.

function argum(){
  let ist = arguments[0];
  return function(){
    return ist + ' ' + arguments[0]
  }
}

function logAll(){
    console.log(arguments.length);
}



var sh = argum('hello')
sh('world')

logAll(2,4,5,6,7)

As shown above, but i can't understand why the first call on the closure generates undefined. Meanwhile if i rewrite the code like this

function argum(){
  let ist = arguments[0];
  return function(){
    return ist + ' ' + arguments[0]
  }
}

function logAll(){
    console.log(arguments.length);
}

logAll(2,4,5,6,7)

var sh = argum('hello')
sh('world')

it seems to work fine. Any hint on what's happening there? Also use your browser dev tools to run this code, for a better understanding of what am asking.

Jude
  • 1
  • 6
  • 2
    I don't see any difference. `sh('world')` doesn't log anything, so there's no output from that. – Barmar Nov 14 '17 at 22:15
  • 1
    I get `"hello world"` in both cases. – Barmar Nov 14 '17 at 22:19
  • 1
    Are you pasting the whole thing into the console at once? Chrome only shows the result of the last expression when you paste multiple expressions. – Barmar Nov 14 '17 at 22:22
  • `logAll` is not even related to your closure function. It would not affect anything. – Nandu Kalidindi Nov 14 '17 at 22:23
  • @NanduKalidindi He seems to be saying that the result of `sh('world')` depends on whether you do it before or after `logAll(2,4,5,6,7)`. That's why it's relevant. – Barmar Nov 14 '17 at 22:24
  • it shows `5` for me in both cases `(Chrome)` – Muhammad Omer Aslam Nov 14 '17 at 22:27
  • 1
    @deity, try this: `function logAll(){ console.log(arguments.length); return "What's up?" }` Does this solve your confusion about `undefined` or did that make it worse? – Thomas Nov 14 '17 at 22:28
  • hey guys now i get, issue seems to be from my browser. Ran the code from a separate js file with no issues, thanks all for your contributions. – Jude Nov 14 '17 at 22:48
  • It's not an issue at all. It's how the console behaves when you paste something in there. It evaluates *all* your code and at the end, it logs the result of the last expression. Only in your case, your last expression evaluated to `undefined` because that's what `logAll()` implicitely returned. For the same reason, the console "logs" `3` when you enter `1+2`, even without explicitely calling `console.log()`. – Thomas Nov 14 '17 at 23:27
  • Yeah, noticed it just now, thanks for the insight – Jude Nov 15 '17 at 07:21

0 Answers0