DEV Community

Cover image for Beginners guide to JavaScript Variables
Vivian Ijomah
Vivian Ijomah

Posted on

Beginners guide to JavaScript Variables

Hello World, JavaScript is one of the most popular web technologies that when mastered will open a new door of creativity and power in building web applications.
With the JavaScript language, we deal with a lot of data or information, this data or information needs to be stored somewhere we can quickly have access to.
The box or container for storing data are variables.
In this post, we take a look at variables in JavaScript, we will learn what variables are, how to create variables, how to store values and how to access the stored values.

Let's get started

What are variables?

With most web applications, you may want to work with some information or data. For instance, if you plan to build the next social media application, you may want to keep information like who created an account, who posted, who liked a post etc.
The way to keep track of these informations or data is store them in variables.

Variables are boxes that stores values or information or data.

The value or data stored can then be used during the program execution.
Every variable has three main structures

  • The name : to uniquely identify the variable
  • The value : referring to the data or information stored in the variable
  • The memory address : referring to the location in the computer's memory where the variable is stored.

Let's learn how to create variables.

Declaring a variable
To be able to store data in a variable, you need to declare it.

  • You declare a variable with the var (less recommended) or let or const keywords.
  • Followed by the *name * you want to give to the variable.

For instance

var firstName;
Enter fullscreen mode Exit fullscreen mode

or

let firstName;
Enter fullscreen mode Exit fullscreen mode

From the above, I have created a 'container' or box with a label **firstName.
After declaring the variable, you can now **store the data or value into the variable. The syntax will be
var variableName = value;
Let's now assign the firstName variable a value

let firstName = "Vivian";
Enter fullscreen mode Exit fullscreen mode

We have now stored the data or value "Vivian" in our firstName variable (or container).
You can also declare multiple varialbes and assign values to each of them.

let firstName = "Vivian";
let lastName = "Sylvanus";
let email = "vivaluv98@gmail.com"
Enter fullscreen mode Exit fullscreen mode

The above declare three variables firstName, lastName, and email and store three distinct piece of data or value in them.
We can also declare multiple variables at a go, each variable declaration must be followed by a , (comma).

//declaring 3 variables together
let firstName = "Vivian", lastName ="Sylvanus", email="vivaluv98@gmail.com";
Enter fullscreen mode Exit fullscreen mode

Rules for variable name
The following are some rules to take note of when declaring variables

  • Variable names cannot contain spaces
  • The first letter of the variable can be [a-z, A-z], dollar sign ($), or underscore(_)
  • Any digit can be used after the first letter
  • Variable names are case sensitive. For instance let firstName and let FirstName are not the same

Undefined vrs Undeclared Variables
An undefined variable is a variable that has been declared, but has not been assigned a value. Because it has not been assigned a value, the variable uses undefined as its initial value.
Let's declare a variable not assign it a value and see what the output will be

let firstName;
console.log(firstName)
Enter fullscreen mode Exit fullscreen mode

The output will be undefined
However, an undeclared variable is a variable that has not been declared. Accessing an undeclared variable will produce a ReferenceError.
For instance

console.log(message);
//ReferenceError: message has not been declared. 
Enter fullscreen mode Exit fullscreen mode

Retrieving Values
To easily grasp the concept of variable, you can imagine it as box with a unique name or label on it, used for storing data. We can put any value or data in the box.
To access the data or value in the box, you need to call the variable name (type the unique name you gave to the variable).

let firstName = "Vivian"
//retrieving the value
firstName;
Enter fullscreen mode Exit fullscreen mode

To dispay the output of a variable, you can use the console.log() method and insert the variable name in the () parenthesis.
So, if you want to view what data is stored in the firstName variable , you can write

console.log(firstName);
/*This will output the data stored in firstName in the developer console.*/
Enter fullscreen mode Exit fullscreen mode

You can also change the value or data stored in the variable by assigning the variable a new data.
See the code below:

firstName = "Chiamaka"; //change the value stored in the variable to Chiamaka 
console.log(firstName); //Chiamaka 
Enter fullscreen mode Exit fullscreen mode

Now when you call the firstName variable, it will contain the value Chiamaka instead of Vivian
Declaring a variable twice
A variable should be declared only once, a repeated declaration of the same variable is an error

let firstName = "Vivian";
let firstName = "Chiamaka ";
/*SyntaxError: 'firstName' has already been declared */
Enter fullscreen mode Exit fullscreen mode

Types of variables
All variables exist within a scope, which determines which part of the code can have access to the variables, and the life span of the variables.
There are two types of variables supported in JavaScript

  • Local variables
  • Global variables

Local Variables

A local variable is a variable that is declared inside a code block, a function body or inside a loop body.

  • In other words, if we declare a variable inside a curly braces {} or block scope, it is a local variable. That variable can only be accessed inside that scope or {}
  • Also, if you declare a variable inside a function, JavaScript will add the variable to the function's scope, the variable will only exist inside the function
  • It is recommended to use let keyword when declaring local variables.

Let's examine the code below:

function someFunc(){
    let firstName ="Vivian";
//accessing the local varialbe
    console.log(firstName)
}
someFunc() // output "Vivian"

//accessing the variable outside the scope {}
console.log('access out scope', firstName)
// Uncaught ReferenceError: firstName is not defined
Enter fullscreen mode Exit fullscreen mode
  • Since firstName variable is declared inside the curly braces {} or a function scope, it is a local variable and cannot be accessed outside {}.
  • If you try to access firstName outside of the function, as in the example above, you will get a ReferenceError because the firstName variable was not defined.

Global variable

A variable declared anywhere within the script and not declared inside a block scope or function scope is a global variable

In simple words, if the variable was not declared inside a function's body or in a block of code {}, then it s a global variable. **
Global variables can be accessed **anywhere in your code.
It is recommended to use the var keyword for global variables.
Naming things right
It is recommended that the name you give the variable, should have an obvious meaning, describing the data that it stores.
A quick glance at variable names can reveal if the program was written by a novice or an experienced developer.
Some good to follow rules are

  • Use identifiable and human-readable names like userName , firstName or tasks
  • Avoid using abbreviations or short names like a, , usr etc. Conclusion

In summary, you have learnt that:

  • Variables are like boxes for keeping data or information
  • We can declare variables using var, let and const keywords.
  • To access the value of the variable, call the variable name
  • Lastly, variables should be named in a way that will help easily understand what is inside them.

If you have found value, in this post, kindly leave a comment. Help other #codenewbies by sharing the post.
Written with love from Lagos Nigeria,( thank you )

Top comments (0)