Them’s the Rules, Kid.

Pamela White
8 min readJul 11, 2021

You Can’t Use Anything Outside Its Local Scope

Rules that tell you what you can’t do are terrible rules. A child hits a peer because they want a truck the peer has. The teacher tells the child, “no hitting”. The child is likely to try something else: like kicking or biting. Instead of telling what not to do, describing what to do is a better rule. The teacher might give the rule, “Ask your peer, ‘Can I have that?’ If they say, ‘No”, you can find another truck over there until they are ready to share.” How can we apply this to scope?

Here’s our current problem, which does not involve aggressive children, but furbabies. I want to create a function that finds the adoption age of a pet, then create a function that tells if that pet was a baby, adolescent, adult, or senior when they were adopted.

First, the whole idea of scope was confusing to me, because I did not realize it existed when I first started writing functions. To clear that up, we have global scope and local scope. Global scope is the stuff outside any functions. It can be used anywhere in the code. Local scope is the stuff that is inside the current function. A function can access anything within its own curly braces and the global scope. It cannot access what’s in the curly braces of another function (nested or otherwise). A function nested inside a function has its own local scope and can only access information from its local scope — what’s in its own curly braces — or the global scope.

I’m going to create three variables at the beginning of my code. They are in the global scope and can be used anywhere in the code.

let animalsAge = 15

let currentYear = 2021

let adoptionYear = 2007

Once I write a function, anything inside that function’s curly braces becomes part of the function’s local scope. Here’s function that calculates our animal’s age when they were adopted:

let findAdoptionYear = () => {

let adoptionAge = animalsAge — (currentYear -

adoptionYear)

return adoptionAge

}

Woo hoo! Now I have an adoption age! But wait, the “bad” rule is, “You Can’t Use Anything Outside Its Local Scope”. So the adoption age is useless to me outside the scope of findAdoptionYear(). If I try to use adoptionAge outside, it will return undefined. If I try to use it in the global scope, it will return undefined. If I try to use it in another function, it will return undefined. Even if I try to use adoptionAge in a function nested within findAdoptionYear, it will return undefined (this one really blew my mind):

let findAdoptionYear = () => {

let adoptionAge = animalsAge — (currentYear -

adoptionYear)

let tellAdoptionAge = () => {

return adoptionAge

}

console.log(tellAdoptionAge())

}

Uh….tellAdoptionAge() returns undefined?! What do you mean I can’t use a variable I created in a function outside of its local scope?!?! I need to use that adoption age in another function! Cue cursing, furious attempts, and consumption of chocolate.

Rather than “You can’t…”, here’s a rule that tells what you could do. Like the child who wants the toy, asking the peer for it isn’t the only rule that might work to get it, but the teacher gave that one rule in that moment, because it was the most appropriate for that little learner. So, little learner, one rule about how to use the information from a function elsewhere in the code (not the only way, but one rule): Save the function as a variable in the global scope. The value of that variable will be whatever the function returns.

let animalsAge = 15

let currentYear = 2021

let adoptionYear = 2007

let findAdoptionYear = () => {

return animalsAge — (currentYear — adoptionYear)

}

let adoptionAge = findAdoptionYear()

console.log(adoptionAge)

Woo hoo! This console.log will print the adoption age! Now I can use adoptionAge in another function. I can use adoptionAge to tell me the life stage of my cat when I adopted him:

let tellCatLifeStage = () => {

if (adoptionAge <= 1) {

return “You adopted a baby cat!”

}

else if (adoptionAge <= 3) {

return “You adopted an adolescent cat!”

}

else if (adoptionAge <= 11) {

return “You adopted an adult cat!”

}

else return “You adopted a senior cat!”

}

console.log(tellCatLifeStage())

Bad Grammar? I’m Returning Your Paper

As a university professor (er… adjunct), I told my students that I would return papers with bad grammar. They were students at an elite university, who — even if they did not come from stellar highschools — had free access to tutoring. There was no excuse for poor grammar*. The problem with poor grammar, for me as their professor, was confusion. My confusion reading their work meant a bunch of my time was wasted. And I was not compensated for wasted time. When we use “use strict” on a JS document, it’s a bit like my grammar rule.

First, what is “use strict” and how do I apply it? It’s a set of syntax rules for your code. At the beginning of a JS document, it’s applied globally. It can also be applied locally, like within a function, and only apply to that function.

For this analogy, English grammar is like JS syntax. The “use strict” rule in a JS document means that bad syntax is not allowed. Things that without “use strict” would still work, don’t work under “use strict”. Much like a student’s grammar-mistake-ridden paper, poor syntax under “use strict” returns errors.

Some examples of the strict rules of “use strict” include:

  • No undeclared variables
  • No undeclared objects
  • No deleting variables, objects, or functions
  • No duplicating a parameter name

Some advantages to “use strict” are that it requires the coder to be diligent and clear with their work. Like my no bad grammar rule, in this way, “use strict” makes it a bit easier for others to read your code. My bad grammar rule can help prevent students from communicating things they don’t mean:

Eats shoots and leaves //What a panda does

Eats, shoots, and leaves //Alternative ending to Pulp Fiction

The “use strict” rule also prevents the coder from accidentally changing things you don’t intend to change, like a global variable, which then could effect unintended changes in the entirety of your code.

Some disadvantages to “use strict” include not being able to do some actions (like deleting), and… it requires the coder to be diligent. I’m sure many of my students were annoyed by my grammar rule for this same disadvantage.

*(I need to point out that if any of my students had had English as a second language, I would have made some accommodations. And it wasn’t a no-errors rule, like “use strict”, it was more like, “If I get to a 5th grammar error on your first page, I’m sending it back”. Also, I only had to implement it once. I’m not a monster, but I cannot afford to spend more than 20 minutes deciphering an introduction.)

Always Prioritize

JavaScript reads from top to bottom, but moves declarations to the top of the current scope. The declarations are hoisted to the top. The initializations or values are not hoisted, just the declarations. It’s a bit like collecting a bunch of labeled boxes and putting them in one easily accessible place (in this case, the top of the code). But there’s nothing in those hoisted boxes.This allows them to be used before they have been created.

There may be some great rule about how this hoisting applies to prioritization or vice versa. However, in this case, the Always Prioritize applies to me. I have read at least half a dozen articles, watched two videos, and tried playing around with code to demonstrate it. I don’t understand hoisting any better than this description (above) right now. I need to prioritize other things right now — both in life and in coding — and leave this here.

A Dictionary and a Classroom Contract

The ECMA is an association that creates a set of standards for writing code. Like dictionaries define the official words of a language, the ECMA defines the official rules of writing code. Also like dictionaries, the standards are sometimes updated. Currently we’re using the 10th edition. Humans can communicate by using non-dictionary words, because we can create and learn. Computers only do what we tell them to do; they don’t have creativity and don’t learn things unless we program them to perform some version of learning. They need to follow the same standards to be able to communicate with each other. In this way, ECMA standards are less like a dictionary and more like a classroom contract that a teacher might set up with a class. If you follow the contract, you’ll be able to stay in the class and perform your functions as intended. If you follow ECMA standards, you’ll be able to perform your functions on the World Wide Web.

I am Not Eric Cartman

If you know the show, South Park, you know that Eric Cartman is a bit of a brat who frequently says, “I do what I want”. This is the opposite of the approach I take to coding, because I want my code to be maintainable.

Maintainability (there are entire articles and blogs dedicated to its definition) is essential making sure your code is easy to modify, extend, or use again. Making code maintainable is important to me, personally, because I want to be able to open up something I wrote a month ago and understand what’s going on so I can use it again. It’s important for others, because it’s the way we communicate our ideas, and we want our ideas to be modified, extended, and used again by others. This is especially true in the context of a business or a team.

Here are some ways I try to make my code maintainable:

  • Consistency. I’ve written about this before, but consistency in formatting is a tool I use to make my code more readable, and therefore easy to use later.
  • Whitespace. For the same reasons as consistency, cognizantly using whitespace makes code more maintainable.
  • Standards. While I previously explained why standards are necessary for computers to communicate with each other, they also help people easily understand code.
  • Commenting. This one I’m working on, and I don’t have a lot of examples, so I’m doing what works for me. Commenting code can be a quick way to understand what’s happening — or what’s supposed to happen. Most of us process our own human language (in my case, English) more easily than coding language. Commenting makes code more maintainable because we can more easily know what’s supposed to happen.
  • Descriptive variables, class names, and function names. Similar to commenting, we process human language more easily than coding language, so variables, class names, and function names that are descriptive allow humans to more easily know what’s happening.

DO NOT ENTER

It seems that so many (American) cartoons and sitcoms include the “Do Not Enter” sign on a teenager’s bedroom door. Why would anyone follow that rule? Because entering could have unintended consequences (for an example, see here:

https://www.reddit.com/r/tifu/comments/oeyrvd/tifu_by_responding_to_my_instinct_at_4am/?utm_source=share&utm_medium=web2x&context=3)

Like that Do Not Enter sign on a teenager’s door, a good rule about the global scope on a website is to never touch it. The global scope applies to everything. Changes to one small thing in the global scope will likely have a cascading effect on other parts of the website. When you’re working on a website, it’s unlikely that you know what everything does. It’s even less likely that your job is to change everything it does. Your work likely can be carried out on a more local level and added to the work that’s already been done. And if you do think you need to change something in the global scope, it may be worth it to check in with someone before you do. Kinda like a parent asking their teenager if it’s okay to collect their dirty laundry from their room, rather than just entering.

--

--