I’m still very new to JavaScript and I recently read through the documentation for setTimeout() and saw the following example:
setTimeout("console.log('Hello World!');", 500);
How does this work? Are we not making console.log() a string? I tried to find more information about this but I don’t really know where to look or how to properly ask the question. Does this apply to all functions and methods? And if so, what determines if I need to use quotation marks or not?
I tried the above sample and it works, I just don’t understand why it works since it seems like we make the whole thing into a string.
Chill Spirit is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
According to MDN, one of the ways to use setTimeout
is:
setTimeout(code, delay)
where code
works as part of:
An alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is not recommended for the same reasons that make using eval() a security risk.
Executing a string as code is not recommended; prefer passing an anonymous function instead.
This would be better and achieve the same effect:
setTimeout(() => console.log('Hello World!'), 500);