Javascript Closures for Wizards

A bit of a daft experiment in writing a piece about closures and what they mean in a the style of an 80s “learn basic” book.

Javascript Wizard

Let’s dive into the whimsical world of JavaScript, specifically the magical concept of “closures”! Imagine you’re a wizard, and every time you cast a spell (which is like writing a function in JavaScript), you can remember and use the magical ingredients (variables) that were available when you first learned the spell. That’s what closures are all about!

In JavaScript, a closure happens when a function “remembers” the environment or scope in which it was created, even after that environment has gone. It’s like having a backpack that you can fill with stuff (variables and their values) from your current surroundings (the function’s scope). When you move to a new place (execute the function somewhere else), you still have your backpack with all the stuff from before.

Let’s conjure up a couple of simple examples:

Example 1: The Counter Spell

Imagine you want to create a counter that keeps track of how many times a button is clicked.

function createCounter() {
    let count = 0; // This is like putting a 'count' variable in our backpack.

    return function() {
        count += 1; // Every time we call this, we increase the count.
        console.log(count);
    };
}

const myCounter = createCounter(); // Cast our counter spell.
myCounter(); // Outputs: 1
myCounter(); // Outputs: 2

In this magical trick, createCounter is a spell that returns another spell. The inner spell changes the count variable, which is remembered (thanks to the closure) even after createCounter has finished executing.

Example 2: The Secret Keeper

Now, let’s keep a secret inside a function:

function createSecretHolder(secret) {
  return function() {
console.log(The secret is: ${secret});
};
}
const mySecret = createSecretHolder("JavaScript is fun!");
mySecret(); // Outputs: The secret is: JavaScript is fun!

Here, createSecretHolder takes a secret and returns a new function that remembers that secret and can reveal it whenever it’s called. The secret stays safe and sound inside the closure, like a message in a bottle!

In both examples, the functions remember the variables (count and secret) from their original environment. This memory trick is all thanks to closures!

So, in the enchanting land of JavaScript, closures are like memory charms, allowing functions to remember and access variables from an outer scope, even after that outer scope is gone. It’s a handy spell to have in your grimoire! 🧙‍♂️✨

Why does this work? (without wizards ;))

Understanding JavaScript’s Execution Context

In JavaScript, whenever a function is called, it creates an “Execution Context.” This is essentially the environment in which the function operates. Each execution context contains:

  1. Local Variables: These are the variables defined within the function.
  2. Scope Chain: This provides the function with access to variables outside its immediate scope.
  3. this Value: This is the context in which the function is executed, determining what this refers to.

The Mechanics of Closures

Closures occur when a function defined inside another function (known as an “inner function”) references variables from its enclosing function (the “outer function”). Here’s what happens:

  • When the outer function finishes execution, normally, its local variables would be discarded and its memory freed up. However, if an inner function still exists and it references variables from the outer function, those variables are not discarded.
  • Instead, these variables are stored in a special “Closure Scope.” The inner function maintains access to this Closure Scope.
  • This means the inner function can access and manipulate the variables of the outer function even after the outer function has completed execution.

Underlying Technical Details

From a technical standpoint, this behavior is tied to how JavaScript manages memory. The language’s garbage collector does not remove variables that are still accessible by a living function. In closures, the inner function keeps a reference to its outer function’s environment, thus preventing the garbage collector from removing those variables.

Practical Implications of Closures

Closures have several practical uses in JavaScript:

  • Data Encapsulation: They allow for creating private variables that are accessible only within a certain scope, enhancing data protection and modularity.
  • Callbacks and Asynchronous Programming: Closures are essential in patterns like callbacks, especially in asynchronous operations like event handling or server requests, as they remember the environment in which they were created.

Conclusion

In summary, closures in JavaScript enable functions to remember and access variables from an outer scope, even after that outer scope has finished execution. This is achieved through specific memory management techniques inherent to JavaScript, allowing for more powerful and flexible programming constructs.

Vscode Theme

This isn’t really a post about what them or how to comprehensively style VScode to create a new theme. It’s because I like to make my VScode look like the 80s has thrown up all over it. It took a bit of time to find this info so I thought I would put it all in one place. Personally I never found a theme that suited me so I was looking for how to change default colours myself.

Below is an example of the high-contrast (ish) colour scheme I prefer to use.

It’s horrific but it works for me.

tokenColorCustomizations and settings.json

VScode has a very nice settings.json that allows you to customise everything in one place. If you haven’t had a look just ctrl + shift + p and type settings and the file should appear under the command box

To be able to style the editor to your liking you will be changing this block of json. I think you can infer quite clearly what is going on here. You have the scope which has a commented list of properties and settings that has a commented list of text styles in key value pairs.

editor.tocenColorCustomizations

The problem I faced was knowing the names of the properties I needed to change. To find these you need to go to the command input, look for and click “Developer: Inspect Tokens and Scopes”

Developer: Inspect Editor Tokens and Scopes

Now when you click on a word in the editor you should see what the propertie name for that element is. You will get an info box like the one below and you can see the property type here is “support.type.property-name” which you can now use in settings.json to update that elements style.

vscode token scope

I think that should cover it for now 🙂

A Very Simple Example of Functional Programming in JavaScript

The functional programming paradigm is quite a popular thing at the moment and it is something I keep meaning to take more of a look at and add to my work process. I thought I would start with something very simple; a loop that would call another function and iterate over itself.

Here’s my example, as you can see it does nothing special just takes two values and increments one of them. It calls the console log function and if the count is not reached does the whole thing again.

const looper = (start, count) => {
  // do something or call something
  console.log(start);
  
  start += 1;

  if (start <= count) { 
    looper(start, count);
  }
}

looper(1, 10);

Wayback When

Had a little trawl on the wayback machine and found this beauty from 1998 – the first commercial website I worked on. Okay so it’s pretty ugly but I am still proud of working on this baby. When web development was a lot more brute force. There were no editors or IDEs and you had to ftp everything.

My duties were creating the beautiful graphics you see before you, hand coding HTML in notepad, creating adverts in gif form and uploading them as per an enormous spreadsheet and not to mention the evils of early days javascript

A splash screen!! the bosses loved a splash screen
Take your pick we have it all, I feel I need to download this and host the thing again… I wonder if if

Tables were the order of the day, because, well, you couldn’t actually get a design to hang together without them and often times all text was in gif form – oh the lack of accessibility and of course we wouldn’t do that now. Oh and iframes, I sincerely apologise but there may well have been an iframe or two knocking around this site.

woo animation

And with this new online technology comes animation, just check out how dynamic this gif is, it really does show Auto Trader to be a modern online presence.

As you will have guessed this is the search form, I have no idea who decided green for the extra bits. The back end for the search, if I remember correctly, was all done by one chap, Greg, the guy was a bit of a genius. The one issue we did have with it though was that it couldn’t differentiate between the manufacturer Seat and the fact a car had seats because it was essentially doing a text search across flat files.

Me back in the 90s contributing to what now looks like comedy web design, checkout the retro equipment

So to us now this looks like I’ve been on a bit of a mission to collect the greatest in retro tech from ebay, but no! you would be wrong. What we have here is a lot of very expensive equipment… it could even render images in lightroom ( a 3D package) at quite a pace. Auto Trader were not stingy when it came to equipment – you couldn’t lug it home to work from home. I don’t think we went home much as we generally played Quake in the evenings.

Javascript Events

…and triggering them

Recently I had an issue attempting to dispatch an event to a DOM element in a unit test. The particular element was a radio button and the way I would normally create an event:

var event  =  new Event('click',{'bubbles':true, 'cancelable':false})

object.dispatchEvent(event)

just didn’t work, this led to some digging about, looking through various documentation .. you know the score.

In the end I had to resort to a much older method of using object.click()

object.click() 
new MouseEvent('click', {bubbles:true});

more information:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click

https://developer.mozilla.org/en-US/docs/Web/API/Event/Event

https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent

Powershell Bits & Bobs

Autocomplete

How to add bash-style autocomplete to powershell. Just add the following to your profile1 script.

Set-PSReadlineKeyHandler -Key Tab -Function Complete

Execution Policy

When setting up a profile.ps1 you will most likely be unable to run any of the scripts you have written. By setting the execution policy to remote unsigned it stops scripts being run via third parties.

set-executionpolicy remotesigned

What Version

The version of powershell you are currently running is in the versiontable


$PSVersionTable.PSVersion

Useful Git Commands

I have found Git to be the best code repository I’ve used in time as a web developer. I’ve made a list of some Git commands that I have found useful. Many of these I’ve added aliases to configs to improve my workflow.

I’ll update this list as and when I get time

Editing Your Config

  • global: git config –global –edit
  • local: git config –local –edit

Deleting Branches

  • from remote: git push origin :<branchname>
  • from local: git branch -D <branchname> (the -D will force it)

Working With Another Branch

  • show the file list: git ls-tree -r origin/<branch name> <path to file> 
  • show the file contents: git show origin/<branch name>:<path to file>
  • copy a file: git show origin/<branch name>:<path to file> > <path to move file to>

Working With Merges

  • show branches merged into a specific branch: git branch -a -v –merged <branch name>
  • as above but add  name filter: git branch -a -v –list <filter wildcard> –merged <branch name>

Listing Branches Using Refs

  • Details of all branches: git for-each-ref –sort=committerdate –format=’%(color:cyan)%(committerdate:short)%(color:white) ,%(color:green)%(refname:short)%(color:white) ,%(color:yellow)%(authorname)’

 

 

 

The classic “Hello World”

Like a lot of Devs I have come across in my time in IT, I have procrastinated and procrastinated some more, rather than set up a space/blog for myself.

So I have decided to just install the vanilla WordPress and the default theme, resist the temptation of ‘designing’ a blog and start putting down some thoughts, spout nonsense and use it as a space to store some code etc for future use.