Why can't you stringify a function expression?

wwaawaw picture wwaawaw · Sep 29, 2012 · Viewed 15.4k times · Source

Why doesn't this produce anything?

console.log(JSON.stringify(function(){console.log('foobar');}));

Answer

Bergi picture Bergi · Sep 29, 2012

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');})