DEV Community

Cover image for What is the difference between null and undefined?
Benny Code for TypeScript TV

Posted on


What is the difference between null and undefined?

The convention in TypeScript is that undefined values have not been defined yet, whereas null values indicate intentional absence of a value.

Example with null

The below function shows how null can be used by returning an object that always has the same structure, but with intentionally assigned null values when the function does not return an error or result:

function divide(a: number, b: number) {  
  if (b === 0) {  
    return {  
      error: 'Division by zero',  
      result: null  
  } else {  
    return {  
      error: null,  
      result: a / b  
Enter fullscreen mode Exit fullscreen mode

Example with undefined

On the other hand, undefined represents the absence of any value. It is a value that is automatically assigned to a variable when no other value is assigned. It often indicates that a variable has been declared but not initialized. It can also signify a programming mistake, such as when a property or function parameter was not provided:

let ratio: number | undefined;  

if (ratio === undefined) {  
  console.log('Someone forgot to assign a value.');  
} else if (ratio === null) {  
  console.log('Someone chose not to assign a value.');  
Enter fullscreen mode Exit fullscreen mode

Best Practice

The TypeScript Coding guidelines recommend using only undefined and discouraging the use of null values (see here). It is important to note, however, that these guidelines are tailored towards the TypeScript project's codebase and may not necessarily be applicable to your own projects.

Want more?

If you found this short explainer helpful, hit that subscribe button on my YouTube channel or give me a follow on Twitter to level up your TypeScript game.

Top comments (0)