Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Variables

A variable is a name under which a value is stored. You can read the value, change it and use it anywhere in the program. Without variables you would have to repeat the same numbers and strings again and again.

Declaring with let

A variable is created with the word let followed by a name. The = sign means "put the value into the variable" — this is assignment, not equality as in maths:

let name = 'Anna';
 
console.log(name); // Anna

You do not need to state the type of the value — JavaScript works it out itself. Creating a variable is called declaring it.

Changing the value

A variable declared with let can be given a new value. You do not repeat let — the variable already exists:

let count = 1;
count = count + 1;
 
console.log(count); // 2

The expression on the right (1 + 1) is evaluated first, then the result is written into the variable and the old value is lost.

const

The word const (short for constant) declares a variable that cannot be reassigned:

const price = 100;
 
console.log(price * 2); // 200

Use const by default and let only when the value really will change. That way the code shows at a glance what can change and what cannot.

Naming rules

  • a name consists of letters, digits, _ and $ and cannot start with a digit;
  • case matters: age and Age are different variables;
  • reserved words of the language such as let, const or if are not allowed.

Name variables so it is clear what they hold: userName is better than x. If a name has several words, each following word starts with a capital letter — this style is called camelCase.

Inserting into a string

In a string written in backticks (`) a variable's value is inserted with ${...}. Such strings are called template literals:

const name = 'Anna';
const age = 25;
 
console.log(`My name is ${name}, I am ${age}`); // My name is Anna, I am 25

Ordinary quotes do not do this — the text ${name} is printed as is.

The old word var

Older code declares variables with var. Its scoping rules are confusing and lead to subtle bugs. When you see var, read it as let, but in your own code use only let and const.

Common mistake

Assigning a new value to a variable declared with const stops the program with an error:

const total = 10;
total = 20; // TypeError: Assignment to constant variable.

If the value has to change — a counter or a running sum, for example — declare the variable with let.

Thanks for reading!

Donate to the site — we work hard for you.