Thoughts on ‘The Good Parts of JavaScript and the Web’ by Douglas Crockford

I’ve set aside some time to take some online courses at FrontendMasters to deepen my understanding of various engineering principles as a personal continuing education goal. While taking courses I focus by taking notes, and figured I may as well share them with the world, so welcome to the Learning Series!

The first course is The Good Parts of Javascript and the Web, by Douglas Crockford. The course description is as follows: “In this course, you will learn the history of JavaScript, the details of the language, with particular attention to functions, which is where the power of the JavaScript language is hidden. There is also an overview of how browsers work, how servers work, and security.”

This writeup got a little long because I found so much of the course interesting, so here’s an outline – feel free to jump to the bits you find interesting:

Introduction and Background

Douglas Crockford is the author of the classic title from 2008 that many refer to as the go-to introduction to the JavaScript language: ‘JavaScript: The Good Parts‘. At the time, many classic developers complained about the backward ways of JS, but he wanted to point out the good parts. He’s also the author and maintainer of JSLint since 2002 (the first JavaScript syntax checker) ando behind JSON – he coined the acronym (though wishes now he thought of something better) and was involved in popularizing the data format.

For those that are excited about licenses and things, Crockford also famously used the MIT license in his tools but with a slight modification: He adds the line “The Software shall be used for Good, not Evil“. This is part of the licensing in JSLint as well as JSON. Yay for Good, is your JSON used for Good?

JSLint

JSLint is a static code analysis tool used for checking if JavaScript source code complies with certain coding rules. Douglas states that JSLint “will hurt your feelings”. As linting tools goes, it’s fairly opinionated but in his course he explains many of the reasons for these strong opinions which in his opinion are backed by data and a philosophy that:

If there is a feature of a language that is sometimes problematic, and if it can be replaced with another feature that is more reliable, then always use the more reliable feature.

Good use of coding style can reduce errors, so JSLint helps us to prefer forms of writing code that are error resistant. For example, the roman language initially was all caps and had no punctuation. Scribes would copy written statements and errors would creep in over time. Roman scribes invented punctuation and lowercase letters for legibility. It showed that they could copy with less errors by using these coding styles. In the same way, writing code today doesn’t need to be illegible. Let’s fix it by creating some punctuation rules that will help us and the computer read it better. Additionally, let’s have something that helps us avoid the time loss we tend to endure when finding and fixing bugs. We end up wasting so much time because our mental model of how JavaScript works, is not actually how it always works. Some of the coding issues are because of the discrepancies in how our brains understand the language and some of the issues are a result of badly designed features of the language itself. Some (opinionated) guidelines that come from JSLint for writing better JS include the following:

  • Left or right curly braces? Right is better, some cases of using left will silently break your code and you could waste time diagnosing the simple fix. So consistently use curly braces on the right, because you will never have this problem.
  • Always manually add semicolons – don’t rely on the computer to automatically add them because they sometimes get added in unintuitive ways which can dangerously break your code if you leave it up to the machine.
  • Don’t use “with” statements in order to avoid confusion on how “with” loops work slightly differently than others.
  • Always use triple equals

Not using some of these smart best practices is the equivalent of pointing a gun at your foot and saying “Watch this, I almost never miss!” You might miss, but you might not and the more times you do it, eventually you don’t miss. That would be a tad uncomfortable.

If a feature is sometimes useful and sometimes dangerous, and if there is a better option, then always use the better option.

History Lessons

I am a big fan of history, so I really enjoyed the historical sections of this course. In the course, Crockford discussed the history of JavaScript, the history of HTML and even browsers and the internet. I feel like we can better understand the current situation of the web if we understand where it came from. In always keeping up and being focused on the most modern and latest updates, it’s easy to lose sight of where it all came from. It’s easy to curse those days since today we are still living with legacy issues. Anyone that’s been in the industry for a while can easily remember the frustrations involved with table based layouts and also the collective salvation we found in jQuery. In learning the history, though, I was constantly reminded that those involved were doing the best they could with the limited information, time and resources they had.

