Reputation: 17
console.log(String(console.log('Not undefined')) === 'undefined');
console.log(String(console.log('Not undefined')) !== 'Not undefined');
I feel this two lines of codes are supposed to give me the false but ?if someone can explain to me?thanks
Upvotes: 2
Views: 112
Reputation: 30416
Let's break this apart into levels that will make this behavior cleaner. First take the inner most command inside the first line:
console.log('Not undefined')
Here the console.log
function is echoing "Not undefined"
but it is returning undefined
. This is the default behavior of all functions in JavaScript. If they do not explicitly return something they will return the undefined
value. From there we step one level out to the casting of undefined
to a string
with this line:
String(console.log('Not undefined'))
Which if we combine with the previous insight would appear like this to the JavaScript run-time:
String(undefined)
This is evaluating to the string "undefined"
. Next you are doing a literal comparison (===
compares values and types) which evaluates to true
.
The second line is the same, only now you are comparing that String(console.log('Not undefined'))
is not 'Not undefined'
which it is not so you get true
as well.
Upvotes: 3
Reputation: 40638
console.log(String(console.log('Not undefined')) === 'undefined');
For the first one, you have from the deepest call: console.log('Not undefined')
which obviously outputs Not undefined
. Then the result (not the actual given string in the console) is given to the String()
function which returns the string version of undefined
which is 'undefined'
. All in all when compared to 'undefined'
it returns true
.
For the other it's pretty much the same:
console.log(String(console.log('Not undefined')) !== 'Not undefined');
here console.log('Not undefined')
just logs the string to the console but gives undefined
to String() which converts it to "undefined"
. Then compared to "Not undefined"
, both are strings but they are different. It returns true
.
Upvotes: 0
Reputation: 143
As a matter of fact, it does. If you run the code in developer tools, you'll notice that it returns three outputs: undefined, "undefined", and "Not undefined." The actual undefined result (not a string, it's really undefined) is from the console.log command itself - while console.log is able to print output to the console separately, it itself returns as undefined. The "undefined" string comes from the String function, which appears to have an output of its own (not sure why). Then, you get the desired result - "Not undefined". So really, it does print the desired string to the console, but when you try to assign the code to a variable, like so:
var myVar = console.log(String(console.log('Not undefined')));
myVar returns undefined. But, it does still print the output to the console.
Upvotes: 0