DEV Community

Cover image for Brief Intro to the Variable Keywords in Javascript
Matthew S.
Matthew S.

Posted on

Brief Intro to the Variable Keywords in Javascript

In Javascript, there are three different variable keywords, which include var, let, and const. Each variable keyword acts differently, so it is important to know how they will affect your code.

Var

When declaring a variable using the var keyword, it makes a global scoped variable. Global scoped variables can be accessed throughout your code due to hoisting. Var declared variable can also be reassigned new values.

var name = 'Jack';

function printName() {
  console.log(name);  // accessing global var name
}

printName(); // 'Jack' will be logged to the console
Enter fullscreen mode Exit fullscreen mode

Here we reassign the var name to be a different value:

name = 'Gracie';
console.log(name); // 'Gracie' is now logged to the console
Enter fullscreen mode Exit fullscreen mode

Let

Unlike var, let is a block scoped variable, meaning when you declare a variable using let, that variable cannot be accessed out the block of code where it was created. The only way you could access that variable, is if it was put in the global scope of your code. The let keyword however can be reassigned a new value.

Variables assigned with let cannot be accessed if put within a block of code:

let x = 20
if(x > 10) {
  let message = 'greater than 10';
}
console.log(message); // ref error: message is undefined
Enter fullscreen mode Exit fullscreen mode

They can be reassigned though:

let y = 30;
y = 5;
console.log(y); // 5 will print to the console
Enter fullscreen mode Exit fullscreen mode

Const

The const keyword is also considered a block scoped variable, but variables declared with const cannot be reassigned a new value.

Trying to assign a new value to a const variable will give the following error:

const number = 50;
number = 100; // typeError: assignment to constant variable
Enter fullscreen mode Exit fullscreen mode

Know which to use

It is important to understand when to use each of these keywords because they act so differently from one another. It is now more common practice not to use the var keyword, due to it being globally scoped along with the possibility of accidentally reassigning a variable. If you want to be able to reassign a variable, you can use the let keyword, otherwise use const. Even though both of these keywords are block scoped, you can always just put the variables in the global scope of your code to make them globally accessible.

Even though the concepts and examples shown here are very basic, it is good to get a grasp of the fundamental traits and characteristics of the these three variable keywords and understand when each should be used.

Top comments (1)

Collapse
 
colin-williams-dev profile image
colin-williams-dev

Great job Matthew!