Variables are one of the axiological blocks of any programming language, the way each accent defines how we acknowledge and collaborate with variables can make or break a programming language. This means every developer should be able to accept how to finer work with variables, their rules, and particularities. In today’s tutorial, we’re going to learn how to declare, interact, and scope variables in JavaScript. We’ll acquaint new concepts and important JavaScript keywords like var, let and const. So, let’s get started.

Declaring variables

Nowadays JavaScript has three altered keywords to acknowledge a capricious — var, let and, const. Each has its own backdrop and particularities. Let’s start by making a simple allegory table of the three keywords and then dive into the details.

webrok

Don’t worry if right now you’re not absolutely sure what we mean by scope, hoisting, or any of the other attributes. We’re going to cover them in detail next.

Variable scope

Scope in JavaScript refers to ambience (or portion) of the code which determines the accessibility (visibility) of variables. In JavaScript, we have two types of scope, local , and global. Though local scope can have altered meanings.

Let’s work through the definitions by giving some examples of how scoping functions. Let’s say you define a variable message:

webrok

As you may expect the variable message used in the console.log would exist and have the value Hello World. No doubts there, but what happens if we change a bit where we declare the variable:

webrok

Oops, it looks like we broke it, but why? Well, the if account creates a local block scope, and since we used ‘const’ the capricious is only declared for that block scope, and cannot be accessed from the outside.

Let’s talk a bit more about block and action scopes.

Block scope

A block is basically a area of code (zero or more statements) which is belted by a pair of curly braces and may optionally be labeled.

As we already discussed the use of let and const allows us to define variables that live within the block scope. Next, we’ll build very agnate examples by using altered keywords to accomplish new scopes:

webrok

Let’s explain this one as it may look a bit aberrant at first. In our outer scope, we were defining the variablex1with a value of1. Then we created a new block scope by simply using curly braces, this is strange, but absolutely legal within JavaScript, and in this new scope, we created a new capricious (separate from the one in the outer scope) also namedx1. But don’t get confused, this is a brand new variable, which will only be accessible within that scope.

Same archetype now with a named scope:

webrok

The ‘while’ example, but don’t run this code below. I’ll explain why soon.

webrok

Can you guess what’s wrong with the code above? And what would happen if you ran it? Let me explain, x3 as declared in the outer scope is used for the while comparison x3 === 1, commonly inside the while statement, I’d be able to reassign x3 a new value and exit the loop. About as we’re declaring a newx3 within the block scope, we cannot change x3 from the outer scope anymore, and thus the ‘while’ action will always appraise to true bearing an absolute loop that will hang your browser, or if you’re using a terminal to run it on NodeJS will print a lot of2.

Fixing this accurate code could be tricky unless you absolutely rename either variables.

So far in our example, we used const, but absolutely the same behavior would happen with let. However, as we saw in our allegory table, the keywordvar is absolutely the action scope, so what does it mean for our examples? Well, let’s take a look:

webrok

Amazing! Even though we re-declared x4 inside the scope, it afflicted the value to2on the inner scope as well as the outer scope. And this is one of the most important differences between let,const, andvar and is usually accountable (in one way or another) for account questions.

Function scope

A action scope is in a way also a block scope, so let and constwould behave the same way they did in our antecedent examples. However, action scopes also abbreviate variables declared with var. But let’s see that continuing with our xn examples:

const or let example:

webrok

Exactly as we accepted it, and now with var:

webrok

In this scenario, ‘var’ worked the same way as let and const. Also:

webrok

As we can see, var declarations only exist within the action they were created in and can’t be accessed from the outside. But there’s more to it, as always JS has been evolving, and newer type of scopes have been created.

Module scope

With the addition of modules in ES6, it was important for variables in a module to not anon affect variables in other modules. Can you brainstorm a world where importing modules from a library would battle with your variables? Not even JS is that messy. So by definition, modules create their own scope which encapsulates all variables created with var,let or const, agnate to the action scope.

There are ways though that modules accommodate to export variables so they can be accessed from alfresco the module, and that I covered already in a previous article: An Intro To JavaScript Modules.

