What do you think about a C# 6 like nameof() expression for JavaScript.

# Behrang Saeedzadeh (9 years ago)

So basically we could use it like this:

function aFunc(aParam) {
    throw new Error(nameof(aParam));
}

and nameof(aParam) would return the string "aParam".

This is possible to do even right now using arguments.callee and some hacky code, but having it built-in to spec would be nicer IMHO.

# Behrang Saeedzadeh (9 years ago)

Forgot to mention that nameof works with local variables too:

function foo() {
 var aNum = 1;
 console.log(nameof(aNmum), aNum);
}
# Isiah Meadows (9 years ago)

Call me crazy, but I don't see anything that couldn't be done more concisely with a string literal. Is it supposed to be able to do this?

function foo(x) {
  return nameof(x);
}

foo(bar); // "bar";

In that case, the engine would have to keep track of usages as well, in a similar sense as arguments.callee, and if it were a function, it would make optimization quite difficult, as engines don't have the capacity to statically analyze that such a function is used.

If it is like typeof, we now have a breaking change - a keyword that was a valid Identifier before.

// Error?
function nameof(value) {
  return value.name;
}

var bar = {name: 2};
nameof(bar); // "bar" or 2?

I don't think this is going to work out in practice, not in ECMAScript proper. You might appreciate Sweet.js, though.

# Ron Buckton (9 years ago)

One of the main purposes of the nameof operator is to provide the string value of a symbol, so that if you perform a "Rename" refactoring of that symbol that the change is also reflected. This is primarily for cases where you perform precondition assertions tied to an argument:

  ...
  static void Method(string x) {
    if (x == null) throw new ArgumentNullException(nameof(x));
    ...
  }

Now, if I later rename x, I don't need to also find any string literals of "x" and manually update them.

There are other uses of nameof, but they all boil down to roughly the same thing.

# Isiah Meadows (9 years ago)

To be honest, most larger IDEs also search for references in strings, and even if it doesn't, any decent editor can do a regex replace of identifierName without problem. I don't see much of a problem here. Also, do you know of any other language that has this at the syntax level (not macro)?

# Ron Buckton (9 years ago)

While its true most IDE's can search for references in strings, nameof takes some of the guesswork out of determining whether a substring that matches a symbol refers to the symbol or is merely part of the sentence.

That said, nameof is primarily a convenience for an IDE.

# Waldemar Horwat (9 years ago)

This would have interesting consequences if you run your code via a minifier. Should the minifier return a string with the old name or the new name?

# Behrang Saeedzadeh (9 years ago)

It depends I guess. Should be a configuration option.