EDIT: ADDED OBJECT
I'm having an issue with a variable declared within the body of a function that seems to disappear before the variable is returned from the function:
var customerData = {
'Joe': {
visits: 1
},
'Carol': {
visits: 2
},
'Howard': {
visits: 3,
},
'Carrie': {
visits: 4
}
};
function greetCustomer(firstName) {
var greeting = '';
for(var key in customerData){
if(key === firstName){
if(customerData[key]['visits'] === 1){
greeting = "Welcome back, " + firstName + "! We're glad you liked us the first time!";
console.log(greeting); // here to illustrate issue
}
else if(customerData[key]['visits'] > 1){
greeting = "Welcome back, " + firstName + "! So glad to see you again!";
console.log(greeting);
}
}
else{
greeting = "Welcome! Is this your first time?"
}
}
return greeting;
}
greetCustomer("Joe");
And the output:
Welcome back, Joe! We're glad you liked us the first time! // here is the correct greeting from the console output
=> 'Welcome! Is this your first time?' // this is what I got
Welcome back, Carol! So glad to see you again! // correct output again
=> 'Welcome! Is this your first time? // base case again.
Shouldn't greeting be visible throughout the function for accessing its value and for assignment as well? I know that I can just return the greeting from the branch, but I'm unsure as to what I'm seeing here, but I hope someone can explain. Thanks.
greetingvariable. Only the value set in the last iteration is returned.greetCustomerfunction. Does yourcustomerDatahave a keyJoe? Step through your for loop and compare the input Joe to the object.