This first chapter is all about variables, the way to declare and change them as well as some of the naming rules and different types of variables.
A variable is named storage for data. Each variable must have a unique name which is called an identifier. Variables can be hard-coded to hold predefined values of dynamically generated.
You can easily declare a variable using the
let keyword followed by the name of the variable.
let userName; userName = "Dev";
You have the option to declare a variable and assign a value later or do both at once.
let userName = "Dev"; let loggedIn = true;
You can easily change the value of a variable by easily assigning a new one.
let testVariable = "Hello"; testVariable = "World";
let testVariable = "Hello"; testVariable = 10; testVariable = false;
numbers or the
symbols $ and
However, the first character can't be a number and you can't use reserved keywords (such as
return) for variable names.
// Valid variable names let test; let test1; let variable_name; let user_1; let userName; // Invalid variable names let 1test; let variable-test; let return;
If the value of your variable is constant and won't be re-assigned you can use the
const keyword instead of
const welcomeMessage = "Hello World!";
These are useful to create a distinction between constant and changeable variables.
const userName = "Dev"; let isLoggedIn = true;
It has also become common practice to use constant aliases for known values that are used throughout a site or application. These are written with uppercase letters and underscores.
const PRIMARY_BRAND_COLOUR = "#1c3aa4"; const CONTACT_EMAIL = "email@example.com"; const COMPANY_REG_NUMBER = "9876543210";
You can still declare variables using
var, however, the practice is now considered outdated.
// Old standard var message = "Hello World!"; // New standard let message = "Hello World!";
Variable declared with
var aren't scoped and have various other flaws, so unless you need to support a really old browser it's best to use
letto declare variables with changeable values.
constto declare constant, non-changeable values.
- Follow the naming rules and name your variables well.
- User uppercase constants for hard-coded global constant values.
- Don't use
varto declare variables unless you require legacy browser support.
If you like this post. Kindly support me by Buying Me a Coffee