Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
TypeScript null and undefined Type
Next article icon

How to check null and undefined in TypeScript ?

Last Updated : 01 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article let's learn how to check if a variable is null or undefined in TypeScript. A variable is undefined when it's not assigned any value after being declared. Null refers to a value that is either empty or doesn't exist. null means no value. To make a variable null we must assign null value to it as by default in typescript unassigned values are termed undefined. We can use typeof or '==' or '===' to check if a variable is null or undefined in typescript.

By using typescript compiler tcs we transpile typescript code to javascript and then run the javascript file.

tcs name_of_the_typescript_file

run the javascript file in the terminal by using:

node name_of_the_js_file

Example 1: In this example, we demonstrate when variables are null and when they are null. 

JavaScript
let s: string;  // Returns undefined console.log(s); let n: number;  // Assigned null value n = null; console.log(n); 

Output:

undefined
null

Example 2: In this example, typeof operator returns the type of the variable we want to check. In the below example we check the variable. unassigned variable returns undefined and the value which is assigned null returns object as 'null' is also taken as a null object in javascript.

JavaScript
let s: string;  // Returns undefined console.log(typeof s); let n: number;  // Assigned null value n = null; console.log(typeof n); 

Output:

undefined
object

Example 3: In this example, '==' the equals operator helps us check whether the variable is null or undefined but when we check if null == undefined it results 'true'. it's also known as equality check.

JavaScript
let s: string; let n: number;  // Assigned null value n = null; console.log(n == null); // Returns true console.log(s == undefined); // Returns true console.log(null == undefined); // Returns true 

Output:

true
true
true

Example 4: In this example, just as in the previous example instead of '==' , we use '===' to check. this method is called strict equality check. when checked if null=== undefined, it returns false unlike the previous method.

JavaScript
let s: string; let n: number;  // Assigned null value n = null; console.log(n === null); // Returns true console.log(s === undefined); // Returns true console.log(null === undefined); // Returns false 

Output:

true
true
false

Method 5: Using Optional Chaining and Nullish Coalescing Operator

In this approach, we utilize the optional chaining (?.) and nullish coalescing (??) operators to check if a variable is null or undefined. These operators provide a concise and readable way to handle null and undefined values in TypeScript.

Example: Below is an example demonstrating the use of optional chaining and nullish coalescing operators to check for null or undefined values.

Data: Variable Declaration

We declare variables that can be either undefined, null, or assigned a value.

let undefinedVar: string | undefined;
let nullVar: string | null = null;
let assignedVar: string | null | undefined = "Hello, World!";
JavaScript
let undefinedVar: string | undefined; let nullVar: string | null = null; let assignedVar: string | null | undefined = "Hello, World!";  const checkUndefinedVar = undefinedVar ?? "Variable is undefined"; const checkNullVar = nullVar ?? "Variable is null"; const checkAssignedVar = assignedVar ?? "Variable is either null or undefined";  console.log(checkUndefinedVar); console.log(checkNullVar); console.log(checkAssignedVar); 

Output:

Variable is undefined
Variable is null
Hello, World!

Next Article
TypeScript null and undefined Type
author
isitapol2002
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • TypeScript

Similar Reads

  • TypeScript null and undefined Type
    TypeScript, a popular programming language, is widely used for building scalable and robust applications. In this article, we’ll explore the null and undefined types, which represent the absence of a value or uninitialized variables. Null TypeWhat is Null?null represents the intentional absence of a
    2 min read
  • How to Check Types in Typescript?
    Checking types in TypeScript involves methods like typeof for primitive types, instanceof for class instances, and custom type guards for complex type validation. These techniques help ensure variables are correctly typed, improving code safety, and readability, and preventing runtime errors.Here ar
    3 min read
  • How to use Hashmap in TypeScript ?
    In TypeScript, One can use the built-in Map data structure to implement a hashmap. A Map can be used to store key-value pairs where keys can be of any type. Syntax:// Create a new empty hashmaplet hashmap: Map<KeyType, ValueType> = new Map();// Add key-value pairs to the hashmaphashmap.set(key
    2 min read
  • How to Return a Union Type in TypeScript ?
    In TypeScript, a union type is a powerful way to express a variable that can be one of several types. Union types are used when a function or variable is expected to support multiple types of input. Union types are defined using the pipe (|) symbol between two or more types. This indicates that a va
    4 min read
  • How to enforce strict null checks in TypeScript ?
    In Typescript to enforce strict null checks in tsconfig.json file, we need to enable "strictNullChecks" to true. When "strictNullChecks" is false, the language generally ignores variables of type null and undefined. If null and undefined is used in places where a definite value is expected, it raise
    2 min read
  • How to declare nullable type in TypeScript ?
    In vanilla JavaScript, there are two primary data types: null and undefined. While TypeScript previously did not allow explicit naming of these types, you can now use them regardless of the type-checking mode. To assign undefined to any property, you need to turn off the --strictNullChecks flag. How
    2 min read
  • How to Create an Object in TypeScript?
    TypeScript object is a collection of key-value pairs, where keys are strings and values can be any data type. Objects in TypeScript can store various types, including primitives, arrays, and functions, providing a structured way to organize and manipulate data. Creating Objects in TypescriptNow, let
    4 min read
  • How to write a function in Typescript ?
    Writing a function in TypeScript is similar to writing it in JavaScript but with added parameters and return type. Note that any JavaScript function is a perfectly valid TypeScript function. However, we can do better by adding type. Syntax: Let's see a basic TypeScript function syntax (with two argu
    4 min read
  • How to Check if an Object is Empty in TypeScript ?
    In TypeScript, it's common to encounter scenarios where you need to determine if an object is empty or not. An empty object typically means it contains no properties or all its properties are either undefined or null. Below are the methods to check if an object is empty or not in TypeScript: Table o
    3 min read
  • How to check interface type in TypeScript ?
    Typescript is a pure object-oriented programming language that consists of classes, interfaces, inheritance, etc. It is strict and it statically typed like Java. Interfaces are used to define contacts in typescript. In general, it defines the specifications of an entity. Below is an example of an in
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences