The MEAN Stack – A New Direction for Crooked Code!

It’s been about 8 months since I began the Crooked Code blog…  And so far it’s been a great experience!

While the overall purpose for writing the Crooked Code blog has been, and will continue to be, helping others learn to code, most of the posts fall under one of two major themes…

The first of these themes has been articles covering Algorithm Scripting Challenges in the Free Code Camp curriculum. Two of the most popular of these posts, based on pageviews, have been Symmetric Difference and Map the Debris.

The second major theme has been tutorials on JavaScript, including the Rubber Ducking Series I started a couple months ago based on (but not affiliated with) ‘You Don’t Know JS’.

Where to go from here??
Where to go from here??

While I plan to continue adding JavaScript tutorials, particularly the Rubber Ducking Series, I’m planning on putting a temporary hold on new posts covering Free Code Camp algorithms.

As you may have heard, Free Code Camp has announced they are adding a major expansion to their curriculum. A look at the current map of the beta version shows that many of the advanced algorithms will be supplemental to the main program.

Because of this, I’ve decided to wait until the beta is released into production before I continue writing up more algorithm challenges, as I have no way of knowing which challenges will make the final cut.

I am, however, very excited to announce that I’ve decided to add a third major theme here at Crooked Code – Angular 2 (ng2) and the MEAN stack.

Angular 2

I’m doing this for several reasons…

First, about 90% of my focus lately has been on learning Angular 2.  It’s the first JS framework I’ve learned, so the process has been a long one, and judging by many of the comments I’ve seen throughout the FCC community, I’m not the only one on this journey.  Which brings me to my second reason…

The final release of ng2 is so recent, many of the tutorials and videos out there are a mix of earlier release candidates and the final release all mashed together…

This causes some major confusion in building a working ng2 app, particularly in how to structure the project.  So I hope to shed some light on what I’ve found and save others some of the time I’ve spent (and continue to spend) making sense of it all.

MongoDB, express, Angular2 and NodeJS
MongoDB, express, Angular 2 and NodeJS

Further, I plan to highlight how the ng2 frontend framework ties into the rest of the MEAN stack.

Now that I’ve spent some time digging into Angular 2 on a deeper level, I’m planning on using my previous experience with Node, Express and MongoDB (with Mongoose) to build larger full stack apps.  I think this will be a great opportunity to share what I’m learning with the Crooked Code community.

That’s all for now,

-Jeremy

 

 

For Loops vs. forEach()

I recently wrote a post here at Crooked Code discussing that, as a relative beginner to JavaScript, I’ve had a tendency to use loops exclusively when traversing an array.

Further, I wondered if it would be better if I were taking advantage of the methods built into the array prototype. Methods such as forEach(), reduce(), map() and filter().

Let’s take a look…

For reference, MDN is a great resource to learn more about arrays and the array prototype.  They cover forEach() in far greater detail than I will here, so I encourage you to go read it.

How do you use forEach()?

Simply put, forEach() takes a callback function as an argument and executes that function on each element of the calling array.

The callback function takes 3 arguments – the element value, the element index and the array being traversed.  Instances where the index and array are not needed in the callback function, you’ll see it invoked with only the element value.

A simple example of forEach():

 

When should I use forEach vs. a for loop?

Researching the differences between a for loop and forEach() to write this post has been somewhat enlightening (there are some very opinionated people out there).

First, if you need to stop or break out of the loop before every element is visited, forEach() is not the right function.  In such cases, use a for loop, or look into using every() or some().

Other than that, it seems to come down to performance vs. readability.

Improved Readability with forEach()

Let’s revisit the example above and compare the same functionality using a for loop.

I’ll let you be the judge as to which one is more readable…

Personally, I think the more you use forEach(), the more you’ll prefer it to a for loop for readability.  Clearly, not using additional variables or worrying about ‘off by one errors’ is an added benefit too.

It’s also worth mentioning that ES6 syntax, with the arrow function, improves the readability even further.  I’m still writing my functions the archaic way, which is what I did above, but the same function written in ES6 would look something like this:

Performance

I used jsperf to run performance tests to compare for loops, while loops and forEach().  The tests were run in the Chrome browser.

The for and while loops were the clear winners (6,233 and 6,261 Ops/sec respectively).  forEach() was 18% slower at 5,202 Ops/sec.

So, on a sheer performance basis, the loops were faster than the function call to forEach().  I was a little surprised, however, that forEach() was only 18% slower than the loops.

Bottom Line…

I think you could argue either way of which one, the for loop or forEach(), is better.  Ultimately, I think it depends on the use case…

If you’re developing something that is very data intensive, and the extra performance of the for loop will make a difference, go with the for loop.

Otherwise, if you find forEach() to be more readable and aren’t iterating over huge data sets, use forEach()…

Either way, get out there and build something cool…  That’s it for now, see you next time.

-Jeremy

Side Note

Finally, I need to mention that the forEach() method takes an optional second argument that provides the value to use as this when executing the callback.

Covering this in depth was beyond the scope of this blog post, but You Don’t Know JavaScript: this & Object Prototypes Ch. 2 has an excellent, easy to understand example of using the this argument.

When all you have is a hammer, everything looks like a nail…

I recently posted about an overly elaborate solution that I wrote to a CodeWars algorithm. That post has been lurking in the back of my head since I wrote it…

I’ve come to realize that I can’t be too hard on myself for coming up with the solution that I did.  After all, the only tool I had available to me was a hammer, so I treated every problem like a nail.

Man Hammering Nail
An image of me writing code

My point is that up until then, any time I had to traverse an array, I had used a for loop rather than any of the methods native to the array prototype.  Setting the conditions of the loop to something like (var i = 0; i < arr.length; i++) allows you to easily access and manipulate any element of the array using arr[i].  So that’s what I did…

While there’s (usually) nothing inherently wrong with that (in fact, it’s how I solved many of the algorithm challenges at Free Code Camp), loops aren’t always the most elegant solution to a problem, especially when you start to consider asynchronous options in your code.  Besides, the point of this journey is to become the strongest developer I can, so let’s explore other options.

While going through the front end program at Free Code Camp, I was exposed to many of the methods in the array prototype, including forEach(), reduce(), map() and filter().  The problem was that those methods required callback functions, of which my understanding was tenuous, so I found it much easier at the time to use loops.

Working with Node.js these past few months has given me much more exposure using callback functions, so I’d like to revisit these methods and solidify my understanding of them.  That way, when I encounter problems in the future, I’ll have more than one tool at my disposal.

Over the next couple weeks, I will write a post that will cover each of the four array methods mentioned above in detail.  Hopefully, these posts will serve as good resources for others in my position and, at the same time, give me extra practice using each.

I’ll be sure to come back and provide links to the follow up posts once they’re written.

That’s it for now, thanks for reading.

-Jeremy

JavaScript Fatigue, or in my case JavaScript Paralysis…

Since starting FCC in March I’ve made pretty steady progress through the curriculum.  Of course I’d like to be moving faster, but considering all the other commitments in my life, I’m happy with my pace thus far…

That is until the past few weeks…

I was moving right along through the back end program.  Learning Node and Express was going well and I got through the API projects relatively quickly…

Then I moved on to the voting app, the first of the Dynamic Web Application Projects.

I’d previously experienced so-called JavaScript Fatigue, or the overwhelming sense you get at the thought of all the frameworks, libraries and tools associated with JS.

The past few weeks, though, it’s hit me something fierce…

photo by Windell Oskay
photo by Windell Oskay

While thinking about how to approach the voting app I considered using a framework, maybe React or Angular 2.  So I dug a little deeper…

As someone still relatively new to the JS world, comparing React and A2 isn’t exactly easy.  How do I compare JSX vs TypeScript if I haven’t seen either?

Babel and Webpack.  Huh?

Redux?  Flux?  WTF??

Bring on the JavaScript Paralysis…

I’ve spent the past couple weeks paralyzed with indecision and frustration…

Photo by Kenny Loule
Photo by Kenny Loule

When I was thinking about writing this post, I made a quick list of all the JS libraries and frameworks that I could think of.  In about 2 or 3 minutes I came up with 39 of them!!

Off the top of my head!!

39!

I have the scrap of paper to prove it!  No wonder JS fatigue is a real thing.

Moving on….

Look, I’m not going to go on and on here…  There’s been a ton written about JavaScript fatigue lately, most of it far more eloquent than this…

I just wanted to put this out there in case anyone else in the Free Code Camp program was going through the same thing.  Plus, I’m hoping this will serve as a bitch session to get it off my chest so I can move forward.

I’ve decided to say F-it and move on without a framework for the time being.

I plan on building 1 or 2 of the full stack apps without a framework, then decide between moving forward with either React or Angular 2.

At that point, I’m hoping FCC has updated their data viz section and the decision will be a little easier.

That’s it for now…  Get out there and code something cool, I’m certainly going to try.

-Jeremy

 

Embarrassingly Elaborate Solution to a Codewars Algorithm

I’ve been thinking about writing a post like this for a while but have put it off because, frankly, it’s pretty embarrassing…

Today, I saw a post in the Free Code Camp Forums that made it clear, however, that I’m not the only one that goes through this.  So hopefully this post will encourage other beginners to keep going, even if their code looks terrible in their own eyes…

The purpose of this post won’t be to walk through the algorithms and explain everything that’s going on, but rather to emphasize how different two answers to the same problem can be.

Codewars

Codewars, as I’ve mentioned in previous posts, is a great way to practice solving algorithm challenges.  It can be pretty humbling at times, though, because after you solve the problem, you have the opportunity to look at other people’s solutions.

So, when you solve what you thought was a difficult challenge, only to see that others have solved it in one or two lines of code, it makes you wonder if you’re writing in the same language.  When you realize you are, you wonder further if this coding thing is really for you…

The upside to this, and, in my opinion, the real strength of Codewars, is that you can learn from these solutions…  I’ve only done a handful of algorithms on this site so far, but I’m going to show my first and last solutions as examples of how things can improve.

My First Codewars Solution

The first algorithm I solved at Codewars was called ‘Decode the Morse code’.  Try not to laugh….

The site’s description of the algorithm is as follows:

So, in thinking about the solution to this algorithm, I immediately pictured various ‘for’ loops to split the Morse code into words, then letters.  Then I could replace the Morse letters for real letters and reassemble the message using more ‘for’ loops.

Here is what I came up with…

I was feeling pretty good about myself (it worked after all!) until I saw some of the top rated solutions…

Here are a couple:

Pretty big difference, huh?  These 3 solutions, put together end to end, took fewer lines than my 1 solution did…

I want to make a couple points about this…

My Latest Codewars Solution

First, if you use these solutions to learn from, you can get more clever with your own solutions, and in the end, make yourself a better programmer.

Here’s an example of an algorithm I submitted a couple days ago.

Algorithm details:

My solution:

Most of the top solutions were variations of this:

Ok, so was this last attempt better??  Sure…  Still room for improvement? You betcha…

Looking through past examples definitely helped me put together a more concise solution for this problem, but I still have a lot to learn…

For instance, looking at the answers to this algorithm reminded me that the array.filter() method doesn’t change the array on which it is called. So, once I filtered the non-zero values into a new array, I still had the original array to work with.  I could have used it again to add the zeros to the end of the new array.

Hopefully, next time I come across a problem like this I’ll remember the more elegant solution.

In my experience, learning a new skill, especially one as difficult as programming, is all about repetition and practice.  So I encourage you (and myself too) to use sites like Codewars to practice these skills over and over.

I also encourage you to take the time to look through other people’s solutions and learn from them.  It’ll probably help with your approach to your next one.

It ain’t necessarily about having the shortest solution…

The second point I want to make is that the shortest solution isn’t necessarily the best solution.

We can argue that ‘for’ loops are actually faster than native functions like array.filter() and array.map(), and they are, but that argument is mostly semantic.  Unless you are writing an application that demands extremely high performance, it is unlikely that the user will see a difference between the two.

I believe, therefore, that prioritization should be placed on the readability of the code you write.

Going through the process of teaching myself how to code, I’ve read many examples of code written by others, and can say for certain that all code is not created equal.

Some code is nicely written and readable…  Other code is like a plate of spaghetti and impossible to decipher.

Let’s go back to the answers to the first algorithm.  My code, while drawn out and overly complicated, is fairly easy to follow.  The last two solutions listed, while being the shortest, are not that easy to read (at least to a newbie like me).

I’d argue that there’s gotta be a happy medium, maybe something like the one written by czyzykowski.  Their solution is logical, modular and very easy to follow.

Feel free to comment below if you disagree, like I said, I’m still new to this, so maybe those last 2 examples are perfectly readable to someone who’s been at this a while.

Bottom Line

I think the takeaway from all this should be – don’t worry if your code looks like a fanewgi wrote it, just keep plugging away…

Read code others have written and keep writing more of your own.  Before you know it, you’ll look back at code you wrote a while ago and realize just how far you’ve come!!

That’s it for now, I hope this helped straighten out the code…

-Jeremy

Getting Feet Wet with Internet of Things (IoT)

As I mentioned in my last post, I’m interested in the ‘Internet of Things’ as a way to use and strengthen the skills I’m learning in the back end program at Free Code Camp.

So last week I ordered the SparkFun Johnny-Five Inventor’s Kit.  Over the weekend, I started playing around with it, and as a bonus, my two boys (ages 9 and 12) helped out!

Keep in mind, the title of this post is ‘Getting Feet Wet…’, so nothing I’ve done so far is earth shattering, but you have to start somewhere, right?

The Kit

The kit included the Tessel 2 board and a ton of peripherals  (LEDs, a breadboard, 2 motors, resistors, an LCD screen, a magnetic door switch, etc, etc).  Here’s a picture of the Tessel 2 board plugged into a micro USB cable.

Tessel 2 Board
Tessel 2 Board

The reason I chose this kit (there are quite a few on the market) is that it came preloaded with Node.js.  I figured this would be the easiest way to get started using full stack JavaScript (Node.js along with Johnny-Five).

Granted, you can download Node to the other boards on the market, but considering I was an IoT virgin, I went with the preloaded option.

It also comes with a great Experiment Guide that takes you through 14 experiments to get started.  The guide also contains links to relevant tutorials so you can learn on a deeper level as you go.

I started by reading a few tutorials like ‘What is a circuit?‘,  ‘Voltage, current, resistance and Ohm’s Law‘ and ‘How to use a breadboard‘ to freshen up my knowledge of circuits and electronics.  The experiment guide turned out to be an awesome resource in helping to get started.

Getting Started with the Tessel 2 Board

The first few pages of the experiment guide explain what a development board is, what it can be used for and describes the particular features of this board.  The Tessel 2, among other things, has 2 USB ports, an Ethernet port and WiFi!

It then takes you through software and hardware installation and setup.

The only software you’ll need is a text editor (I’ve been using Atom to develop my FCC projects, so continued to use it for this), Node.js and a terminal application.  The guide walks you through the installation of each of these if you don’t already have them on your computer.

The hardware setup consisted of connecting the board to your computer via both USB and Wifi.  You also have the chance to name your board if you want, so I named mine Lucy (after my late, great boxer)…

Lucy
Lucy

At that point, you’re ready to get started with experiments!

Not counting the time I took reading the tutorials, it took less than a half hour from the time I opened the box until I was ready to run some experiments.

Time for Experiments!

The first experiment in the guide (and the first one I did with my kids) was getting an LED to blink.  Exciting right?  Yeah, my kids weren’t terribly impressed either…

We started by building the very simple circuit outlined in the experiment guide.

Experiment 1 Circuit
Experiment 1 Circuit from the Sparkfun Experiment Guide

As you can see from the diagram above, using the breadboard to make the connections, we made a circuit from one of the ports in Lucy (our board) to the anode (+) of the LCD, then from the cathode (-) of the LCD, through a resistor, back into the ground port of Lucy.

With the circuit complete, now we had to write the code that will make the circuit do what we want.

The Code…

This is the code the guide provides as a starting point.  If you’re new to Node.js, the experiment guide does a great job of walking you through and explaining the lines of code.

Obviously, this isn’t a complete Node tutorial, as it would take too long and I don’t have the experience (yet) to cover such a big topic, but we can walk through this code to see what it does…

One of the great things about Node is the vast number of modules that are available for use.  A module is basically a block of code that does something for us.  There are modules for node that handle all kinds of things.

As you can see by the top two lines of code above, we included the ‘tessel-io’ and ‘johnny-five’ modules using require() and set the modules equal to variables (Tessel and five respectively).

We can now reference those variables to have full access to the modules functionality.  If you’re new to Node, that may be confusing, but keep reading for examples.

There’s actually quite a bit going on in the next block of code.

By writing ‘new five.Board()‘, we create an instance of a Johnny-Five Board by referencing the Johnny-Five object, Board, using the variable ‘five’ that we created in line 2.

Again, similar to what we did in the first 2 lines, we set the new Board equal to a variable, ‘board’, so we can access and manipulate it later.

io: new Tessel() is telling our program to use the Tessel() object to communicate with our board.  Tessel, if you remember, is the variable we created in line 1 and set equal to require(‘tessel-io’).  So, basically, we are telling our program to use the ‘tessel-io’ module to communicate with our board.

Now that we have the modules we need, and have created an instance of our board, we can actually do something with it!

The last block of code creates a listening event for our board.

board.on(‘ready’, callback) tells our program that when the board is ready (done initializing), run the callback function.  In this case, our callback function, which is written in the new ES6 Syntax, () => {} , is contained on the 2nd 2  lines.

Again, we use ‘five’ to access the Johnny-Five module and create a new LED.  We set our new LED equal to a variable, ‘led’.  The ‘a5’ parameter tells our program that our new LED is connected to the A5 pin in our board.

We can then use ‘led’ to access our LED.  led.Blink(500) tells the LED to blink every 500 milliseconds.  Which, it did! (after we loaded and ran the program)

And the crowd goes wild!!

Well…  Maybe not wild, it’s only a blinking LED after all.  But that’s not the point!

We used our new coding skills to do something!  Actually, that might be overstating it too, we copied the code from the experiment guide.  But the point is, we completely understood the code and can now use this to build on.

We ended up running experiment 3 too.  This time we were able to control the LED with a button.  You can check out the circuit and the code in the guide, but here are some pictures of our version.

LED with button circuit
The circuit used to control an LED light with a button using a Tessel 2 board.

The boys were a little more impressed with this experiment, as they could actually control something.

Tessel 2 lighting LED with Button Switch
Tessel 2 lighting LED with Button Switch

All in all, it was a great couple hours spent with my boys, hopefully getting them excited to learn something.  I definitely plan on digging deeper into what this kit can do and hope to use my newfound Node skills to design some more custom projects.

I’ll be sure to write up future adventures in IoT here at Crooked Code.

Please leave comments below if you have any suggestions for interacting with IoT or personal experiences you think might help others.

That’s it for now…  Thanks for reading.

-Jeremy

In the spirit of full disclosure, the two links to the Sparkfun Kit contained in this post are Amazon (which is where I purchased it) Affiliate links, which means I would get a small (very small) percentage of your purchase if you click on the link and buy one…  In the unlikely event that I see any proceeds from this, they will be used to offset part of the expense of running the Crooked Code site.  Thank you.

End of Summer Wrap-Up

It’s been a couple weeks since I’ve had the chance to write a post, as things have been a little crazy around the Crooked Code household…

Football season started for my two boys, they started school this week and my wife went back to work this week!! Hopefully, now things will start to settle down a bit.

Anyway, enough about that, let’s talk about what we’ve accomplished this summer and what we want to accomplish this fall….

What I’ve done this summer…

As I mentioned in a previous post,  I finished the front end certificate at Free Code Camp in July!!

I decided to work on the Back End Program at FCC, then jump back and complete Data Visualization.  Thus far, the back end has been difficult, but enjoyable.

It’s been difficult in that I’ve really had to change gears in my head. Node.js and working on the server side have been completely different than any other coding I’ve done in the past (granted, it’s a fairly limited past as far as coding is concerned).

Diving In…

I started the back end program by working through the Cloud9 modules for Git, Node.js, Express.js and MongoDB.

If I’m being honest, I found these modules to be pretty useless…  I didn’t learn much from them, and half the time I wasn’t even sure what they were asking me to do.

