Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why console.log doesn't work as an argument?

Tags:

javascript

In javascript there is a callback, and functions are first-class objects right? so i can pass a function as an argument however if i pass console.log() it doesn't work why is that isn't it a function as well?

setTimeout(function(){console.log("hello")},5000);

this code is valid however

setTimeout(console.log("hello"),5000);

produces an error, why is that?

like image 413
Ilyes Hamrouni Avatar asked Jun 05 '18 21:06

Ilyes Hamrouni


2 Answers

When you call console.log with some argument, the argument is printed to console and the function returns undefined.

So when you do:

setTimeout(console.log("hello"),5000);

"hello" will be printed, but what you're essentially doing is:

setTimeout(undefined, 5000);

In the other example (that works) you create a new function, but you do not call it. So you pass this new function to setTimeout, and that is why it works.

like image 169
Phillip Avatar answered Oct 15 '22 12:10

Phillip


The reason that the following code

setTimeout(console.log("hello"),5000); 

fails is because console.log() is invoked directly inside the setTimeout parameter and it always returns undefined (more info: MDN Documentation on Console.log). This means you are essentially running setTimeout(undefined,5000);

You need to provide a function declaration that is not invoked. If you wrap the code inside of a function declaration and do not invoke it, setTimeout will invoke it for you after the specified time lapses. This is why your first statement works, you provide a function declaration:

setTimeout(function(){console.log("hello")},5000);

If you had invoked the function you provided in the first parameter it would also return undefined and "hello" would be output immediately.

So if you provide a function declaration it will work:

setTimeout(()=>{console.log("hello")},5000);

Another way to use console.log directly without a function declaration is to bind it to a variable (more info: MDN Documentation on Function.prototype.bind). An example using .bind prototype:

setTimeout(console.log.bind(null,"hello"),5000);

The code above binds "hello" to invocation of console.log. The first parameter is null in this example but it is the this context.

setTimeout also allows you to pass variables that you want the function to be invoked with. See MDN Documentation on setTimeout

For example to pass a variable:

setTimeout(console.log,5000,'hello');

In the above example you are telling setTimeout to invoke console.log in 5 seconds with the variable (in this case a sting) of 'hello'.

like image 22
Evans Avatar answered Oct 15 '22 11:10

Evans