Do You Know the Differences Between var, let, and const?

Quick-start with declaring and initializing variables in JavaScript

Cristian Salcescu
Frontend Essentials

--

Photo by the author

There are three ways for declaring variables in JavaScript. We are going to discuss all and look at the differences between them.

var

The var statement was the initial way for declaring variables but has started to become obsolete.

It is optional to initialize the var variables. An uninitialized variable stores the undefined value.

var name;console.log(name);
//undefined

When declaring a variable with var inside a function that variable is available everywhere in that function.

Variables declared with var have no block scope. Consider the next example.

{
var name = 'Jon Snow';
}
console.log(name);
//'Jon Snow';

Variables declared with var are hoisted to the top of their scope, being that a function or a module, and as such, they can be accessed before the declaration. In that case, they have the value of undefined.

console.log(name);
//undefined
var name = 'Jon Snow';

--

--