As a beginner, I think it would have been more useful to have a better intro to the languages and better explanations as to what I was trying to do with them.

Instead, I felt like I was trying to satisfy the requirements of some very random modules so I could move on (and getting nothing out of it in return)…

I realize, that’s just my personal opinion and that different people learn by different methods…

Intro to the very helpful Ninja!

Speaking of actually learning, I found a very helpful tutorial series on YouTube called Node JS Tuturial for Beginners by the Net Ninja.  I may have mentioned this guy before and I highly recommend these videos if your starting out learning the back end.

There are quite a few videos in the series, but each one is short and to the point and very easy to understand.  I watched each of the videos and worked along side them in building a ‘To Do’ app in the last 7 or 8 videos.

In addition to a great intro into Node.js, one of the cool tangential things I learned from this series was working with Atom.

The ‘Ninja’ takes you through the steps of setting up Atom, installing Node, npm, etc.  I’ve been working in Atom ever since and find it a much better environment to develop the back end projects than working on Cloud9.

Initial Thoughts on Server Side

At the risk of sounding a little naive and corny, learning how servers work has opened my eyes to the potential you have as a full stack developer.

Let me try to explain what I mean…

I feel like I learned a ton in the Front End program but I always had a nagging in the back of my head like, ‘yeah, these new skills are great, but how do I actually use this to build something bigger than a one page app??’.

Working with Node and Mongo and everything else involved in the back end program (yes, even Git) has calmed that nagging a bit and given me a sense of the bigger picture.

Granted, I’m less than a month into this and have a lot of work ahead of me, but it’s very motivating to start tying things together like this…

Progress Thus Far..

At this point, in addition to the Cloud9 ‘learning’ modules, I’ve completed 3 of the 5 API projects.  Feel free to check out my Timestamp MicroserviceRequest Header Parser Microservice and URL Shortener Microservice.

You can find the code for all these apps on my GitHub page. Please feel free to comment below with any suggestions or questions about my code.

Where we’re heading this fall…

First and foremost, I’ll be working towards completion of the Back End Certificate.  I plan on finishing up the last two API projects then moving right on to the full stack ‘Dynamic Web Application Projects’.

Additional Resources

In addition to the Free Code Camp projects, I’ve continued listening to tech related podcasts.  I mentioned most of the ones I’m listening to in a previous post, but have picked up a few new ones as well.

Two of my favorite new ones are FiveThirtyEight Elections Podcast and IoT Podcast.

The Elections Podcast is by the awesome people at FiveThirtyEight.com where they talk about how they are applying their models in an attempt to predict the outcome of this year’s US presidential elections.  It’s very relevant and very cool…

Internet of things

As I’ve been working through the back end program at FCC, I’ve been trying to think of ways to start applying what I’m learning in the real world.

One idea that I’ve been giving a lot of thought to lately is the internet of things (hence the IoT Podcast).

The internet of things, if you don’t already know, is a broad term that describes all the real word items (refrigerators, cars, wearables, thermostats, etc, etc, etc) that are hooked up to the internet and can be sensed and/or controlled remotely, the so called ‘smart’ items.

Just yesterday I ordered a beginners kit that includes a board and a bunch of sensors and motors so I can start playing around with this stuff.  I’m really excited about it and one of my sons wants to get involved too, which makes it even better!

Johnny-Five!

Considering the FCC program is full stack JavaScript, I’m planning on using the JavaScript framework called Johnny-Five which enables you to run full stack JavaScript, including Node, to control the robotics.  I’ll be sure to include my experiences here at Crooked Code.

A friend of mine, Serg Chernata, just started a blog called ‘Bits & Pieces‘, where he’s going to discuss a bunch of tech related topics, including his experiences with IoT.  In fact, his first post was about setting up a Raspberry Pi as a home server to host his blog.

I’ve included a link to his blog on the sidebar of this site under ‘Recommended Blogs’.  I’ll keep adding to this list as I come across sites that I find interesting and useful.

Once again I’ve written a much longer post than originally planned, which is not easy for someone who says so little in the real world!  Hopefully, if you’re still reading, you got something out of this.

Until next time…

-Jeremy