Why doesn't this produce anything?
console.log(JSON.stringify(function(){console.log('foobar');}));
To be clear, the output looks like JSON but in fact is just javascript. JSON. stringify works well in most cases, but "fails" with functions.
JSON can't stringify functions at all, it handles them just like undefined or null values.
Stringify a JavaScript ArrayIt is also possible to stringify JavaScript arrays: Imagine we have this array in JavaScript: const arr = ["John", "Peter", "Sally", "Jane"]; Use the JavaScript function JSON.
stringify() method in Javascript is used to create a JSON string out of it. While developing an application using JavaScript, many times it is needed to serialize the data to strings for storing the data into a database or for sending the data to an API or web server.
JSON can't stringify functions at all, it handles them just like undefined
or null
values. You can check the exact algorithm at EcmaScript 5.1 §15.12.3, see also the description at MDN.
However you of course can stringify function expression by casting them to a string, try
console.log("" + function(){console.log('foobar');})
yourFunctionName.toString();
will also stringify a function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With