Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you don't provide an explicit <code>return</code>, the return value is <code>undefined</code>. Your second function <em>always</em> returns <code>undefined</code>, in other words. Because the function always returns <code>undefined</code>, there'll never be anything included in the JSON stringified result, so the overall effect is that you get <code>undefined</code>.</p> <p>It's sort-of an anti-pattern to do this:</p> <pre><code>if (something) { return whatever; } else { return somethingElse; } </code></pre> <p>Your first function would be more idiomatic as:</p> <pre><code>str = JSON.stringify(o,function(k,v) { return Object.isSealed(this) ? undefined : v; }); </code></pre> <p><em>edit</em> &mdash; note that <code>JSON.stringify()</code> calls your replacer function <em>first</em> with an empty key, and "v" equal to <strike><code>this</code></strike> a new <em>wrapper</em> object containing the object to be stringified (and note that <em>that</em> object is <em>not</em> sealed). That is, before checking each property of an object to be stringified, it asks the replacer function whether it should work on the object as a whole. Because your function always returns <code>undefined</code>, the stringify function thinks that there's absolutely nothing to be done. It can't return an empty object because your replacer function immediately told it "don't include this in the result".</p> <p>Also note that the caller of your function cannot determine whether your function explicitly returned <code>undefined</code> or if it returned <code>undefined</code> because it didn't return anything, in case that's not clear. Those two cases look exactly the same to the caller.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload