Variables II (Constants and Scopes) - Beginner's JS

Variables II (Constants and Scopes) - Beginner's JS

ยท

5 min read

You've learned the importance of variables and how to create them. But there's just one more type of variable that we need to know about. This is called the constant.

Constants are a type of variable whose initial value is absolute and cannot be reassigned further in your program. They're containers, just like variables, but the value within a var/let variable can be changed at any point in time, while constants, well...once it's created with a value, you cannot change it without invoking an error.

Let's look at the differences using code:

//Variable
var a = 23;
console.log(a);
//Displays: 23

a = 42;
console.log(a);
//Displays: 42

//Constant
const b = 23;
console.log(b);
//Displays: 23

b = 42;
//Uncaught TypeError: Assignment to constant variable.

Do you see the difference?

Constants are extremely useful whenever you want to assign a value that you wish not to be changed by any other operation in the program. Let's face it, as you continue to write more code, you will be confused with all of the variables you created. It's easy to be confused with them, so constants help you to avoid making huge mistakes you might regret.

Scopes

You may recall in the first article of this series, we mentioned the keywords 'let' and 'var'. We know they're used to create variables, but what exactly is the difference?

'var' variables can be used at any point of the program. Consider it a 'global' variable. However, 'let' variables are restricted to its 'scope'.

Now...wait...calm down. If you didn't quite get that paragraph, let me help you out.

Think of scopes like access levels. Let's say you're a junior ๐Ÿง‘๐Ÿฝโ€๐Ÿ’ผ in a company and you only have access to information that is available to your level, while, maybe your boss ๐Ÿ‘จ๐Ÿผโ€๐Ÿ’ผ or your boss's boss ๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ผ may have access to information you see...and more.

Like the above, scopes are like access levels. Whether or not you can access a variable and it's value depends on which scope you declared the variable in.

Let's visualize how scopes work by using code. :)

var num = 22;

Notice that the above variable, num, was assigned the value of 22 and is not inside any function or class? This is known as a Global Variable and the place it was defined in is the Global Scope๐ŸŒŽ. Global Scopes are accessible anywhere in the program. If we were to use our first example here, I'd say the Global Scope is information that you, your boss and other people can access. (Like public, non-confidential information available company wide)

There's also the 'Local Scope'.

function localScope(){
      num1 = 3;
}

Yes, you guessed it (or not). Functions create a new scope. Variables defined here can only be accessible within this scope. The value of the variable, however, can be accessed when we use the 'return' keyword followed by the variable that holds the value.

function sayHello() {
    let message = "Hello World";
    return message;
}
๐Ÿ’ก
Note: Conditionals such as if/else, switch and loops (for, while) do not create new scopes. So variables defined in an if statement, for example, can be accessed outside of the statement since it's considered a 'Global Scope'. (Once you use var, that is. We'll explain more later)

Let's look at another example of how scopes work.


var num1 = 22; //global variable

function showNum(){
      var num2 = num1; //num2 is a local variable
      console.log(num2);
}

showNum();
//Result: 22

The variable num1 is a 'global variable'. Notice that we referenced that variable into the new scope we created in the function showNum. What this does is assign the value of the num1 variable to the num2 variable. The JS engine first searches for the variable (num1) inside of the local scope, then once not found, it searches the 'Global Scope' or the scope immediately outside of its local scope. (starts from the inside, ends on the outside...there, that might help you visualize it)

But, it can't work the other way around.

var num1 = 22;

function showNum(){
      var num2 = 44;
}

num1 = num2;

console.log(num1);
//Result: Uncaught ReferenceError: num2 is not defined

Here you see the variable num2 being referenced outside of the scope it was defined in. The JS engine searches for the variable in the global scope, and since 'global' is the last level, there's no other scopes to check, so you're thrown a 'ReferenceError'.

let vs var

Now that you have an idea of what scopes are, let's explore the difference between let and var.

Well, you've seen how we used var above. But, here's where 'let' differs,

//Example with var

var bool = true;

if (bool){
   var answer = "This is true";
}
else{
   var answer = "This is false";
}

console.log(answer);
//Result: This is true


//Example with let

let bool = true;

if (bool){
   let answer = "This is true";
}
else{
   let answer = "This is false";
}

console.log(answer);
//Result: 'answer' not defined

How does this work?

let is blocked based. It can only be accessed in the block it was declared in. Essentially, it acts like that block is it's 'scope'. While var, on the other hand, is not restricted by block (unless it's a function which creates a new scope, of course).

let is to blocks as var is to scopes :)

Variable Hoisting

Of course, every programming language has it's syntax; rules that you must follow. In some cases, JavaScript allows for some rule breaking.

One common example of this is referencing a variable before it has been initialized. Hoisting refers to moving up variable declaration at the top of the script. Let's see how the keywords 'let' and 'var' differ as it relates to this situation.

console.log(bool);
//Returns: Undefined

var bool = true;

In the case of var, JavaScript searches for the referenced variable. If not found, the variable is declared at the top of the script. No ReferenceError is throw. The variable is declared and assigned "undefined".

So instead, the script would look like this:

var bool;

console.log(bool);

bool = true;

In the case of let, there's no hoisting when referencing a variable that was not declared. Instead, JavaScript throws an error.


console.log(bool);
//Returns: Uncaught ReferenceError: counter is not defined

let bool = true;

Now...you know the difference, you've seen the code. Go ahead and code away my little dev.


Don't forget to follow me social media accounts :) :

Twitter/X - steph_codes

Threads - steph.codes

Instagram - steph.codes