Sunday, July 24, 2022

[FIXED] Why can't you stringify a function expression?

Issue

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


Answered By - Bergi
Answer Checked By - Clifford M. (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.