Taking Notez – Island Pond Consulting

Notes from My Work with Salesforce and Cloud Technologies

Return to JavaScript: Function and Block Scoping

leave a comment »

Confession: I’m not organizing my posts in any particular order. It’s really a reflection of what I find interesting as I dig into the “new” world of modern JavaScript.

In my former life as a developer using JavaScript I defined variables with the var keyword. For me, that meant that the some variables were defined at the “root” and were global. Others, defined in a function were limited to the function. A problem could arise in which a global variable is modified in a function leading to unexpected outcomes.

To be fair, most of my work was dealing with doing client side validation of input fields so this wasn’t a frequent problem. My function would accept a value, test it, and the user could “move on” or “try again”.

Now, however, with dynamic pages consisting of a lot of CSS and JavaScript, understanding the management / scope of variables becomes much more important.

Having learned Java, I was familiar with using code blocks to do more than make my close look nice. I could shield variables within blocks as well as functions. Not so with JavaScript var declarations. Enter the let keyword.

Variables assigned with let are always block scoped. But this isn’t the only benefit to using the let keyword. Variables assigned this way also cannot be hoisted“. This quote, from “Explore New Syntax in JavaScript ES6” is a part of a fantastic primer on the “new” JavaScript universe and I highly recommend it.

Hoisting is a feature of JavaScript that is personally annoying. I grew up in Fortran and still prefer the orderly progression of procedural programming. Hoisting, in case you don’t know, allows a developer to put variable declarations “anywhere” and use them lines (and more lines) before they are declared. Too many times I’ve found myself reading a page, finding a variable and wondering, “Wait, where the heck did that come from?”.

The keyword, let, doesn’t guarantee I’ll know where a variable was declared but, if I’m reading from the beginning, there’s a better chance I’ll know. So, now I have a new tool in my tool box for declaring variables and (very excited) being able to organize them in blocks as well as in functions.


Written by David Wilkerson

August 9, 2020 at 12:37 pm

Posted in General

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

%d bloggers like this: