Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does console.log treat 'this' differently?

Why does the following statement:

(function(){ console.log(this); }).apply(String("hello"));

display the following output

String {0: "h", 1: "e", 2: "l", 3: "l", 4: "o", length: 5} 

and not a simple:

hello

Is this behavior built-in to the interpreter or is there a way to detect the type of reference passed?

like image 935
hondaman Avatar asked Jan 30 '14 07:01

hondaman


People also ask

Which is the better to do console log in?

I've always been told that when debugging an application, JavaScript's console. log() method is preferred over simply using an alert() method.

What does console log () do?

The console. log() method outputs a message to the web console. The message may be a single string (with optional substitution values), or it may be any one or more JavaScript objects.

Is console log same as print?

Here's a quick lesson for you: In your web browser's devtools, your console. log() does not capture the objects you print when you print them. It captures it when you look at the printout.

Does console log return anything?

console. log() is a function used to print information to the console. return on the other hand is a call to pass some value back up to where the call was made. For instance, let's say you create a function called square() that takes in a single numeric parameter and returns that value squared.


2 Answers

The reason that you get an object and not a string as the output of your function is that by default javascript 'this' object is always forced to be an object.

If you however use javascript in a strict format with 'use strict' then this is disabled and you can get the result that you would expect.

// wrapped in a function to allow copy paste into console
(function() {
   'use strict';

   (function(){ console.log(this); }).apply(String("hello")); 
})();

A more thorough explanation about 'strict mode' and why it removes the boxing of this into an object can be found on the mozilla site here

like image 177
DeadAlready Avatar answered Oct 16 '22 00:10

DeadAlready


In JavaScript, this can't be a primitive type; you would need to use .valueOf() to fetch the primitive value, i.e.:

(function(){ console.log(this.valueOf()); }).apply(String("hello"));

Or use 'use strict'; like DeadAlready mentioned in his answer.

like image 33
Ja͢ck Avatar answered Oct 16 '22 02:10

Ja͢ck