Understanding Closures in JavaScript.

Downloaded photo from Unsplash
function addLastName(fname){
lname = ' Wick'
function getFullName(){
return fname + lname;
}
return getFullName();
}
console.log(addLastName('John')) // logs - John Wick
function addLastName(fname){
lname = ' Wick'
function getFullName(){
return fname + lname;
}
return getFullName;
}
let getName= addLastName('John');
console.log(getName()) // logs: John Wick
function addLastName(fname){
lname = ' Wick'
return {
setLastName: function(name){lname = name},
getName: function(){return fname + lname}
}
}
let obj = addLastName('John')
console.log(obj.getName()) // logs: John Wick
obj.setLastName('BabaYaga')
console.log(obj.getName()) // logs: John BabaYaga

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store