Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 3, 2021 06:28 pm GMT

A nice introduction to JavaScript variables

Content

  1. What is a programming variable?
  2. How do we create a JavaScript variable?
  3. var, let & const declarations
  4. Scope, Hoisting & Shadowing
  5. Which variable declaration keyword should I use?
  6. How should we name our variables?
  7. What can we store inside variables?
  8. Conclusion

What is a programming variable?

One of the core features of any programming language are things called variables. We use variables to store data. Think of them as boxes that contain some entity and without them we lose the item that was stored inside.

Consider a bottle of beer for a second. Or juice depending on your age . If we empty out the liquid it no longer has a container and is doomed to be lost to the floor.

Variables are essential to programming languages because they allow us to store pieces of data that we might need later on.

To be able to focus on variables I will stick to using simple examples and assigning basic primitive data types as values to variables(e.g. numbers, strings and booleans). If you would like to check out more about JavaScript data types you can have a quick read of this article by MDN - JavaScript data types and data structures.

Ready? Let's go!

How do we create a JavaScript variable?

To begin with let's have a look at how we create a variable. The most common syntax is generally as follows where we declare our variable with a name and initialize it with a value .

(variable declaration) (variable name) = (some value);

We also add a semi-colon ; after declaring the variable which is used to to separate expressions. It is also used across many other programming languages for this reason and in JavaScript although it is optional, it is highly recommended that we use them after each code instruction to avoid potential bugs that can arise as a result.

It is also possible to create certain variables that are not initialized with a value. In this case the syntax is as follows:

(variable declaration) (variable name);

Variables created by in this way are initialized by JavaScript at execution with a value of undefined and later we will see this in action.

In JavaScript there are three primary methods of creating variables each with their differences. We start by defining the keyword associated with creating the variable before usually assigning some value to it. Let's take a look at each method and the differences between them.

var, let & const declarations

const

The const declaration creates a read only reference to a value that we must be defined when we create the variable. Let's create some variables below .

Defining some const variables

(The last example is useless I'll admit. There is no need to store a boolean value in a constant that can't be changed, we could just use the value false instead but I thought it was funny so it stays ).

When we define a variable using const what we are actually saying is that the variable identifier(name) cannot be reassigned to another value. See here:

Example of const reassign error

When the const declaration we must also initialize the variable with a value. Not doing so will result in an error.

Example of const re-assign error

