TypeScript variable types and basic operations
TypeScript Basic: Exercise-3 with Solution
Write a TypeScript program that declares variables of the following data types: number, string, boolean, and undefined. Assign values to them and perform basic operations.
Sample Solution:
TypeScript Code:
// Declare variables
let n1: number = 42;
let strVariable: string = "Hello, TypeScript!";
let boolVariable: boolean = true;
let undefinedVariable: undefined = undefined;
// Perform basic operations
const n2: number = 10;
// Addition
const sum: number = n1 + n2;
console.log("Sum:", sum);
// String concatenation
const concatenatedString: string = strVariable + " How are you?";
console.log("Concatenated String:", concatenatedString);
// Logical operation
const isTrue: boolean = boolVariable && true;
console.log("Logical AND:", isTrue);
// Check if undefined
if (undefinedVariable === undefined) {
console.log("undefinedVariable is undefined.");
} else {
console.log("undefinedVariable is defined.");
}
Explanations:
In the exercise above,
- Declare variables 'n1', 'strVariable', 'boolVariable', and 'undefinedVariable' with their respective data types.
- Assign values to these variables.
- Perform basic operations such as addition, string concatenation, and logical operations.
- Finally, check if the 'undefinedVariable' is 'undefined' and print a corresponding message.
Output:
"Sum:" 52 "Concatenated String:" "Hello, TypeScript! How are you?" "Logical AND:" true "undefinedVariable is undefined."
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: TypeScript variable declaration and scoping: let, const, and var.
Next: TypeScript type checking example.
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