Five Ways CSS Grid is Better Than Flex-box

1. It’s easier than ever to create two dimensional layouts

The biggest benefit to using grid over flex-box is that grid allows you to style layouts in two dimensions, quickly and easily. Say you want to create a layout like this:

See the Pen 1.1 Layout Model by Float Nine (@floatnine) on CodePen.

You can achieve this with flex-box, but the solution is either hacky and rigid, or requires several flex-boxes working in tandem. Instead, take a look at how it can be laid out in grid:

See the Pen 1.1 Layout Model by Float Nine (@floatnine) on CodePen.

See that grid-template-areas property? Those four short lines determine the layout of the grid. Then the grid-area properties map items to elements. It couldn’t be easier.

2. Easily rearrange the layout of your grid without altering the CSS

Take another look at the layout in the above example. Now look at this:

See the Pen Standard Grid in CSS Grid with Cells Rearranged by Float Nine (@floatnine) on CodePen.

These changes were made without altering the HTML at all. That’s the power of grid. While in flex-box you could rearrange the order of items in a flex container, with grid you can change the size, shape, and location of elements with just a line or two of CSS. Combined with media queries, this is a really powerful feature.

3. Grid’s auto-fit keyword

This was a big pet peeve of mine in flex-box. When a row of items spills into the new row, flex-box leaves uneven white space at the end of the initial row. Resize the red container to see what I mean:

See the Pen Resize Flex No Grow by Float Nine (@floatnine) on CodePen.

You can remedy this with flex-grow, but then you have another problem. The bottom row stretches its items to fill up the empty space:

See the Pen Resize Flex Grow by Float Nine (@floatnine) on CodePen.

With some help from grid’s auto-fit keyword, the items in each row and column work together to create an eye-pleasing, two-dimensional layout:

See the Pen Resize Grid Auto-Fill by Float Nine (@floatnine) on CodePen.

For more information about auto-fit and its partner auto-fill, check out this excellent article on CSS-Tricks.

4. Auto calculate remaining space with the fr unit

One of the most powerful features of grid is the fr unit. Fr stands for fraction. Its power lies in its ability to calculates available height and/or width for you. It takes into account the fixed widths/heights, percentages, as well as the proportional fr values of all the other elements in the row or column. Then it determines how much space is needed to fill the remaining width or height:

See the Pen wXgXYy by Float Nine (@floatnine) on CodePen.

Here we have a first column that is one third the width of the second (1fr vs 3fr), and three rows of varying heights (2fr, 1fr, and 3fr). Frs are responsive, so as the viewport size changes, they will auto-adjust for you. Not only that, but you don’t have to factor in margins and borders like you did when using percentages.

5. Comes with its own functions: repeat and minmax

Remember that auto-fit example from reason 3? Let’s take a look at what’s happening under the hood:

See the Pen Comes with its own functions by Float Nine (@floatnine) on CodePen.

Specifically, look at the grid-template-columns property. In addition to auto-fit, it uses a repeat function and a minmax function. These are currently grid exclusive functions that help us do cool things. In this instance, the repeated items shrink and grow along with the container, but when they hit < 60px in width, they wrap to the next line. The minmax function is equivalent to setting a min-width and max-width for each item. Resize the grid container to see this in action. Grid’s units, keywords, and functions work together flawlessly, and can be mixed and matched in lots of different ways.

Conclusion

So there you have it. Grid is an awesome technology that I recommend you dive into, if you haven’t already. It already has widespread support, and will become more and more popular as time goes on. If you’re looking for an online resource to start learning grid (or fill in your existing knowledge), A Complete Guide to Grid on CSS-Tricks is a great resource. I’m not affiliated with the site, by the way, I just like their work.

And keep in mind, grid is not going to replace flex-box. The two technologies actually complement each other very nicely. And often times flex-box is the best choice for a given task. But for a lot of your layout needs, grid really is the best solution. So my advice is to get familiar with grid at your earliest convenience. Its not only useful, its a lot of fun.

The Ten Best CSS Named Colors

