DEV Community

Cover image for JavaScript Var, Let, and Const
Bello Osagie
Bello Osagie

Posted on • Edited on

11 3

JavaScript Var, Let, and Const


To declare a variable in JavaScript either var, let or const is used.

Let's see the differences between the three below.


var and let

Block Scope

A Block scope contains a group of code within curly braces {}.

A variable created with the let keyword in a block scope is only available within it.

let greeting = "Hi John!!!"; // Global Variable

if (true) {
    let greeting = "Hello Bello!!!"; // Local Variable
    console.log(greeting);// Hello Bello!!!
}
console.log(greeting) // "Hi John!!!"
Enter fullscreen mode Exit fullscreen mode

let creates either a global or a local variable. If it is out of scope, it's globally scoped else it is locally scoped if in scope.

While;

var always creates global variables.

if (true) {
    var greeting = "Hello Bello!!!";
}
console.log(greeting) // "Hello Bello!!!"

if (true) {
    let hello = "Hello Bello!!!";
}
console.log(hello) // ReferenceError: hello is not defined
Enter fullscreen mode Exit fullscreen mode

Update and redeclaration

Variables declared with either var or let can get updated at any time in a program.

var name = 'Mary';
name = 'Nadia';
console.log(name); // Nadia

let myName = 'Bob';
myName = 'Richard';
console.log(myName); // Richard
Enter fullscreen mode Exit fullscreen mode

Both var and let can be updated as shown above, but only var can be redeclared.

var firstName = 'John';
var firstName = 'Osagie';
console.log(firstName); // John

let lastName = 'Bello';
let lastName = 'Bob';
console.log(firstName); 
// SyntaxError: Identifier 'lastName' has already been declared
Enter fullscreen mode Exit fullscreen mode

image.png


Hoisting

Hoisting is JavaScript's default behavior of moving declarations to the top.

A variable may get to be declared after it has been used. It's only peculiar to the var keyword.

console.log('My name is ' + name); // My name is Michael

var name = 'Michael';
Enter fullscreen mode Exit fullscreen mode

The below example shows how the JavaScript engine will interpret the above code when var keyword is used for declaration.

var name = 'Michael';
console.log('My name is ' + name); // My name is Michael
Enter fullscreen mode Exit fullscreen mode

JavaScript in strict mode ('use strict') does not allow a variable to be used if not declared first.

See the example below:

'use strict';
console.log(name);

var name = 'Jerry'; // no output, no error
Enter fullscreen mode Exit fullscreen mode

When let is used, it is impossible to use a variable before it has been declared.

console.log('My name is ' + name); // ReferenceError: Cannot access 'name' before initialization

let name = 'Michael';
Enter fullscreen mode Exit fullscreen mode

const

Block scope

const has the same feature as let because it also maintains its scope.

const greeting = "Hi John!!!"; // Global Variable

if (true) {
    const greeting = "Hello Bello!!!"; // Local Variable
    console.log(greeting);// Hello Bello!!!
}
console.log(greeting) // "Hi John!!!"
Enter fullscreen mode Exit fullscreen mode

Update and redeclaration

The const keyword is also used to create a variable but can not be updated unlike let and var.

const birthday = '01/20/2020';
birthday = '01/19/2020';
console.log(birthday); // TypeError: Assignment to constant variable.
Enter fullscreen mode Exit fullscreen mode

It is, of course, impossible to update someone's birthday. So use const only when a value will not be updated or changed.

const birthday = '01/20/2020';
console.log(birthday); // 01/20/2020
Enter fullscreen mode Exit fullscreen mode

Since it can not be updated, it can not be redeclared.

const birthday = '01/20/2020';
const birthday = '01/10/2020';
console.log(birthday); // SyntaxError: Identifier 'birthday' has already been declared
Enter fullscreen mode Exit fullscreen mode

Undefined

A const variable must be initialized to a value. If a constant variable is undefined, it leads to an error.

const name; // undefined variable
name = 'Jack';
console.log(name); // SyntaxError: Missing initializer in const declaration
Enter fullscreen mode Exit fullscreen mode

If you plan to undefined a constant variable, use the value undefined.

const name = undefined;

function myName() {
  if (!name) {
  return 'Jack';
}

return name;
}
console.log( myName() ); // Jack
Enter fullscreen mode Exit fullscreen mode

Hosting

const has another similarity with let in terms of hoisting a variable. That is it also doesn't support hoisting.


Conclusion

  • It is advisable to use let and not var has it is the modern way to create a variable in JavaScript.

  • Use const only when a value is constant (immutable variable).

  • It is advisable to always declare all variables at the beginning of every scope with let when necessary to avoid bugs (errors).

Happy Coding!!!


Buy me a Coffee


TechStack Media | Bluehost

  • Get a website with a free domain name for 1st year and a free SSL certificate.
  • 1-click WordPress install and 24/7 support.
  • Starting at $3.95/month.
  • 30-Day Money-Back Guarantee.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (2)

Collapse
 
sanamichael profile image
Sana Michael Yves

Hi, i don't understand why hello variable is not defined.
We know it has been declared like greeting variable.

Collapse
 
bello profile image
Bello Osagie • Edited

Because when let is used to create a variable within a block scope ({ ... }), the variable is only available in it. This type of variables are called local variables; while when var is used to create a variable within a block scope ({ ... }), the variable is available everywhere in the program (within or outside the scope). This type of variables are called global variables

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay