ES6 variable declaration – let and const


In standard Javascript, the only way to declare a variable in JavaScript was to use the keyword var.

But, in ES6 there are now two new ways to declare variables in JavaScript: let and constlet and const have some other interesting properties.

  • Variables declared with let can be reassigned, but can’t be redeclared in the same scope.
  • Variables declared with const must be assigned an initial value, but can’t be redeclared in the same scope, and can’t be reassigned.

Below is the example to show how let and const is being used:

const CHARACTER_LIMIT = 255;
const posts = [
“Mallik”,
“talksjava “,
“.com”
];

// prints posts to the console
function displayPosts() {
for (let i = 0; i < posts.length; i++) {
console.log(posts[i].slice(0, CHARACTER_LIMIT));
}
}

displayPosts();

Output:

Mallik

talksjava

.com

The big question is when should you use let and const? The general rule of thumb is as follows:

  • use let when you plan to reassign new values to a variable, and
  • use const when you don’t plan on reassigning new values to a variable.

Since const is the strictest way to declare a variable,  you always declare variables with const because it’ll make your code easier to reason about since you know the identifiers won’t change throughout the lifetime of your program. If you find that you need to update a variable or change it, then go back and switch it from const to let.

Advertisements
About

I born in Good cultural place called India. My family is traditional family. We fallow all Indian traditions.

Tagged with: , , , , ,
Posted in ES6, JavaScript

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 678 other followers

Calendar
February 2018
M T W T F S S
« Aug   Mar »
 1234
567891011
12131415161718
19202122232425
262728  
Mallikarjun Gunda

This is Mallikarjun Gunda, I am working as a software professional. Blogging is my Passion. This blog contains the posts on Java related technologies and programming languages. I am happy to share my knowledge through the blogs.

Blog Stats
  • 281,100 hits
IndiBlogger
malliktalksjava.wordpress.c...
70/100