Although a full range of colors have been available in CSS since the early days, most of the named colors we have today are a slightly newer phenomenon. Some of the 124 “non-standard” named colors that rolled out with CSS3 are wacky. Some are just plain inaccurate. But the fact remains, they are still much easier to remember than most Hex and RGB codes. So without further ado, here are the ten best CSS named colors that you should add to your palette today:

10. Dodger Blue

See the Pen ERNZGo by Float Nine (@floatnine) on CodePen.

The name for this color was originally coined by LA Dodger’s team manager and baseball great, Tommy Lasorda.  It was added to the X11 User Interface System by Paul Raveling in 1989, and a few decades later ported over to CSS3 along with the other 124 non-standard colors. Although Dodger Blue can be found throughout Dodger Stadium, the blue on the actual Dodger’s uniform is a little darker: #005A9C.

9. Tomato

See the Pen WyoRPr by Float Nine (@floatnine) on CodePen.

This one kind of speaks for itself. Tomato is a nice, neutral orange-red color, and it actually looks like the thing it’s named after. Soothing and unoffensive as a bowl of soup, it is, also like a bowl of soup, sometimes exactly what you need. Tomato pairs well with lots of other colors too. All great reasons why it is one of the best CSS named colors.

8. Papaya Whip

See the Pen bKBgZd by Float Nine (@floatnine) on CodePen.

Like tomato and Dodger blue, papaya whip was originally part of the X11 User Interface System. It’s not a particularly remarkable color, just a standard looking beige. This one makes the list because it has one of the kookiest names, it’s practical, and most importantly, it’s just plain fun to write.

7. Light Sea Green

See the Pen mKORvg by Float Nine (@floatnine) on CodePen.

Light sea green not only has a great, overly verbose name, it strikes a number of perfect balances. It’s not quite blue and not quite green. Not exactly natural looking, and not too artificial. Not too bright, and not at all dull. There are actually four varieties of sea green amongst the web colors, and light sea green is the only one in the “Cyan Colors” section, making it one of the best CSS named colors.

6. Gold

See the Pen MXbJRm by Float Nine (@floatnine) on CodePen.

Funny thing about the named colors ported over from from X11, the programmers really didn’t include a good amount of well saturated yellows. Light yellow is way too pale, and yellow itself is too bright. So gold makes the list at number 6 in the best CSS named colors, as a serviceable alternative. Hopefully if the W3C ever revises the named colors again, they will add a few more usable yellows.

5. Chartreuse

See the Pen xzRgej by Float Nine (@floatnine) on CodePen.

Chartreuse is named after a popular French liqueur of the same name. The liqueur is more of a pale apple-green color, and the brighter web version was formulated in 1987 as an X11 color. With a hexadecimal code of #99FF00, chartreuse sits on the color spectrum exactly halfway between green and yellow, and is one of the bolder of the best CSS named colors.

4. Indigo

See the Pen YvpNgB by Float Nine (@floatnine) on CodePen.

Indigo is a nice satisfying deep purplish-blue, and makes the list at number four of the best CSS named colors. It is named after indigo dye, but the web color indigo is a little more violet and a little less blue than its natural counterpart. Perfect for when you need a solid purple color, without too much of a red tint.

3. Deep Sky Blue

See the Pen GGNrPa by Float Nine (@floatnine) on CodePen.

Besides having a descriptive name, deep sky blue is one of the more eye catching colors on the named colors palette. A little lighter than Dodger blue, deep sky blue is part of a three member family that includes sky blue and light sky blue. Originally called capri in the “real world,” the name deep sky blue was coined by the X11 programmers in the late 80s, and it’s stuck ever since.

2. Dim Gray

See the Pen Pabjzx by Float Nine (@floatnine) on CodePen.

Every web developer needs a few grays in their palette. Not only does dim gray have a cool name, but it’s a great “darker gray” tone. It’s darker than both gray and dark gray (gray is actually darker than dark gray, thanks to confusion amongst the X11 programmers, but that’s another story). Unlike some of the other “grays” on the named colors list, dim gray is a true gray color, meaning it has equal parts red, green and blue. Perfect for solid gray backgrounds that aren’t too dark or too light.

1. Orange Red

See the Pen vrygbb by Float Nine (@floatnine) on CodePen.

