0

Is it possible to get the name of the variable passed in as an argument from inside of the function, if a variable has been passed in?

function foo(bar){
  // how to get the string `obj`?
}

const obj = {a:1};

foo(obj)
melpomene
  • 84,125
  • 8
  • 85
  • 148
Gunther
  • 561
  • 8
  • 12
  • 3
    What would you expect from the call `foo(3)`? Or `foo(1+2+3)`? Or `foo(sum([1,2,3]))`? – Scott Hunter Oct 01 '19 at 18:07
  • what you really want I mean 1. are you really want to know about passed parameter name . 2. or you want to use its value – Er. Amit Joshi Oct 01 '19 at 18:10
  • 2
    @Er.AmitJoshi OP's code seems to specifiy that they want the string `\`obj\``, *not* its value. – Tyler Roper Oct 01 '19 at 18:11
  • 3
    @EternalHour I don't believe that's a duplicate. It fetches the names of the function *parameters*, not the passed-in *arguments*. – Tyler Roper Oct 01 '19 at 18:12
  • It's definitely not a duplicate, he wants the name of the variable in the outer scope, which is not possible. The corner cases provided by @ScottHunter reveal a fundamental problem with the goal proposed by the OP which were likely not considered when asking the question. – Jake Holzinger Oct 01 '19 at 18:15
  • 1
    I would assume this is impossible, given that the `function foo(bar)` is never passed the string `"obj"`; as far as I'm aware, it's passed solely the value that the variable represents. – Tyler Roper Oct 01 '19 at 18:17
  • For the record: It was proposed that https://stackoverflow.com/questions/1007981/how-to-get-function-parameter-names-values-dynamically is a duplicate, but that "*fetches the names of the function parameters, not the passed-in arguments.*" as mentioned in the comments. – str Oct 01 '19 at 18:22
  • @ScottHunter the question was to get the name of a variable. in your examples, `foo(3)` and `foo(1+2+3)` and `foo(sum([1,2,3]))`; `3` is not a variable, nor is `1+2+3` nor the other... – Gunther Oct 01 '19 at 18:56
  • @Gunther: That was the point: there might not be a variable to get the name of, and `foo` can't tell the difference. – Scott Hunter Oct 01 '19 at 18:57

0 Answers0