I happened to find an issue with the weird behaviour of scope in the javascript
const obj = {
name : "alex",
isLoggedIn : true
};
if (true) {
function takeobject(str) {
console.log("hello1");
return `my name is ${str}`;
}
}
function takeobject(myobj) {
console.log("hello2");
return myobj['name'] ? `the object is ${myobj['name']}` : "hello there!";
}
console.log(takeobject(obj));
The output is :
hello1
my name is [object Object]
I created an object name obj with two members name and isLoggedIn
then in the if statement with true condition i created the function takeobject which takes parameter str (supposed to be string).
Then another function in global scope with same name takeobject which takes parameter myobj (supposed to be an object).
Now, after executing the code, the console prints my name is [object Object] i.e., it calls the function inside the if block even though the passed argument is an object.
Why the global function takeobject is not called?
I tried using both functions in same and different if(true) block(s) then the the function takeobject(myobj) is called as it is redefining it but when doing the above, the function takeobject(str) is being called instead of function takeobject(myobj) even though takeobject(myobj) is global and it should redefine it.
const obj = {
name : "alex",
isLoggedIn : true
};
if (true) {
function takeobject(str) {
console.log("hello1");
return `my name is ${str}`;
}
function takeobject(myobj) {
console.log("hello2");
return myobj['name'] ? `the object is ${myobj['name']}` : "hello there!";
}
}
console.log(takeobject(obj));