Lesson Introduction and Overview

Welcome to today’s session on TypeScript programming, where we will take a closer look at TypeScript variables. Just as a container might hold various items, variables in TypeScript be used to store data of different types. In this lesson, our main focus will be on understanding what variables are, defining them, assigning values, grasping proper naming conventions, and finally displaying the values stored within these variables. Isn’t it exciting? Let's embark on this illuminating journey!

Understanding TypeScript Variables

Imagine a box. This box can contain items like books, snacks, or even small gadgets. Variables in TypeScript are akin to such boxes—they store different types of values. The exciting part is that, similar to changing the contents of the box, the values variables hold can also be changed. Now let's see this in action with some code:

TypeScript
let myVariable: string = "Hello, TypeScript!";
console.log(myVariable);  // This will print "Hello, TypeScript!"

myVariable = "123";
console.log(myVariable);  // This will print "123"

In this example, myVariable initially holds a greeting message and then gets re-assigned to a string containing a numerical value.

Defining and Naming Variables in TypeScript

In TypeScript, defining a variable and assigning it a value can be done using the let, const, or var keywords, followed by the variable name and an optional type annotation. The let and const keywords are part of TypeScript's newer syntax and offer block-scoped binding, contrasting with var, which is function-scoped. A crucial difference to note is that variables declared with const are meant to be constants, meaning once assigned a value, it cannot change throughout the code.

Here are properly formed variable names and assignments:

let x: number = 7; // valid: starts with a letter
let myVariable: number = 7; // valid: starts with a letter
let _myVariable: number = 7; // valid: starts with an underscore
// let 7x = 7; // invalid - starts with a digit
// let x!y = 7; // invalid - contains the prohibited character '!'

And here is how you would define a constant variable:

const PI: number = 3.14; // Once set, the value of PI cannot change
Value vs. Reference Behavior
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal