JavaScript variables

Variables plays a key role in mastering javascript and other languages. They form the basics in how we store data and retrieve same data with accuracy.

See variables as containers or a box, holding an information (data) inside it.

In javascript, variables can be declared using let, var and const as you will see in a second.

Variable declaration with let

let keyword is one way to declare a variable in javascript. 

let greetings; 

Here a variable is declared by name ‘greetings’

A value can then be assign to the variable ‘greetings’ by using the assignment operator =

let greetings = 'Good day'; 

The value ‘Good day’ is term as a string in javascript and all strings must be enclosed with single or double quotes.

In order to access the string ‘Good day’ associated with the variable name ‘greetings’, the variable name need to be called:

let greetings = 'Good day';

alert(greetings) // output Good day in an alert or dialogue box 

Alternatively, above statement could be split into two and still produce same results:

let greetings = 'Good day'; // greetings is declared and assign directly

let greetings;
    greetings = 'Good day'; // greetings is declared and later assigned to the string value 'Good day'
    
alert(greetings); // output same results 

The format you choose to work with is entirely optional or based on team best pratices.

Variable declaration with const

In addition to let keyword, variables can also be declared using the keyword ‘const’ which stands for constant.

Const is used when a value is known and isn’t going to changed over time. Example: mathematical formulars, hard coded values or birth day date are values that can not be changed and can be declared with const keyword.

const BIRTHDAY = 05.11.1975; 

Note that reassigning a constant value will throw an error. Once declared it can not be reassigned to a different value.

Variable declaration with Var

Var keyword is another way to declare a variable but that’s no longer in use and regareded as old school. 

The difference between var and let is pretty negligible. The scope of var declaration is same as let.