r/javascript • • May 28 '19

What are some JavaScript things beginners don't know?

333 Upvotes

383 comments sorted by

View all comments

Show parent comments

16

u/[deleted] May 28 '19

let me end all your struggles:

the only time you use == instead of === in JS is when you do yourVar == null because this checks for null and undefined.

2

u/[deleted] May 28 '19

Your data structures shouldn't usually be capable of being T | null | undefined, so I'd argue there's really no place for double equals in a modern codebase.

3

u/[deleted] May 28 '19

It absolutely should. Undefined before getting any data, null when no data or when explicitly set to empty.

2

u/[deleted] May 28 '19

undefined representing not having attempted to retrieve data yet and null representing no data is a bit vague and implicit; unless there was a comment outlining this, do you think it would be obvious when reading the code that this was your intent?

Personally I'd opt for null to represent no or empty data and a second variable or property to represent how you have or have not attempted to retrieve said data, probably written as an enum for maximum clarity.

// This really needs commenting to make clear what each falsy value represents
let data: Data | null | undefined = undefined;

// This is much clearer IMO
enum DataFetchState {
    Success,
    Failure,
    InProgress,
    None,
}

let state: DataFetchState = DataFetchState.None;
let data: Data | null = null;

4

u/[deleted] May 28 '19

I didn't mean "no data yet" as in "no data from database". I meant not initialized variable/property. It should be undefined since it's not yet, well, defined.

The other cases should be null.

That's what I use, my company uses and I've seen it used often.