DEV Community

loading...

JavaScript: Variables (Beginners)

banesag profile image Banesa Guaderrama ・2 min read

As in math variables in programming languages are used to refer to values stored to be used later, in this case it is stored in the memory of the program.

Declaring and Assigning Variables

Variables must be declared before they can be used. In JavaScript the keywords ‘const’ and ‘let’ are used to declare variables. The mean to assign a value to our keywords is by follow the keyword by the ‘=’ (equal sign) operator.

Keyword const and let

Is important to note that the keyword ‘const’ is used when the variable will not be reassigned to another value, and the keyword ‘let’ can be reassigned later inside your program.

For example:

This example shows how we declare the variable name and assign a string ‘banesa’ to it.

const name = 'banesa'; // In this case the value ('banesa') will not be assigned to another string

Another example using the keyword ‘let’:

This example shows how we declare the variable score and assign a value of ‘0’ (number).

let score = 0; // The assigned value can change during the program

This was made by using primitive data, but if the variable references a non-primitive data type, such an array, function, or object, then the keyword const will be mutable. Which it means, is that the data inside an object can change.

Example:

const name = { value: ‘Banesa’}; // the object is indicated by using curly brackets
name.value = 'Barbara'; //change the value through the use of object notation (.)
<< 'Barbara' // the output will be 'Barbara' since we allowed to change the variable by been inside an object

Because the variable is using the curly brackets, it allows to convert the variable value into an object, it will require an additional step, it is to call for the new variable that will be reassign later in the program by using the object notation (name.value), the combination of these two rules/methods will allow you to reassign the non-primitive data still using const.

Even when the use of const seems to be a restriction, it helps you to prevent bugs in your program by not assigning twice the same variable.

Discussion (0)

pic
Editor guide