After some advice from well-meaning peers, I'll try to study 10 items a day as part of efforts to improve my basic skills. In the past I have studied some topics, and it did somewhat help me solve problems quicker at work. For an initial target, I'll try to study for 20 days, and save 10 days for recap.
Note: I still have great faith in ChatGPT to perform the fundamental work for me though. So there's that.
1. What is the difference between null, undefined, and undeclared? How would you go about checking these states?
Undeclared means it's not even initialised with a let
, const
or var
. undefined means it's declared but no values were initialised. null means it is declared and specifically set to null.
I think you can't tell between undeclared and undefined, unless there was some way of checking all memory locations to see whether a certain variable name has been defined? But between null
and undefined
, we can first check if var === null
. If that check fails, we check if !var
to find if it's undefined. The order matters. If these two checks fail, then it's probably defined and non-null.
Model Answer
Interesting things from the answer to explore:
- equality operators (== / ===) - this is something that seems fundamental but possibly confusing.
- As a good habit, never leave your variables undeclared or unassigned. Explicitly assign
null
to them after declaring if you don't intend to use them yet. - I think undeclared variables can cause problems, yes, that's why we always have fallback values, such as-
for display string, or0
for numbers. Actually linting rules (?) help avoid this as well. Feels like leaving itundefined
is still acceptable though.
2. Practice implementing type utilities that check for null and undefined on GreatFrontEnd.
3. Practice implementing type utilities (II): Non-primitives π¨.
4. How to write unit tests for JS
5. How do you reliably determine whether an object is empty?
6. What is the difference between ==
and ===
in JavaScript?
Thoughts: is this not something related to pass-by-value vs pass-by-reference? Note: comparing non-primitives like arrays seem to be comparing by reference. Primitives don't have this complexity.
Top comments (0)