We round off the list with the eye-catching orange red. What can be said about this one, except that it makes the list because it’s just so pleasing to the eye. Bright and saturated, but not obnoxious. A little more red than orange, this one is perfect when you want a solid color that pops and isn’t common or boring. Pairs well with lots of other colors.

So there you have it! Ten great named colors to add to your palette. If there is an overall theme, it’s that these colors strike a balance between eye-catching and practical (except maybe for chartreuse). Incorporate them into your next web project, or just show off your named colors skills to your friends and colleagues. Hopefully too, this article will save you a trip to Google the next time you’re looking for the right web color. Forget hex codes! Named colors to the rescue!

 

How ems Work in CSS – Nailing it Down

Many developers go for years without knowing exactly how ems work in CSS. I blame this partly on the internet. It’s hard to find articles that properly and concisely explain what they are and how they work. As a result, developers often forgo them for pixel or percentage values when setting heights and widths in their CSS. This is a mistake, because ems are a useful tool to have. So if you don’t know exactly what ems are, and how they behave in different scenarios, this article will answer that for you.

Flags with Sky Background

How Ems Work in CSS – A Working Definiton

At the time of writing this article, I googled “How ems work in CSS” and I had to search five results down to this Sitepoint article to get a satisfactory answer. Here is the meat of the definition, as per the article:

“In CSS, an em unit is equal to the computed font-size for the element to which the em is applied.”

Okay, this is a pretty good explanation. It should be pinned to the top of the Google results. We all know what font size is, and this definition makes clear sense. Since a lot of us are visual learners, let’s look at a couple examples to drive the point home. First, take a look at this Codepen:

See the Pen bKErPy by Float Nine (@floatnine) on CodePen.

A couple notes here. We have set the height and width of the body element to 200px and given it a blue border. The .plane div inside of it has a width and height of 50%. As expected, this width and height equals 100px, or 50% of 200px. Now lets change the width and height of the .plane div to ems:

See the Pen MXKEvJ by Float Nine (@floatnine) on CodePen.

What happened? Well, the .plane div now has a height and width of 1em, which is equal to its font size, in pixels. Since we haven’t set a font size for the .plane div, the browser looks for the font size of its parent element, in this case the body element. As you can see in the CSS, we haven’t set a font size for the body element, either. So next, the browser looks for the font size of the html element. Since the html element has no set font size either, the browser essentially gives up. It stops trying to find a developer set font size, and it uses its default font size instead.

In this case, the default browser font size is 16px. So the browser determines that the font size of the .plane div is 16px, and sets the width and height of the div to 1em of 16px (1 x 16px = 16px width and height).

Traversing Up the DOM

The process the browser went through to traverse up the DOM and find the right font size is important to note, as it is a main source of confusion for developers trying to understand how ems work in CSS. Here it is explained in the Sitepoint article:

“When em units are declared on child elements that don’t have a font-size defined, they will inherit their font-size from their parent, or from another ancestor element, possibly going all the way back to the root element on the document.”

In the case of the Codepen above, the browser looks for a developer set font size first in the .plane div, followed by the body element, and finally the html element. In this case, since even the html element doesn’t have a set font size, the browser uses its default font size of 16px. Another way of saying this is that the .plane div inherits a 16px font size.

A Test To Lock it Into Memory

Let’s make one more update to our Codepen to make sure we know exactly how ems work in CSS. We’re going to give the body element an explicit font size:

See the Pen PaZJEM by Float Nine (@floatnine) on CodePen.

I did something here you usually don’t see. I set the font size of the body element to 100px. Too big for most designers’ typographical needs, but it demonstrates my point well. The .plane div now has a width and height equal to 100px, or 1em (1em = 1 x 100px = 100px). As you would expect, the .plane div takes up half the height and half the width of the body element.

So that’s it. An element with a height or width in ems will match the height or width of it’s own font size multiplied by the number of ems specified. If the developer hasn’t set a font size, the browser traverses up the DOM to the element’s parent, grandparent, etc, until it finds a set font size. If the developer hasn’t set a font size for any of these elements either, the browser will use its own default font size, usually 16px. This is the same as saying that the element’s inherited font size is 16px. 1em will equal 16px, 2ems will equal 32px, 3ems will equal 48px, etc. So now you know, once and for all, how ems work in CSS.

Readable Code is Better Than Concise Code

When coding in a competitive environment, programmers often try to outgun each other by writing code that’s as compact as possible. But conciseness is not always a good thing in programming. In fact, readable code is almost always better than concise code.

If anyone knows the name of this artist, leave a comment below and I will attribute them (I couldn’t find them)!

Tell me if you’ve been in this situation before: you write a piece of code to add to your company’s application. You push it up to the shared repository, satisfied that you’ve done a good job. But before the head coder adds it to the application, he or she “revises” it. They reduce the variable names to single letters like “a” and “b,” and replace lines of code with helper functions. When they’re done doing that, they combine lines, and add in hacky tricks to make it all work. All this in the name of saving space and making things concise. What’s left looks technically impressive, but it’s no longer readable code.

From a philosophical standpoint, your code may have been better to begin with. In fact, it probably was.

This can be discouraging. The revised code is unrecognizable, as if your contribution has been written right out of it. The changes feel like a critique of your skills. Often times, from a philosophical standpoint at least, your code may have been better to begin with. In fact, it probably was. You wrote a block of readable code, and after the edits, well, it’s hard to see what it does.

Sometimes More is More

Compact code isn’t necessarily a bad thing, but readable code is better. If your code is too compact, other programmers will have trouble understanding it. Hell, YOU will have trouble understanding it. Say you come back to it after a few months to add a feature or refactor. It may take you a minute just to reacquaint yourself and remember what you did.

Take a look at the following code:

This dictionary in Python contains a first name and a last name that we want to print out in a message. But we don’t know that the “first name” and “last name” keys exist (imagine that we don’t have direct access to the dictionary, or that it’s dynamically created). So we’ll have to check for them before we write the message.

Code That is Too Long

Something like this will work:

Pretty straightforward, right? We check that the keys exist in the dictionary, assigning them to variables if they do. Then we append them to a string, and print the string. This is certainly a block of readable code. Of course, it’s also bait for an edit-happy colleague, because it’s not exactly concise.

Code That is Too Concise

You can make it a lot more concise, like this:

This code does what the previous snippet did in thirteen lines, in only one. Instead of storing anything in variables, we’re printing the message straight out, using ternary (or conditional) operators. Since Python has trouble with two ternary operators on the same line, we’ve put them into a join() function, that uses a single space as a separator (the ‘ ‘ before the .join function name).

But hang on…this is no longer readable code. If you didn’t know what this code did beforehand, it would have taken some effort to parse. It’s not that it’s too hard to deconstruct, given a little time, but consider a hundred lines like this. Things would get tiring quickly.

The Solution: Readable Code

If a line of code appears too compact on first read-through, consider splitting it up a bit. Let’s try rewriting the code one more time, this time making it concise, while still readable:

There we go. We’ve reduced the snippet down to three lines, which is good. But more importantly, it’s still readable code. In some ways, actually, it’s easier to read than the first example. Our two ternary operators are on their own lines, giving them some breathing room. This means that we don’t have to strain to see where they start and stop. Finally, the results are plugged into a print statement, and we can easily see where the variables came from.

If a line of code appears too compact on first read-through, consider splitting it up a bit.

As I’ve hopefully demonstrated here, readable code is always preferable to compact code. You may save some memory and speed up a program by cutting down on lines, but unless you’re programming for embedded systems, or you’ve scaled to global proportions, it won’t matter much. It’s a lot more important to that your code is understandable. So don’t stress yourself out making your code as terse as possible, focus on readable code instead!

Why Few People Ever Master CSS

CSS is a simple technology, right? Not exactly. Many web developers know it well enough to make regular style updates to a website. But to master CSS takes more than practice, it takes an effective strategy.

sunglasses on a rocky beach

Recently I came across this article on Stack Overflow about how to make a div the same height as the browser window. The top answer is mercifully simple – apply the 100vh rule:

See the Pen KRYaVX by Float Nine (@floatnine) on CodePen.

vh stands for viewport height, the height of the drawable region of a browser window. This is a cool trick, but it’s not always what we want to achieve. For example, if the div you are applying 100vh to is inside another div with a defined height, it can throw off the layout. Here’s an example, where the parent div has a green border:

See the Pen JvVEXz by Float Nine (@floatnine) on CodePen.

The overflow of the #inner div makes it appear that something unintended has happened in the layout. So 100vh might not always be ideal. You could use 100% height instead, which will make the div as tall as possible, without exceeding the height of its parent element:

See the Pen LmvxxK by Float Nine (@floatnine) on CodePen.

If you want the parent element to be 100% the height of the viewport, give the parent element and all its parents elements (including the body and html tags) 100% height, too:

See the Pen VxNPbw by Float Nine (@floatnine) on CodePen.

You might be thinking at this point, “That’s starting to get too complicated. What if I can’t make all of a div’s parent elements 100% height? It’s much easier to use the 100vh trick.” I would agree with you. This is a common problem people run into when they try to master CSS. Any given rule seems to only work some of the time. It seems like you’re left with one of two choices:

  1. Memorize one or two techniques for each scenario and limit your HTML markup to always accommodate those techniques.
  2. Don’t worry about the markup, whenever you come across a problem with styling, just noodle around in CSS until you get your desired effect.

Neither one of these strategies is ideal, for obvious reasons. The best answer is that you need to learn multiple ways to achieve any given effect, and know when and why to apply each one. This principle can be applied to thousands of layout issues: centering elements relative to each other, creating “sticky” footers and columns of equal heights, working with background images, and a myriad of everyday issues like lining elements up next to each other and repositioning elements with relative and absolute positioning.

The good news is, you don’t need to be able to list the different techniques off the top of your head, to begin to master CSS. Just try to approach CSS problems with this philosophy in mind. You will be way ahead of the game.

Coding Confidence – aka Ignoring the Hype

The following is a work of fiction, but it’s affects nearly all of us at some point. Hopefully, if you relate to it, you can take the message to heart and increase your coding confidence.

Anxiety Mounts

You’re sitting at your desk, and your team lead comes into the room and makes an announcement:

“Listen up everyone, I just had a team meeting with devops, and we’re switching to Laravel for the next project.”

You hold back a groan. Not only have you never worked with Laravel before, you’re not even that familiar with PHP. As feelings of anxiety start swirling in your chest, another developer chimes in:

“I take it we’re using 5.4.22 then?”

The team lead’s face lights up a little. “Yeah, unless they release a newer version between now and then.”

“Laravel’s a good one,” the developer says, not missing a beat. He picks a foam dart off the table and pitches it through a basketball hoop against the wall. “I’ve been keeping an eye on Laravel since they added model binding in 5.4.”

“Oh yeah, 5.4 was a huge jump forward,” the team lead agrees.

“Blade templating’s a nice touch, too,” the developer says.

“And route prefixing,” the team lead adds.

You start to imagine that you have never learned anything useful about programming in your life, let alone anything you could have an intelligent conversation about.

Coding Confidence Tanks

The team lead’s eyes brush over you and the other developers, and you look away, hoping he doesn’t realize you have no idea what they are talking about. Model binding? Blade templating? Route prefixing? As your anxiety builds, your coding confidence plummets. You start to imagine that you have never learned anything useful about programming in your life, let alone anything you could have an intelligent conversation about. Were you were supposed to be keeping abreast of MVC release logs? Hell, maybe you really aren’t very good at what you do. You can’t help but entertain the notion, as you watch your two teammates return to their seats, that maybe you just aren’t cut out for programming.

Diagnosis & Solution

This is called impostor syndrome, and a lot of programmers suffer from it. Maybe you don’t have a formal degree in computer science, and feel like you just haven’t been trained to think about things from the right perspective. Or maybe you do have a degree, but you have coworkers who skipped college and started programming for large companies right away. Since programming is one of those professions that a lot of hiring managers don’t know how to test for, it would be easy for an impostor to slip through the cracks, right? This is exactly how good programmers lose coding confidence.

These terms that your coworkers used: model binding, blade templating, and route prefixing, they are all pretty simple concepts.

Okay, so what I recommend here is to take a deep breath and let’s try to see the big picture. Part of what is fueling your insecurities can actually bring you some relief, and here’s why: jargon in the programming world is completely out of control. Marketing teams hype up simple concepts in an effort to catch peoples’ attention. These terms that your coworkers used: model binding, blade templating, and route prefixing, they are all pretty simple concepts. Let’s take a look at them, one at a time.

Breaking it Down

Model binding is probably the most complex of the bunch, and all it means is that, when a user enters a URL into your web app, like “profile/user/22”, Laravel automatically looks up the record in the User table with an ID of 22 and gives you, the developer, access to the record. So if you wanted to show the user their email address and phone number when they entered “profile/user/22”, you wouldn’t have to write the code to query the User table for that record. That’s all model binding is.

Blade templating is just a kind of templating system. Blade is one of the most intuitive, straightforward templating systems I have ever worked with. It’s a snap.

Route prefixing is a Laravel feature that lets you forgo beginning of a URL when writing routes. Say you need three routes, “admin/profile/{id}”, “admin/dashboard/main”, and “admin/users/all”. First tell Laravel that the next group of routes will start with the prefix “admin”. Then write them as: “profile/{id}”, “dashboard/main”, and “users/all.” Laravel puts “admin” on the front of each one for you. It’s really simple, isn’t it? Not intimidating at all.

It’s really easy to get intimidated by jargon, but in hindsight, the conversation your coworkers had was pretty basic.

Coding Confidence

Feel better? It’s really easy to get intimidated by jargon, but in hindsight, the conversation your coworkers had was pretty basic. They might as well have been talking about baseball:

“I’m a Yankees fan.”

“Yeah, but what about the Red Sox?”

“Don’t forget the Blue Jays.”

99% of the time, tech talk in offices is much simpler (and boring) than it sounds. Maybe your coworker was just trying to impress the team lead with a barrage of intelligent sounding jargon. Maybe model binding and blade templating really do excite him. Either way, bring the focus back to yourself and don’t worry about him. You’ve got this, and you can build your coding condfidence. You know much more than you think you do.

Five Things (Almost) That You Don’t Need jQuery For

You might be in the habit of using jQuery to perform quick and relatively simple tasks on the front-end of the stack. But especially nowadays, you don’t need jQuery for many everyday web dev tasks. Vanilla Javascript will do the job fine, and with less overhead.

The Problem with Using JQuery

There are a few things you need to do to set up jQuery on a webpage. First, add a script reference to jQuery in the page head. Then make sure that script src points to a CDN or a copy of the jQuery library living on your company’s server. Finally, write the script and test to make sure jQuery has loaded.

Easy, right? But what if the CDN goes down? What if the company server coughs up the script, or, more likely, it clashes with another copy of jQuery somewhere? One of the most stressful parts of web development is unforeseen deployment issues, and you just want to code, right?

Nowadays you don’t need jQuery for a lot of tasks. Javascript does these jobs just fine.

The thing is, nowadays you don’t need jQuery for a lot of tasks. Javascript does these jobs just fine, and with less overhead. Here are five things you can do in Javascript alone, without the help of jQuery:

Selecting an Element

Selecting an element is one of the most fundamental things we use jQuery for. It’s pretty simple. In jQuery:

That dollar sign is called syntatic sugar, and it’s supposed to make reading a language easier. But you really don’t need jQuery to do this. You can just as easily write this expression in Javascript:

Changing CSS Styles

You can directly change the CSS styles of elements with jQuery, right? It’s something you might do like so:

See the Pen aGayEx by Float Nine (@floatnine) on CodePen.

But why use an external library when you can do it with Javascript:

See the Pen vjzJoy by Float Nine (@floatnine) on CodePen.

Adding a Class

jQuery makes this easy! Like this:

Why would you do it any other way? Because you don’t need jQuery to do it. It’s just as easy in Javascript:

 Adding a Click Event

This is one thing that jQuery certainly does better than Javascript, right?

See the Pen pVOWwB by Float Nine (@floatnine) on CodePen.

Again, NO. Why not just do this with Javascript:

See the Pen odPGyw by Float Nine (@floatnine) on CodePen.

Wrapping Your Script in a $(document).ready Function

Okay, surely this is a job for jQuery. The $(document).ready wrapper ensures your code is scoped and gets executed after the page has loaded. For example:

See the Pen ELebaW by Float Nine (@floatnine) on CodePen.

This codepen doesn’t really do anything, but if there were code inside the $(document).ready function, you could be assured that it would execute after all of your HTML elements loaded. That’s a handy feature, as it takes time for your browser to render each element on the page, and if your script is manipulating elements, you want to make sure they’re there. Well, you don’t need jQuery for this either. Not exactly, that is…

Here is one way to try to mimic $(document).ready with simple Javascript:

See the Pen VxGrex by Float Nine (@floatnine) on CodePen.

This will do the trick in most browsers, but not IE8. Increasingly, that’s not a problem anymore, as a lot of companies are phasing out support for anything before IE9, or IE10. If you must support IE8, you can do something like this:

See the Pen aGaVmy by Float Nine (@floatnine) on CodePen.

By putting your script after all HTML elements (other than the closing body and html tag) you are safeguarding against the browser not having loaded the elements the script uses. The generic function wrapper makes sure the script fires without prompt. This isn’t perfect, either, as there are times when a browser renders some objects or elements after the initial page has loaded. But it’s a pretty good alternative, and will work fine most of the time.

But this last example brings up a greater point. We’ve gotten into territory where the solution to the problem has gotten a little complicated. Do we use jQuery here, or do we try to achieve the same with vanilla Javascript? Those kinds of decisions are ultimately up to you, and you should get in the habit of knowing what you do and you don’t need jQuery for. What is important is not that you make flawless decisions every time, but that you know the benefits and drawbacks of the different routes, and stand behind your decisions accordingly.

Streamlining Code (Without Fucking Things Up)

When people talk about streamlining code, usually they are talking about writing code that runs as fast as possible under heavy loads. Google’s search functionality, for example, handles millions of requests daily, so it’s to Google’s advantage to write the leanest, fastest code possible. Even a small bit of code, if written badly enough, could measurably slow down a production that large.

Of course most of the code we write doesn’t handle data at the volume Google does. But even if you’re just looping through a large file, it is useful to streamline your your code. Streamlining also tends to follow best practices, and makes your code easier to read, so doing so builds your skills as a programmer.

Take a simple task like opening a file and reading through its lines, one by one. Let’s say we want to streamline this. We might first look at something like this:

Seems pretty succinct. But without much effort, we can reduce this five line snippet to four, like so:

All we did here was collapsed lines 1 and 2. Moving the string stored in the file variable into the open() function. It’s arguable a little easier to read, and now the machine running it won’t have to store an extra variable in memory, only to retrieve it one line later. Also, the code is arguably just a little easier to read read. We could take things a step further, like this:

Now we’ve collapsed lines 1 and 2 again. That open() function returns a file object, which now, instead of being stored in a variable, is fed directly into the with statement. Okay, so our code is still legible, and we’ve eliminated another unnecessary variable. Can we take it one step further? Well, yeah. This is what we could do:

This works, and produces the same output as the previous snippets. But is it better? No. We’ve lost something here. The with statement has been taken out, and we’re jumping straight to the for loop. The with statement makes sure that the file object created by the open() function gets handled correctly if something goes wrong. It’s essentially like putting the code in a try/finally statement, where finally calls close() on the file object, no matter what happens. It’s the same as writing this:

To put it another way, we reached peak efficiency with out third iteration of streamlines:

It’s at this point that we’d made the code as small and resource light as possible, without losing any of it’s original functionality.

Now, this is not to say that this snippet is necessarily the ideal for any situation. Maybe you want to leave in some of those variables for a reason. Say you’re processing several files with the same snippet, and want to pass in the file names to the same file variable each time. Or maybe you just personally find the use of some extra variables makes your code more legible. That’s fine, and I wouldn’t argue with you at all. The point is to decide what works best for you, while taking into account the load the machine running the code has to deal with, and as a result, how quickly it can complete its job. If you are passing it a file that is only a thousand lines long, maybe reducing the code by a line or two won’t matter. If you’re passing in a thousand files that are a thousand lines long, however, it might be worth your while!