So far we talked about altered types of local scopes, let’s now dive into globalscopes.

Global scope

A capricious authentic alfresco any function, block, or module scope has global scope. Variables in global scope can be accessed from everywhere in the application.

The global scope can sometimes be abashed with module scope, but this is not the case. A global scope capricious can be used across modules, though this is advised bad practice, and for good reasons.

How would you go about declaring a global variable? It depends on the context, it’s altered on a browser than a NodeJS application. In the ambience of the browser, you can do article as simple as:

webrok

Or by using the window object:

webrok

There are some affidavit you wanna do article like this, however, always be accurate when you do it.

Nesting scopes

As you apparently estimated by now, it’s accessible to nest scopes, acceptation you can create a scope within addition scope, and it’s very common practice. Simply add an if account inside a function. So, let’s see an example:

webrok

Lexical scope

In a way, we already made use of lexical scope, though we didn’t know much about it. Lexical scope simply means the other scopes have access to the variables authentic in outer scopes.

Let’s see it with an example:

webrok

That looks drifter than what it is, so let’s explain it. The functionouterScope declares a variablenamewith valueJuan and a action named innerScope. The later does not acknowledge any variables for its own scope but makes use of the variable name declared in the outer action scope.

When outerScope()gets called it allotment a advertence to the innerScope function, which is later called from the exoteric scope. When account this code for the first time you may be abashed as to why innerScope would console.log the value Juan as we’re calling it from the global scope, or module scope, where name is not declared.

The reason why this works is thanks to JavaScript closures. Closures is a topic of its own and you can read more about it on the MDN docs.

Hoisting

Hoisting in terms of JavaScript means a capricious is created in memory during the abridge phase, and thus they can absolutely be used before they’ve been declared. Sounds super confusing, let’s better see it in code.

This is what a normal flow would look like:

webrok

As accepted that works, but what would you think of the following:

webrok

Wait wait wait…. what? As crazy as it sounds, since the action is assigned to memory before the code absolutely runs, the function hoistedDisplayName is accessible before its actual definition, at least in terms of code lines.

Functions have this accurate property, but also do variables declared withvar. Let’s see an example:

webrok

The fact the capricious is “created” before its actual analogue in the code doesn’t mean its value is already assigned, this is why when we do the console.log(x8) we don’t get an error saying that the capricious is not declared, but rather the capricious has value undefined. Very interesting, but what happens if we use let or const? Remember in our table, they don’t share this property.

webrok

It threw an error.

Hoisting is a lesser-known acreage of JavaScript variables, but it’s also an important one. Make sure you accept the differences, it’s important for your code, and it may be a topic for an account question.

Reassignment of variables

This topic covers accurately variables declared with the keyword const. A capricious declared with const cannot be reassigned, acceptation we can’t change its value for a new one, but there’s a trick. Let’s see some examples:

webrok

As we expected, we can’t change the value of a constant, or can we?

webrok

Did we just change the value of a const value? The short answer is, no. Our constant c2 references an object with a property name. c2 is a advertence to that object, that’s its value. When we do c2.name we are really taking the arrow to the c2 object and accessing the acreage from there. What we’re alteration when we do c2.name is the value of the property name in the object, but not the advertence stored in c2, and thus c2 remained connected though the acreage value is now different.

See what happens when we absolutely try to update the value differently:

webrok

Even though the object looks the same, we’re absolutely creating a new object { name: 'Gera' } and trying to assign that new object to c3, but we can’t as it was declared as constant.

Today I covered the topic of capricious declarations and scoping in JavaScript. It’s a very important topic that can explain many weird situations happen to our code. It’s a must-learn skill for all JavaScript developers.

This article was originally appear on Live Code Stream by Juan Cruz Martinez (twitter: @bajcmartinez), architect and administrator of Live Code Stream, entrepreneur, developer, author, speaker, and doer of things.

Live Code Stream is also accessible as a free weekly newsletter. Sign up for updates on aggregate accompanying to programming, AI, and computer science in general.

Read next: Pardon the Intrusion #23: Read this if you have a wearable

Pssst, hey you!