The web standards were grown from a naïve hypertext system under intense, highly unstable competitive pressure.

History lesson of JavaScript

Brendan Ike was tasked with creating a script language for Netscape and wrote the prototype in just 10 days! Talk about a tight deadline! Javascript was greatly inspired by hypercard from Apple. He also pulled in features from other languages: he used the inherited syntax from Java, brought in functions from Scheme, removed classes from Self/Smalltalk. It was first called Mocha, then Livescript and was built into the Netscape Navigator 2 browser. Soon after, Sun and Netscape teamed up to beat the giant Microsoft. Sun backed Java and wanted to replace JS with Java in the browsers. Netscape was supposed to remove LiveScript, but they forced it being kept to load the Java, slyly making it required rather than getting rid of it. This is why it started being called JavaScript – since it’s purpose was loading Java. Javascript was thought of and called Java’s stupid little brother.. but with hindsight, now we all know how well Java applets did.
In order to stay relevant, Microsoft created their own browser. To compete, they reverse engineered JavaScript for IE – along with all it’s odd behaviors and bugs. They called it Jscript, so as not to use the name of a competitor, which was a good call, since Sun went on to sue anyone who used the word Java, including coffee shops and even whole islands.

In the meantime, Netscape went to W3C to standardize the language but were actually denied because W3C was not interested. Eventually, they ended up at the European Computers Manufacturing Association (or ECMA), which is a long way to go for a California software company. They created a committee at ECMA and then Microsoft ended up joining and dominated said committee. They insisted that all the bugs and defects remain in the standard to keep backwards compatibility, and since they already had all the bugs documented, it was agreed. The sticky part was that the committee couldn’t agree on a name (JScript, Javascript and LiveScript), so they published the standard as ECMAScript. Which explains why we call it ES6 (etc) today.

JavaScript as a language is what we call it, but officially it’s ECMAScript. The standardization came about in 1997 and updated to ES3 in 1999. ES4 was abandoned due to political differences concerning the language and, so eventually in 2009, ES5 was released a full 10 years after ES3. Then, 6 years later, ES6 became official in 2015.

There are certainly bad parts in JavaScript These bad parts come from a combination of the haste in which it was first created and good intentions of the creators (trying to make the language easy – especially for beginners), and this complex legacy codebase to keep backwards compatible. The proof of concept, when created so quickly, was not intended to be so widespread, but has now become the most used programming language in the world!

History of HTML

HTML also has a long meandering history. There was a markup language used for print called Runoff. This led to another called ROFF. To standardize a few things they came up with Generalized Markup Language. Then Standard Generalized Markup Language (SGML) brought angled brackets and attributes from another markup called Scribe. Hypertext Markup Language was also influenced by apple’s hypercard. XML then came in to make a claim to standardizing the markup.

Example markup from GML showing similarities to HTML

It’s very interesting to me to look at this example of GML and see how clearly it influenced HTML. I feel like a digital archeologist looking through old code to better understand current code.

Fun Fun Functions

There is an entertaining and educational part of the course where we are provided with a synopsis of a fairly simple function, given time to write our own, and then discuss the “best” solutions. It ended up being nearly 50 exercises and accompanying functions. They tended to build on each other as well, so it was a nice programming challenge and throughout I learned a good deal and through discussing them began to see the simplicity and even genius of functional programming even more. Below is a gist I created showcasing the functions I tried to write the requirements for each function in the comments. The function exercises I most enjoyed were the recursion and curry functions but they also touch on higher order functions, closure, generators, factories and factory factories.

https://gist.github.com/circlecube/3ead7d1a46f57842a8b7276698eb3ca4

A quick dive into scope and closures

The course had a nice section that was a helpful framing for closures. Which is a fairly complex and misunderstood concept in JavaScript that stumps many hopeful applicants interviewing for a web engineering role. To get to closures we first needed to look at function scope.

Diagram showing example function scope with nested functions.

