JavaScript variables: how to declare a variable.

Vedanth bora
2 min readJan 24, 2021

JavaScript variables.

Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container.

Before you use a variable in a JavaScript program, you must declare it.

There are 3 ways to do this, using var, let or const, and those 3 ways differ in how you can interact with the variable later on. For example:

Once you’ve declared a variable, you can initialize it with a value. You do this by typing the variable name, followed by an equals sign (=), followed by the value you want to give it. For example:

initialise variable with value

Using let to declare a variable.

let is a new feature introduced in ES2015 and it’s essentially a block scoped version of var.

Its scope is limited to the block, statement or expression where it’s defined, and all the contained inner blocks.

Modern JavaScript developers might choose to only use let and completely discard the use of var.

If let seems an obscure term, just read let color = 'red' as let the color be red and it all makes much more sense

Defining let outside of any function - contrary to var - does not create a global variable.

Using const to declare a variable.

Once a const is initialized, its value can never be changed again, and it can’t be reassigned to a different value.

const a = 'test'

We can’t assign a different literal to the a const.

If you want me to elaborate on anything or have any questions, feel free to leave me a note.

--

--