Variables and Types
Variables are used to store data and consist of an identifier (name) and a memory space for storing their values. A variable can be thought of as a box with a name and contents (value).
<key_word> <variable_name> = <value>
Variable names
Identifier is the name of a variable, function or class. It consists of one or more characters in the following format:
- The first character must be the letter
a-z
orA-Z
, the underscore_
or the dollar sign$
. - Other characters can be letters
a-z
,A-Z
, numbers0-9
, underscores_
and dollar signs$
. - Identifiers are case sensitive. This means that the variables
user
,usEr
andUser
are different.
The variable name should be self-explanatory.
# ❌ Bad
chislo
korzina_tovarov
profil_polzovatelya
tekushiy_mesyaz
# ✅ Good
number
cart
userProfile
currentMonth
CamelCase notation for identifiers is standard. The first word should be written in lowercase letters, and each subsequent word begins with an uppercase one. For example, user
, greetUser
, getUserData
, isActive
, activeGuestCount
, totalWorkerSalary
.
- How to name variables - [Variable naming conventions](https://medium.freecodecamp.org/javascript-naming-conventions-dos-and- don-ts-99c0e2fdd78a)
Keywords
There is a list of reserved keywords that have specific meanings and are used for certain constructs. You cannot use keywords as identifiers.
abstract | arguments | await | boolean |
break | byte | case | catch |
char | class | const | continue |
debugger | default | delete | do |
double | else | enum | eval |
export | extends | false | final |
finally | float | for | function |
goto | if | implements | import |
in | instanceof | int | interface |
let | long | native | new |
null | package | private | protected |
public | return | short | static |
super | switch | synchronized | this |
throw | throws | transient | true |
try | typeof | var | void |
volatile | while | with | yield |
Variable declaration
A variable declaration begins with the keyword const
. Such a variable must be immediately initialized with a value, after which it cannot be overridden.
// Variables declared as const must be initialized
// with a value during declaration, otherwise there will be an error.
const yearOfBirth = 2006;
console.log(yearOfBirth); // 2006
// When a variable is declared as const, you cannot overwrite its value.
// If you try to assign a new value, you will get a script execution error.
yearOfBirth = 2020; // ❌ Wrong, error message
In order to declare a variable which can be later assigned a new value, use the keyword let
.
// Variables declared through let do not need to be assigned a value straight away.
let age;
// When a variable declared as let is not assigned a value from the start,
// it is initialized with the undefined value.
console.log(age); // undefined
// console.log() is a method for logging data in the browser console,
// you will know more about it later.
// When a variable is declared as let, you can overwrite its value.
age = 14;
console.log(age); // 14
Declaring a variable without the keyword let
or const
will result in an error if the script is run in strict mode.
When to use const
and let
The only difference between const
and let
is that const
forbids to re-assign another value to the variable. By declaring const
, you make the code more readable, since the variable always refers to the same value. In the case of let
, this is not always the case.
It makes sense to use let
and const
like this:
- Use
const
by default, as most variables should be declared this way. - Use
let
if you need to assign a different value to your variable during script execution.
constants and CONSTANTS
The names of CONSTANTS, i.e. variables with unchanged values throughout the entire script, are usually written in the UPPER_SNAKE_CASE
format.
// Constant storing the color value
const COLOR_TEAL = "#009688";
// Constant storing a log in message
const LOGIN_SUCCESS_MESSAGE = "Welcome!";
The vast majority of variables are constants in a different sense, as they simply do not change their values after assignment. However, with different runs of the script, these values may be different. The names of such variables are written using the camelCase
format.
Accessing a variable
It is important to distinguish between undefined and undeclared variables.
Undefined is a variable that has been declared with the keyword let
, but has not been initialized with a value. By default, it is assigned an initial value of undefined
.
let username;
console.log(username); // undefined
Undeclared or not defined is a variable that has not been declared in the available scope. Attempting to access a variable before it is declared will result in an error. For example, to read or change its value.
// ❌ Wrong, error message
age = 15; // ReferenceError: Cannot access 'age' before initialization
console.log(age); // ReferenceError: age is not defined
// Declaring the variable age
let age = 20;
// ✅ Correct, accessing after declaration
age = 25;
console.log(age); // 25
Primitive types
In JavaScript, a variable is not associated with any data type; its value has a type. That is, a variable can store values of various types.
Number, integers and floating-point numbers.
const age = 20;
const points = 15.8;
String, strings, a sequence of zero or more characters. Every string begins and ends with single '
or double quotes "
.
const username = "Mango";
const description = "JavaSript for beginners";
Boolean is a logical data type, true/false flags. Only two values are used, true
and false
. For example, when asked whether the light in the room is on, you can answer yes (true) or no (false).
true
- yes, right, true, 1false
- no, wrong, false, 0
Pay attention to the names of variables containing booleans. They ask a question and the answer is yes or no.
const isLoggedIn = true;
const canMerge = false;
const hasChildren = true;
const isModalOpen = false;
null is a special value that essentially means nothing
. It is used in situations where emptiness must be explicitly indicated. For example, if the user has not selected anything yet, you can say that the value is null
.
let selectedProduct = null;
undefined is another special value. By default, when a variable is declared but not initialized, its value is undefined, it is assigned undefined
.
let username;
console.log(username); // undefined
typeof
operator
It is used to get the variable's value type. It returns in place of its call the value type of the variable specified after it, so you will see a string with type name.
let username;
console.log(typeof username); // "undefined"
let inputValue = null;
console.log(typeof inputValue); // "object"
const quantity = 17;
console.log(typeof quantity); // "number"
const message = "JavaScript is awesome!";
console.log(typeof message); // "string"
const isSidebarOpen = false;
console.log(typeof isSidebarOpen); // "boolean"