Fred J.
Fred J.

Reputation: 6049

javascript module using closure and a function

This code is my first attempt to create a module which gives the full name when given the nick name. but I am getting undefined in the results and don't know why. Thanks

let nameProper = (function nameProper (nameShort) {
  let names = {
    "fj": "Fred Johnson"
  };
  return function () {
    return names['nameShort'] || nameShort;
  };
}());

let myName = nameProper('fj');

Upvotes: 1

Views: 35

Answers (2)

user4244405
user4244405

Reputation:

Alternatively:

let nameProper = function(nameShort)
{
    return this.names[nameShort] || nameShort;
}
.bind
({
    names:
    {
        "fj": "Fred Johnson"
    }
});

let myName = nameProper('fj');

Upvotes: 0

Casey Foster
Casey Foster

Reputation: 6020

const nameProper = (function () {
  const names = {
    fj: "Fred Johnson"
  };

  return function (nameShort) {
    return names[nameShort] || nameShort;
  };
})();

let myName = nameProper('fj');

You need to pass your argument to the inner function, not your closing function that is invoked immediately.

Upvotes: 2

Related Questions