I recently saw this questions:
function compareMembers(person1, person2 = person) {
if (person1 !== person2) {
console.log('Not the same!');
} else {
console.log('They are the same!');
}
}
const person = { name: 'Lydia' };
compareMembers(person);
By seeing this, I am wondering how person
can be the default value for person2
.
const
are not hoisted unlike var
. And even if I try to do a console.log(person)
before function compareMembers
I am getting Reference error.
IF any one can explain me how come the function has access to person
as default value it would be really a great help.
CodePudding user response:
Your code will run like this:
- Stored variables to Stack (
compareMembers
,person
). And referent to Heap Memory - Stored object, function to Heap Memory (dynamic)
{ name: 'Lydia' }
and
function compareMembers(person1, person2 = person) {
if (person1 !== person2) {
console.log('Not the same!');
} else {
console.log('They are the same!');
}
}
Then run Call Stack
- compareMembers(person)
You can read document of call stack and stack and heap memory
CodePudding user response:
JavaScript, as you know, is applied line by line In the first part, you came and created the function and did what you wanted inside
You take the first input from the user and the second input by default, if it does not work, you fill it with a variable
Now, in the next part, you created a variable, my friend, and you gave a function to this input, and this actually applies to both of your inputs, and this is absolutely true.
It only works in the opposite condition in your function if you give two inputs with different values
I hope I was able to help my friend