null vs undefined in JavaScript

Two distinct primitive types that both represent absence of value, but with different semantics and use cases.

Featurenullundefined
Typeobject (historical bug in JS)undefined
Set byDeveloper explicitlyJavaScript engine (usually)
MeaningIntentional absence of valueVariable declared but not assigned
typeof null"object"
JSON supportJSON.stringify(null) = "null"Omitted from JSON.stringify
Default valueNot a default for anythingDefault for unset variables, missing params, missing properties

Verdict

Use null when you want to explicitly indicate no value. Let undefined be JavaScript's default for uninitialized values. Check both with == null or the ?? operator.

Code Example

Javascript
Tip: Modify the code above and click “Run” to see the results

Related Tutorials

Related Glossary Terms