This does not mean that the value itself is immutable(can't be changed). Check out this article for a deeper dive to constant immutability with an object example (When to capitalize your JavaScript constants - {Brandon Wozniewicz})[https://www.freecodecamp.org/news/when-to-capitalize-your-javascript-constants-4fabc0a4a4c4/]

We can however create a new const variable that points at an exisiting const variable. In this situation the value stored in the existing variable is copied into the new variable.

Example of pointing one const variable at another

let

The let declaration differs from const because the value stored within a let variable can be changed. We use the let declaration when we know that later on in the program the value is likely to be changed.

With let variables we are not forced to initialize it with an initial value. In this case the variable will be undefined but will not throw an error. Check it out.

Examples of declaring let variables

var

Using the var declaration predates the previous two examples. It used to be the only way do declare variables until let and const were introduced to JavaScript with ES6 in 2015.

In modern code we have taken to using let and const instead of var because of a few problems that can arise which we will soon explore. It is advisable to stick with let and const although having an understanding of how var works is important to fully understanding JavaScript.

Perhaps you will come across this syntax in older codebases or maybe will be asked to solve JavaScript problems that use the var keyword.

Similarly to let it allows us create variables can either be initialized with a value or not initialized at all.

Examples of variables using var

Unlike the let defined variable we can reassign a var variable to a different value like this

var reassign example

In order to properly understand the what the var syntax does, we need to know about a couple of core concepts which are key to mastering JavaScript. Those concepts are called Scope and Hoisting.

Scope and Hoisting

While I am not going to dive too far into each topic(this would probably take at least two more articles to fully explore ), it is important to grasp the idea so that we can explore the differences between var, let and const.

Scope is a concept that defines what variables are accessible at any point in a script. When we create a variable we are defining the scope variable and what has access to it without really knowing it. In JavaScript we have two types of scope when we define a variable. They are Block-scope and Function-scope.

When we create a variable with let or const we are defining the scope of the variable as Block-scope. This means that we can only access this variable from within the same block or further down in the scope tree. A block is defined between the curly braces {} syntax such as in an if statement, a function and more.

var on the other hand defines a variables scope as the current execution context. This is a fancy term that means it will either refer to the global scope(which is shown in the following examples) or the function that it lives in, also known as Function-scope.

In JavaScript a function is simply a piece of reusable code that we can write that allows us to run it whenever we like. When we create a function a new scope is defined for that function.

Using var to create variables can lead to more unpredictable code where access to the variable is possible outside of the current block scope. Consider the following situations .

Accessing var variable outside of its block

There the if statement has its own block scope defined by the curly braces and we define a variable using var. But this variable is function-scoped meaning it can be accessed from outside in the scope above(in this case the global scope). And this is not necessarily something we want to be able to do. If we try to do the same but instead create the variable using let then we will see a very different result.

Example of let block scope

let defines the scope of the variable as being block-scoped meaning we can only use it from within that block or any nested scope below this block. Here we will add an if check inside the original if therefore creating another nested scope such as this .

Example of nested scope

Here you can see we are able to access the let variable from a nested scope of the scope in which it was created but not from outside. This is a key concept to be aware of as you start working with functions and you are only able to access certain variables in specific scopes.

The second key concept I mentioned was Hoisting. Hoisting is the JavaScript mechanism by which variables and functions are moved to the top of their own scope before the code is executed. When we declare a JavaScript variable it is hoisted. In the case of the var declaration if we try to access it before we declare it, we won't get an error and instead it will return the value undefined.

Opposed to this are let and const where JavaScript does not allow us to access theses variables before we declare them. They are still hoisted to the top of the block however instead of returning undefined and carrying on we will get an error for trying to access it before declaration.

It is always advised whenever possible to initialize your variable declarations with a value to avoid situations where you run into undefined instead of an error resulting in a difficult to debug problem.

Finally shadowing is a concept that we see when we define a variable in a nested scope that has the same name as a variable in its outer scope. Take a look .

example of variable shadowing

Even though we have already defined a const called name, JavaScript does not throw us an error. From the nested scope name will have the value "Bob" while on the outside it will be "Kieran".

Which variable declaration syntax should I use?

This decision has become tricky in recent years since let and const were introduced to JavaScript with ES6(EcmaScript 2015) especially to beginners who are unsure of the differences. In modern code you will often see let and const used exclusively, replacing the former declaration var. These newer methods of declaring variables are generally considered the better approach because they solve some of the problems that come with using var.

Using the var keyword can lead to some unpredictable results. var allows for multiple variables of the same name to be declared re-assigning it a new value. But this is not really something we want. We might accidentally overwrite an important piece of data and JavaScript would not give us an error leading to problems while debugging.

This type of silent failing can be largely eliminated if we stick to using let and const where block-scope is more predictable and easier to grasp for most developers. We will be provided with errors by JavaScript which means we can fix our bugs early before they become a pain in the backside.

Therefore if we need a constant variable where the value is not going to change we use const. If it's value is likely to change then go with let. Even if you are not sure it is not the end of the world. You can start by using const and if you later change the value stored in the variable, your code editor should warn you about the error and before you know it you'll know exactly which declaration to use.

How should we name our variables?

So we now know what variables are. We know how to create them and which versions of variable creation we should use based on the situation. One often overlooked aspect of creating variables is naming them. We should always try to give our variables names that correspond to the data that they hold and sometimes it is more difficult than it seems.

Assigning names in this way helps us because our code is then more readable and much easier to debug. Check out some examples of good and bad variable names

variable naming examples

and another

variable naming examples

You can see in the example above we have a variable name called productName which contains multiple words with the second of which beginning with an uppercase letter. This naming convention is called "Camel case" or "camelCase" where we don't use any spaces to separate words but instead we capitalize any words that come after the first word.

My first Name would become myFirstName.

Camel case naming convention is the commonly accepted method of naming JavaScript variables and also functions with a few exceptions(class initializations, private class properties etc) which will not be covered in this article.

Another naming convention that you might come across relates to boolean values. To help us differentiate boolean variables from other variable types we prefix the variable name with a helper word such as "is" or "are".

Example of boolean variable naming convention

You might also look at someone else's JavaScript code and see a const variable that is all uppercase letters. This is used to denote a constant variable that will point at the same primitive value throughout the lifetime of the script. These primitive values include string, number, boolean, symbol, undefined and BigInt but this convention is generally used when the value is a string or number.

There is really no use case for storing a boolean in a const (as I explained in the first example ) that you never intend to change while storing undefined in a variable is not recommended. Symbols and BigInt types are not used as often although they have their use-cases in other situations.

uppercase constant variable naming example

This is again a convention and not required although it does help us differentiate our variables so they are easier to spot and debug.

There are two rules when it comes to naming variables that JavaScript imposes on us. These are as follows:

  1. The first character of the variable name cannot be a digit
  2. Variable name can only contain letters, digits, or the symbols underscore(_) and dollar sign($).

To finish let's take a quick look at a few examples of names we cannot give to variables even if we really wanted to. Check it out .

Variable names not allowed by JavaScript example

JavaScript also has a few keywords that are reserved and cannot be used to name variables. These can be found here at w3schools.com - JavaScript Reserved Words.

examples of variables using reserved words

What can we store inside variables?

So far you have seen me store strings, booleans and numbers inside variables to introduce you to the basics but really we can use them to store much more. More advanced JavaScript data types such as arrays, objects and also functions which are themselves just objects can and are often stored inside variables so that we can reference the data they hold whenever we require. Below is an example of common types of data we store in variables.

Examples of advanced data types stored in variables

Variables are key in allowing us to build all kinds of applications and there is so much we can do but this has been a nice introduction to JavaScript variables. We've only just scratched the surface.

Conclusion

Now that you have a basic understanding of JavaScript variables I hope you can go off and experiment yourself to see what else you can do with them.

Thanks for reading! If you would like to see more from me including my progress as a developer then come say hi on twitter @Kieran6dev.


Original Link: https://dev.to/kieran6roberts/a-nice-introduction-to-javascript-variables-40gd

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To