Start learning free

LESSON 11 OF 675 · VARIABLES

Variable Naming Rules in TypeScript

Lesson

TL ; DR:

  • In TypeScript, we use the camelCase convention to name our variables. It implies separating different words with capital letters, like this:

    let companyName = "Apple";
    
    let foundingYear = 1976;
    
    let isUnicorn = true;
    
    let numberOfEmployees = 137000;
    



Full lesson:

Variable names must consist ONLY of letters, numbers and underscores and they must start with a letter or underscore.

Bad variable names:

let 18spam;
let x.15;

If you try to create a variable with any of these names, the TypeScript compiler will report a syntax error.


Naming conventions: camelCase and snake_case

Sometimes a variable name might consist of multiple words, for example if you want to store the first name of a person. You might be tempted to separate those names by whitespaces, like this:

let first name = "Kate";

The compiler will report a syntax error for this code too.

When you name your variables, you want to use one of these two conventions:

snake_case = separate different words with an underscore (_), like this:

let first_name = "Jane";
let last_name = "Doe";

camelCase = separate different words with capital letters, like this:

let firstName = "Jane";
let lastName = "Doe";

It's important to be consistent with the casing technique you use. Do not combine both of them in the same code, like this:

let first_name = "Jane";
let lastName = "Doe";

Case sensitive:

Variable names are case sensitive:

let name = "Kate";
let Name = "Andy";
let NAME = "George";

console.log(name, Name, NAME); // Output: Kate Andy George

Although TypeScript allows us to do this, it's always confusing and a bad coding practice to differentiate variable names just by case!


Mnemonic Variable Names:

Since we programmers are given a choice in how we choose our variable names, there is a bit of "best practice".

Sometimes we want them short like x and y, but sometimes we want them descriptive, especially if they are important.

Here is a great example:

let a = 25;
let b = 13;
let c = a * b;
console.log(c);

compared to:

let hours = 25;
let rate = 13;
let pay = hours * rate;
console.log(pay);

TypeScript understands and is happy with both of these pieces of code. But it's clearly which version makes your reader happier.


Assignment
Follow the Coding Tutorial and let's name some variables well!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check