Reputation: 57
I'm practicing my js functions and came through an error that is not so obvious for a beginner. The problem is the function won't define my second variable. It works when I declare my variables outside, but I'm interested on the inside. Heres the code.
(function (firstname, lastname){
var firstN = 'Hubba';
var lastN = 'Bubba';
console.log(firstname + ' ' + lastname)
}(firstN, lastN));
Upvotes: 1
Views: 950
Reputation: 2640
You're asking for the firstN
and lastN
values outside of the scope of your IIFE, which are undefined
in the outer scope. Look into how block scope works.
// SO snippets don't allow undefined vars so we can mimic it using `window` like would be in the browser
var window = {};
console.log(window.firstN); //undefined
console.log(window.lastN); //undefined
var firstN = "Foo";
var lastN = "Bar";
(function(firstname, lastname){
var firstN = "Happy";
var lastN = "Go Lucky";
console.log(firstname + " " + lastname); // 'Foo Bar'
console.log(firstN + " " + lastN); // 'Happy Go Lucky'
})(firstN, lastN)
Upvotes: 1
Reputation: 21575
That's because inside the function the variables firstN
and lastN
are local variables to the functions scope. This means they only exist inside of your function when you execute it.
So when you try to call your function by doing (function(..){...}(firstN, lastN))
those variables you pass are outside the scope of your function, as such they aren't defined.
For example if I did:
var firstN = 'Hubba_1';
var lastN = 'Bubba_1';
(function (firstname, lastname){
var firstN = 'Hubba_2'; // Not needed
var lastN = 'Bubba_2'; // Not needed
console.log(firstname + ' ' + lastname)
}(firstN, lastN));
You will notice that it prints Hubba_1
and Bubba_1
. The outside firstN
and lastN
are entirely different variables compared to the variables firstN
and lastN
inside your function.
Upvotes: 3