When a variable is defined in a function it is scoped to that function and can be used within. For example below, the variable a can be used within the green and the yellow functions. The variable b can only be used in yellow. The a variable will stick around in memory as long as there is a function with a reference to it.

Diagram displaying closure with a private variable being enclosed in a returned function as a private variable.

If we return the inner function then the a value will be encapsulated in the scope, this is what we call a closure. The yellow function can be used and will have access to the a variable, even though it isn’t defined in the function. This is called a JavaScript closure. It makes it possible for a function to have “private” variables.

Web Security

The course pressed the point that “There is no security in obscurity” and that “Security must be factored into every decision”. In fact, having a false security is worse than no security at all, because it puts us at ease. We tend to have a false way of thinking when we say things like “We’ll make it secure later”. In reality if we understand JavaScript, we can use it to enhance our security, since it should be built in rather than tacked on last.

It is not unusual for the purpose or use or scope of software to change of its life. Rarely are the security properties of software systems reexamined in the context of new or evolving missions. This lease to insecure systems.

Many principles of security come from cryptology and ciphers. Auguste Kerckhoffs, author of a military cryptology book in the 19th century, states that a cryptosystem should be secure even if everything about the system, except the key, is public knowledge. Today we still follow this principle.

Kerckhoffs Principle: The design of a system should not require secrecy; and compromise of the system should not inconvenience the correspondence.

The web does get an important security issue right that much other software does not. It doesn’t blame the victims. In other platforms we see a lot of “blame the victim” security models. It’s where we’ll ask the user a question that the user cannot possibly understand or answer correctly. And then when things go wrong it’s the user’s fault for having agreed to this. That’s not a security model, that’s just…stupid! It’s similar to signing every right to privacy away in a legal document before using a product. The browser doesn’t do that (by default). Now the price of that is that the browser is limited in some ways. It’s up to us, the builders of the web, to be smart about how we reduce those limitations in responsible and secure ways. For the sake of security, we must think “Whose interest does the program/website represent?” The user, the site owners, the third-party ads?

We need to alter the way we understand security. We need to better understand the mechanics of the JavaScript language because the most dangerous flaws are the ones we see as a result of misconceptions in how the language works. Our mental model may not reflect what actually happens in the language. Douglas then leads the course through a couple interesting security discussions where attendees work to understand and find security loopholes.

Conclusion

Programmers are as emotional and irrational as normal people.

In the end, we as engineers are emotionally connected to our code and as irrational as any other human. We like to think we are smarter than average, but really we’re all human. We should use things like JSLint (or the 10up eslint code styles) to help us write better and more secure, cleaner code.

I found the course entertaining, educational. It helped me understand the ecosystem of the web by seeing a little more clearly the history of the technologies. The top points of the course for me were the history lessons and the function exercises. I recommend taking this course if this subject matter sounds interesting to you, be aware though that Douglas is as opinionated as JSLint and at times projects a smarter-than-thou attitude which some may find off-putting.

Have you taken the course? Read his book? What were your highlights?

WordPress Core Contributor and my WordPress Story

As I updated a WordPress site today (the new 5.0 version just shipped) I was proud to see my name in the list of core contributors! I’m listed as a core contributor in versions 4.9 as well as 5.0! I didn’t get around to sharing the news last year, but seeing my name in the credits as I upgraded today I realized I should share my WordPress story.

My name in lights ^

My WordPress Story

I share because as an aspiring developer over a decade ago, I fell into WordPress quite accidentally. I was studying in art school at the University of Georgia and creating my own interdiscipline degree with art, technology and animation. I happened to sign up for a Web design for Artists course to create a portfolio site because I was friends with the teacher. We learned flash and stepped into WordPress for blogging. I learned some coding from flash as well as the basics of HTML and CSS to customize the look of my kubric2 blog. The more I learned about coding online, the more I just ate it up!

I loved the immediacy of it all, in contrast to the long time required in my animation classes. For animation you must develop the story, the characters, do the modeling, and rigging and textures and lighting and keyframes etc etc etc, and then you have to let the computer render the animation to see the final. One of my final animation projects for a full semester project was literally half a minute long and it was a rendered movie file that I couldn’t even email because it was so large! It was a motion capture video and was still rather jumpy, but was pretty exciting stuff at the time.

In contrast, in my website class, my final project was viewable anywhere in the world and I could change the look on the fly. I even uploaded my animation so that others could view it online. I was excited for the new world of the internet! It was also interactive! You can do more than just watch it, you actually engage with it and touch (click) it and explore it. Though it can have some movement like animation, it’s a more simple type of movement.

Under pressure to support my pregnant wife, I found a job as a web designer and learned more about javascript and php on the clock. I’m happy that years later, I’m still using WordPress to build sites and grow my skills. WordPress has helped me make sense of web development and grow my career to support a growing family. I’m still extremely grateful and even fascinated by the open source community surrounding the software. I’m humbled to be included in the names of contributors. If I can do it, so can you. Keep working at it and chase your dreams.

My (small) Contributions

Last year, for 4.9, I was able to fix a bug I found in the media library where clicking on the edge of an image failed to select it. It was minor, but I found it annoying, so I created a ticket and after tinkering a while on it figured out how to submit a patch. I discussed the patch with some others and at WordCamp spoke with a committer who pushed it through!

I got involved with the early development with Gutenberg (the new block editor) on github. I figured out how to submit the pull request via github and participated in the wordpress slack discussions. That was a long time ago, but finally with the release of 5.0 Gutenberg is now included. That is until I got too busy to continue and then when I was about to pick it back up, I changed jobs. I know they have been small contributions, but I’m proud nonetheless. I have a goal to continue my contributions and perhaps even up the amount of code I’m able to share.  I feel like I’ve come a long way since those early years, as well as WordPress has come a long way.

My github handle in lights ^

Speaker at WordCamp Birmingham – More WP REST API

I am excited to be a speaker at WordCamp Birmingham 2016. I’ll be speaking on October 29th – just a couple weeks away and now that they have announced the #wcbhm schedule I’m announcing my participation as well. I’ll be opening up the developer track for the day at 10am. I will be presenting more about the WP REST API. A lot will be taken from my WordCamp Raleigh presentation on the same subject, but as usually happens, once you do present, you realize a few holes in your slides and have some additions, suffice it to say, this won’t just be a repeat presentation.

wordcamp-birmingham-badge-speaking

WP API, What is it Good For? Absolutely Everything!

I am very excited about the WP API and am tracking it’s progress closely. There are big discussions as to when it will be rolled into core and all and we’ll discuss these details in the presentation, we’ll also discuss things we can do with the API. It allows us to further separate the data from the code. Because WordPress is a great CMS we can use it to manage our data and then via the API access that data to power whatever we like. We’ll touch a handful of examples and explore an iOS app pulling all it’s data and assets from a WordPress site via this API. We’ll discuss authentication and terms to bring API beginners up to speed on what it’s all about!

So if you’re anywhere close, I encourage you to go get yourself a ticket (just $20) to WordCamp Birmingham and check it out. There will be many other presentations worth checking out as well. I hope to see some familiar faces in Birmingham!

Add Shortcode with Add Media Button

This code snippet really helped me today and since the post doesn’t have commenting enabled, I wanted to say thanks here! Working on building a WordPress plugin that generates shortcodes and wanted an interface for the user to create their own with a wizard of sorts, so using a media button, shortcode and thickbox all together wasn’t very documented anywhere that I could find until I came across this one and I was happy to be able to lift what I needed from this snippet and see my code working like a charm now. The plugin I’m working on is for the Greenhouse Recruiting site and pulls in a job board onto your site via their API. The shortcode wizard will be included in a release soon so you can see it in action.

add shortcode to a page or post without remembering the shortcode itself… choose the shortcode parameters and then have it automatically place itself in the editor

