Reputation: 2019
I am curious as to why this function does not work. I've noticed that it is returning undefined instead of an anonymous function object as I would expect.
function localizeGreeting(language) {
(function(lang) {
if (lang === 'en') {
return function(firstname, lastname) {
console.log('Hello' + firstname + ' ' + lastname);
}
}
if (lang === 'es') {
return function(firstname, lastname) {
console.log('Hola' + firstname + ' ' + lastname);
}
}
})(language);
}
var test = localizeGreeting('en');
test('Dave', 'Matthews');
Upvotes: 2
Views: 88
Reputation: 559
This is not the correct approach. You do not need an IIFE out here. The below solution would work
function localizeGreeting(lang) {
if (lang === 'en') {
return function(firstname, lastname) {
console.log('Hello' + firstname + ' ' + lastname);
}
}
if (lang === 'es') {
return function(firstname, lastname) {
console.log('Hola' + firstname + ' ' + lastname);
}
}
}
var test = localizeGreeting('en');
test('Dave', 'Matthews');
Upvotes: 2
Reputation: 887547
Your outer function doesn't return anything.
It calls an inner function that returns a value, but it then ignores that return value.
Side note: There is no reason to have the intermediary IIFE in the first place.
Upvotes: 6