Working with null and undefined in TypeScript
TypeScript Basic: Exercise-10 with Solution
Write a TypeScript program that declares a variable 'isNull' and assigns it null. You should also declare a variable called 'isUndefined' and assign it an undefined value.
Sample Solution:
TypeScript Code:
// Declare a variable 'isNull' and assign it null
let isNull: null = null;
// Declare a variable 'isUndefined' and assign it undefined
let isUndefined: undefined = undefined;
// Print the values of the variables
console.log("isNull:", isNull);
console.log("isUndefined:", isUndefined);
Explanations:
In the exercise above -
- First we declare a variable 'isNull' and explicitly specify its type as 'null' by using the type annotation: null. This means that 'isNull' can only hold the value 'null'.
- Next we declare a variable 'isUndefined' and explicitly specify its type as 'undefined' using the type annotation : undefined. This means that 'isUndefined' can only hold the value 'undefined'.
- Finally we use console.log to print the values of 'isNull' and 'isUndefined' to the console.
Output:
"isNull:" null "isUndefined:" undefined
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics