Jacob Ruiz

View Original

Mastering Javascript Fundamentals: LibrarySystem (Part 3)

Get the fundamentals down and the level of everything you do will rise. - Michael Jordan

Continuing on day 4 of posting my notes on this this blog as I learn to master Javascript fundamentals one day at a time.

As stated in my original post, I do 1 hour of video lessons from Watch and Code every day. If you're interested in learning Javascript in a way that goes beyond basic tutorials and gives you a foundational, practical knowledge without relying on frameworks - I'd highly recommend it. If you're reading these posts, please keep in mind that these are just my notes, and I'm not an expert (yet!). If your goal is also to master the fundamentals of Javascript, please head over to Watch and Code and start your journey there!

All screenshots were annotated using Shotty.


librarySystem (Part 3)

No let's see how Accounting JS handles this.

Looking at line 379:

We can see that Accounting JS is doing something similar to our if/else statement where we check to see if librarySystem is undefined or not.

See this content in the original post

The if statement checks for a library system called CommonJS by checking the typeof a variable called exports.

And then in the else if statement, it's checking to see if there is a different system, called "AMD":

If AMD exists it runs this code:

See this content in the original post

This code is similar to our code. The function that returns the lib object is very similar to:

See this content in the original post

We can ignore the section about lib.noConflict:

Then our last resort is to simply set window.accounting to the library (lib).

This is the same as what we did with sandwichLibrary:

See this content in the original post

It's not important to know the implementation details here:

Those implementation details are dependent on those specific environments. The point is that the Accounting JS author has written the library to work in several different environments -- the same way we wrote our sandwichLibrary to dynamically work in an environment that uses a librarySystem, or one that doesn't have a librarySystem (in which case it simply attaches the library to Window).

Lastly, let's talk about the vocabulary.

We named our system "librarySystem". A lot of JS developers will use the term "modules". Modules is a more general term. "Library" is a term for code that someone else wrote, like Accounting JS. "Modules" is much more broad. It can include libraries that other people wrote, or code that you wrote yourself.

And that's it for today!

Summary:

  • We can see the same if/else logic in Accounting JS that we used in with sandwichLibary.
  • The idea is that it dynamically detects if you are using a given system, and then runs implementation code specific to that system
  • If there is no system, the last resort is to simply attach the library to the Window object.