Why does "let txt = console.log('testString')" work?

I’m a beginner at codecademy and im just playing around the console while I go through my courses. Out of curiosity, I tried playing with methods declaring a method as a string. I know this is not how its supposed to be done but I’m curious on why the console still printed my trimmed string in the second line but is as an undefined data type if I print it again in the third line.

console.log('Codecademy'.toUpperCase()); let txt = console.log(' Remove whitespace '.trim()); console.log(txt);
1 Like

The third line is trying to print everything that txt equals. This includes another console.log().

Console.log can’t resolve that to a string, so it gives ‘undefined’.

Console.log() has some interesting behaviours from time to time. The MDN has more on the subject. console.log

1 Like

i was bout to type that but u did it for me

Your syntax is not assigning a method to the variable txt, it is assigning the value returned from the console.log function, which is undefined, not whatever you asked it to display.

I think you may have been trying to do something like this instead.

let txt = (str) => {
return (str.trim());
}

console.log(txt('        Remove whitespace   '));

OR …

let txt = (str) => {
  console.log(str.trim());
}

txt('    Remove whitespace    ');