Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't you stringify a function expression?

Tags:

Why doesn't this produce anything?

console.log(JSON.stringify(function(){console.log('foobar');})); 
like image 341
wwaawaw Avatar asked Sep 29 '12 10:09

wwaawaw


People also ask

Does JSON Stringify preserve functions?

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.

Can I Stringify a function?

JSON can't stringify functions at all, it handles them just like undefined or null values.

Is it possible to Stringify JavaScript arrays?

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.

What is Stringify in programming?

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.


2 Answers

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');}) 
like image 75
Bergi Avatar answered Oct 20 '22 07:10

Bergi


yourFunctionName.toString(); will also stringify a function

like image 41
auraz Avatar answered Oct 20 '22 08:10

auraz