Hacker News new | ask | show | jobs
by Jasper_ 1962 days ago
> JSON.stringify on an undefined property removes that property.

Except, you can still differentiate between them:

    > ({ foo: undefined }).hasOwnProperty('foo')
    true
    > ({ }).hasOwnProperty('foo')
    false
So now you have two ways of specifying a missing property, instead of one. null vs. undefined is a really annoying language misfeature to me, especially with some of the other weird behaviors that it has:

    > [].length
    0
    > [].map(v => 123)
    []
    > [].map(v => 123).length
    []
    > [undefined].length
    1
    > [undefined].map(v => 123)
    [123]
    > Array(1).length
    1
    > Array(1).map(v => 123)
    []
    > Array(1).map(v => 123).length
    1
If you need to remove a property from an object, just use delete obj.foo; instead of setting it to undefined.
1 comments

    JSON.parse(JSON.stringify(obj)).hasOwnProperty('foo')
    false
Thing is, other parts of the code might actually serialize and unserialize objects. If you rely on a prop being 'undefined' meaning "prop is unknown like the firstName", as OP suggested, you might be in for a surprise.