via Add Shortcode with Add Media Button.

Packery Preview, from Metafizzy & descended from Masonry

David Desandro / metafizzy, maker of masonry and isotope of which I’m a big fan and user of has been busy with a new project called Packery.

Packery, looks to be a child of Masonry. As you would expect it seems to be pushing things much further and addressing a few pain points of masonry. He’s boasting in this blog post that it will optionally support grid layouts, and give you the option to go grid-less for a more haphazard looking layout. It will allow filling holes and adding elements on the fly, but most impressively… We’ll have drag and drop support (including touch support and multitouch support)! You drag an item around the grid (or non grid) and watch live as elements reposition to embrace the newly placed item! Very cool and I can’t wait to play with it.

Read up on the Packery preview from Desandro on his Metafizzy Blog.

Working out a Math Problem | BIT-101

I love how math creeps into design, programming and other problem solving.

I had some fun playing with Keith’s code (as usual). I’m always impressed with how he’ll see a problem and eventually at least figure out how to solve it using math/trig/physics. It’s a breath of fresh air and it almost makes me wish I was a math teacher and I could whip the example out whenever a student says ‘how is math useful’. I use it and even enjoy using math in my work to solve problems and it what bits I paid attention to in school still really help me.

Anyways, Keith was trying to figure out how to have a ring of a certain number of exactly touching circles around one central circle of a predetermined size. Sounds like a perfect bonus question from trig, right?
Here’s his post: Working out a Math Problem | BIT-101. And then his follow-up post where he gets to what I was expecting in some nice renderings showing how he’s using this simple pattern to make some really interesting designs.

I commented that I liked his problem solving procedure and was interested to see it animated! I love how math creeps into design like this. So I toyed a bit with animating the form. Check out my jsbin at http://jsbin.com/icahul/132/edit.

Exploring the Javascript requestAnimationFrame API

Here's a great overview and explanation of the new-ish requestAnimationFrame API for javascript. This makes the animations happen in sync and controlled by the browser. This is something that will really help javascript come up to par with animations we are used to and use hardware acceleration. Although it still requires vendor prefixes for all browsers there is a polyfill available to make it happen. I want to see some more demos, (the one linked here in jsfiddle –http://jsfiddle.net/wMkJg/ is more jumpy than my first flash animation 7 years ago).

Embedded Link

requestAnimationFrame — The secret to silky smooth JavaScript animation
Do you often find yourself lying awake at night wondering how you, too, can get your JavaScript animations to be as smooth as those silk sheets of yours? I can’t say for certain that all of us on the CreativeJS team actually have silk sheets, but we did want to show you how to make your animations rock, so we created a page over in our Resources section dedicated to the new(ish) requestAnimationFrame API. Go take a look!

LESS and syntax highlighting for Pea.rs

Pears is an open source WordPress theme by Dan Cederholm (simplebits), enabling people like us to get your own pattern library up and running quickly. Collect, test, and experiment with interface pattern pairings of CSS & HTML.

I’ve customized pears. I’ve forked it, adding support for coding in LESS as well as code highlighting! The LESS auto compiles to CSS and then is applied to the HTML content.

  1. Grab the original or fork at Github.
  2. Install the theme.
  3. Create markup & style patterns.
  4. Learn.

Check out my own pattern library (at http://pears.circlecube.com/) to see it in action!

or visit the original.

Link: HTML5 multiply filter with canvas | Alberto Gasparin

Here’s a great little script I found useful today as I was working on having dynamic effects applied to javascript via canvas.

“The canvas element provides scripts with a resolution-dependent bitmap canvas, which can be used for rendering graphs, game graphics, or other visual images on the fly.”

Thanks to the canvas APIs I was able to get the color values of each pixel of the image and transform them applying the multiply formula, which simply is:

MultiplyColor = [255, 105, 0];
function multiply(topValue, bottomValue){
return topValue * bottomValue / 255;
}

via HTML5 multiply filter with canvas via Alberto Gasparin.