javascriptjsonfunctionstringification

Why can't you stringify a function expression?


Why doesn't this produce anything?

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

Solution

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