Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embed an ES6 Arrow Function in JSON Object

Is it possible to embed an ES6 Arrow Function within a JSON object?

Example, would the following data format be considered "valid"?

{
     function:{() => {console.log("executed")}}
}
like image 908
Jake Chasan Avatar asked Oct 25 '25 05:10

Jake Chasan


1 Answers

First off, there is no such thing as a JSON object. JSON is a text format, not an object format. There is JSON text and Javascript objects. The two are completely different things.

Per the JSON specification, the JSON text format does not accept functions. Values in a JSON formatted string are described in this spec in shorthand like this:

value = false / null / true / object / array / number / string

Those are the types that are allowed in JSON.


On the other hand, a Javascript object can indeed have a property that is a function. Since people regularly mix up those two separate things, I'm not sure what you meant, though you refer to JSON which is a text format and does not accept functions.

A Javascript object could have a function like this:

let obj = {
    somePropertyName: function() { console.log("hi")}
};

that could then be called as:

 obj.somePropertyName();

ES6 syntax also allows a few other ways to declare the function, but the idea is the same. You end up with a named property on the object that points to a function. Using an arrow function with ES6 syntax:

let obj = {
    somePropertyName: () => { console.log("hi")}
};

It is important to realize that when using an arrow function, the value of this when that function is called will NOT be set to the object itself since by definition, an arrow function uses the lexical form of this, and this is not set by how the method is called as it is with a normal function definition.

like image 198
jfriend00 Avatar answered Oct 26 '25 19:10

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!