const: JavaScript ES6 best practice

Summary

The audience for this article is JavaScript programmers. Intermediate programmers are likely to have seen the ES5 information before. The ES6 (ES2015) information might be new to them.

In the JavaScript ES6 world, a growing number of programmers are converting from declaring variables with ES5 “var” to ES6 “const” and “let”. Perhaps unexpectedly, some of them are advocating using “const” for every variable they plan to leave constant during its life. (Those radicals! Only …) I’m joining them.

Note

Some readers may consider this post a large departure from my prior posts. This is not an example of project management content. I expect some future posts to be about PM and some to be about programming. This one is about JavaScript programming. I’ll use tags to separate them.

Detail

definition: In computer code, a problem is a condition that is troublesome enough to change. A near-synonym: bug.

This ES5 JavaScript includes a number of improvable conditions.

var startUSCivilWar = 1861
function example () {

… // More code here.
startUSCivilWar = 1961

// Changing history?

console.log(“The ” + warName +
” started in ” + startUSCivilWar +
“.”)

// Uses the warName declared
// later because of hoisting.

… // More code.
var warName = “U.S. Civil War”

}

Condition 1: Our code declared a variable (startUSCivilWar) outside all functions, so it’s a global variable in the computer environment. Everyone sharing the environment has access to it. Had we happened to use a variable name JavaScript already used, the JavaScript variable is unavailable to us and everyone else using the environment. Suppose we chose a variable name like “Object” or “Array”? (Please don’t do either of those in a production environment! 🙂 ) Ick.

Condition 2: Our code changed startUSCivilWar, which is probably bad; it might not be intentional. It’d be great if the interpreter could help us find the condition.

Condition 3: Our code used a variable warName not declared at time of use. Would you agree that it’s at least ambiguous (maybe even questionable) whether the programmer intended this value for this log statement? Lots of programmers with code like this later consider the code to have a bug (or a problem). Can the interpreter help?

Here comes ES6 with some new options.

const declares a variable whose value the interpreter won’t change.

Both const and let declare a variable that cannot be used before its declaration. The variable is still hoisted; the area where it can’t be used is its “temporal dead zone”. (Fancy term, huh?! Sounds terrible.) See discussion in [Zakas 2016] or elsewhere.

const and let variables declared outside all functions are available globally, but aren’t global variables. The earlier “Object” and “Array” examples would thus block use of those JavaScript variables in your code, but not in others’ code. I say: That’s better.

The same ES6 code might look like (underlines indicate changes):

const startUSCivilWar = 1861
function example () {

… // More code here.
startUSCivilWar = 1961

// Error. Changing a constant.

console.log(“The ” + warName +
” started in ” + startUSCivilWar +
“.”)

// Error. Undeclared
// variable: warName. The
// later one isn’t usable
// until declared.

… // More code.
var warName = “U.S. Civil War”

}

Variable startUSCivilWar is available everywhere in your program, but it is not a global variable.

The interpreter threw a couple errors, each of which give you a chance to change a condition before they’re problems. Further, it flags them during development, before your boss or client sees them in execution. Low cost; high benefit. That’s an easy decision.

Personal experience with const and let: I find that I know at declaration time whether I intend to change the variable value. Using const or let accordingly is an easy habit for me.

Roughly half of my variables are constants. I presume that’ll change with the types of programs I write.

Due credit: I didn’t come up with this. I got it from [Zakas 2016], page 12. I presume lots of other places on the web recommend it. I join them.

Source Mentioned

[Zakas 2016] Nicholas C. Zakas. UNDERSTANDING ECMASCIPT 6. No Starch Press. San Francisco, 2016. ISBN 978-1-59327-757-4. Also here on the web, accessed Wed Oct 19, 2016.

Upcoming Events of Note

I need to be more regular about posting messages here about upcoming events. (Okay … I need to be more regular about posting messages here period. That’s another issue!) Two coming events deserve announcement here.

Policy: I intend announcements like this to be a service to readers. No one approached me to post these notices; I don’t expect to receive anything in return. (Though … it’d be nice to earn a reader or two!) I hope this helps you.

Omaha Agile Development
“A Walk Down the Agile Coach Development Path – Lyssa Adkins & Michael Spayd”
Tue Mar 19, 2013 5:30 PM
March 2013 Omaha Agile Development Group
free; some of these events include food

Lyssa is author of “Coaching Agile Teams”, part of the now-familiar (to readers of many Agile books) “Addison Wesley Signature Series”, this one with forwards by both Mike Cohn and Jim Highsmith. Lyssa and Michael are Co-Founders and Co-Presidents of the Agile Coaching Institute. At one point, there were 110 people signed up for this event. Come see your agile peers!

UNO IT Professional Academy
numerous seminar subjects
Thu Apr 4 and Fri Apr 5, 2013
UNO Peter Kiewit Institute
UNO IT Professional Academy
registration instructions at above site

I wrote about the October version of this event at Good Renewal Experience. Both presentations I saw in October are offered again.

Perhaps I’ll attend one or both of these and write a summary of my experience, much like Good Renewal Experience and Agile Myths and Ideologies Meet the Scaled Agile Framework. And perhaps someone else will attend and post their summary here! I’ll welcome other submissions; I don’t guarantee inclusion here, but it’d be great to include such work here!

Community Discussion: What’s a Good Direction for Change on This Blog?

So … as of Sep 2012, I’m new to this blogging thing, other than reading some now and then. It’s kinda like having a newspaper or a magazine column in that among my writings, I write what comes to mind and wait to see whether it builds a readership. It’s unlike those more familiar outlets in that I’m the editor and publisher, too. So … I don’t have a trusted colleague with ready advice and shared goals. (Well … my readers … you, of course …)

So … and this goes throughout the life of this blog: How can this blog better serve you? Prove more interesting? Are the posts “too long”? Are they “too [something else]”?

All feedback welcome … always …

Community Discussion: Use a Blog to Increase Project Team Communication?

Last week at ProDev, I heard that some project teams use blogs for some of their communication. One project team I serve is considering one.

Whatchathink?

Advantages I can see:

  • Add another channel for communication.
  • Adds a source of documentation for the project.
  • This communication can involve lots of team members.
  • Can shorten response time when people find an obstacle.

Disadvantages I can see:

  • Adds work to the project: reading it adds project overhead.
  • Adds work to the project: someone has to administer the blog.
  • Can add more ways for project information to leave the team and reduce competitive advantage.

Another disadvantage someone expressed to me: Most office workers are pretty centered on email today. For those who aren’t yet much centered on blogs, the needed behavior change might be an obstacle. (“Another application I have to remember to open once a day?”)

I’ll appreciate any feedback anyone leaves. As I write this, I’m probably motivated by the effect this community might have on the decision my project team is making. On the other hand, I’ll leave this thread open even after that team makes its decision. Thanks in advance.

Addressing disadvantages I saw above:

  • Perhaps, even if there is more project overhead with project contributors reading the blog, this factor is easy to ignore. Perhaps more time reading the blog means less time reading email, tending toward an equal amount of communication time. Perhaps only a small benefit in communication is more valuable to a project than the cost of this overhead.
  • Perhaps administering the blog can be a minor addition to someone’s time. And again, maybe the blog is more valuable than costly.
  • Perhaps information security comes into my consciousness mostly because of my past military experience. We can put a blog on a server inside the corporate firewall. We can require everyone to enter user name and password to get access.