Full Beginner JavaScript Course

This past summer I decided to give back to the developer community by offering a free course on JavaScript.

The students participated in an 8-week course. Until now this course was only available to the students in the course.

Today I have opened the course to everyone

https://codemorsels.wordpress.com/javascript-course/

I hope you enjoy the course and get some good use out of it.

Feel free to comment and let me know if you have any questions, comments or suggestions.

Calculated Attribute on Ruby Model

I was helping someone tackle a problem that required the use of a calculated property. You may not always want or be able to populate your model directly from the database. Sometimes you may to need to aggregate some data and add that to your record. Maybe you can, but more of a hobbyist than a professional Ruby developer, I don’t know how.

I tried many different things but I couldn’t get any of them right. It’s hard to solve a problem in a language that you don’t know very well and even harder when you don’t how the framework behaves. So… my friend put the problem on hold.

The problem was on hold for a whole week and that gave me time to think about it (sub-consciously at least) and I decided to give it another shot this week.

The calculated value was a sum based on the values of a child table (child as in Primary Key to Foreign Key relationship). The problem was that we had to convert the child records into actual sums. The child did not contain actual values that could be added up. Instead, it contains the record type.

Basically if the child record was of a particular type (liked 0 or not liked 1) it held a value of one. If it was the latter it had a value of negative one. The values could then be summed up and given to a property. Basically it’s a scoring system based on likes.

This problem present a couple of sub-problems that must be solved.

First there is the problem with adding a calculated property. We originally did everything right, or so we thought, but then we weren’t seen the new property arrive in the client side javascript application.

At first we thought the problem lay in adding the attribute accessor. So… we added the attribute attr_reader to the property but still no dice. I think it solved part of the problem because whenever you add a property you should provide access (read, write or both).

After digging a little deeper we found out that when RoR sends the data back (we are using render: json in our controller because it’s a web api) it does not include the calculated prop in its serialization.

That’s what happens when you add add a custom prop that is not directly tied to the database. RoR does not have that as part of its serialization.

That meant that we needed to add an override for the method as_json (you can see the code below).

Here is the code with all three problems solved. The code was actually piece-mealed from a couple of different searches, but I figured that I better post it myself if I ever want to find the whole solution in one place again. I don’t actively do Ruby (on Rails or plain), and I’ve not yet become a big enough fan to want to yet…. but you never know one day I might. And if that day ever comes I will look for this!!!!

class MyRecord < ApplicationRecord
   #this provides read access to the property
   attr_reader :points

   has_many :child_record

   #this is the calculated property
   #in this case we needed to map in order to convert for a type to value that we
   #could sum up
   def points
      values = child_records.map loop |childRecord|
         if child_record.type == 0
             1  
         else
             -1
         end
      end
 
      values.sum
   end

   #as_json will add the calculated prop to the client when it's sent as json
   #if you don't do this on your react or whatever client tech, you will not 
   #see the points attribute
   def as_json(options = { })
      # just in case someone says as_json(nil) and bypasses
      # our default...
      super((options || { }).merge({
        :methods => [:points]
     }))
   end

end

I know the solution is readily obvious once you see it, but it took me a lot of trial and error to find it.

Cheers and I hope this helps you out.

Full Stack .Net Developer for 2 Years

I’ve not written a blog post for several months now. I’ve been busy doing other things but the main reason I’ve not written a blog post is because I’ve been trying to keep up with my team at work.

My team is composed of some truly A rated developers. Being the least experienced, in terms of .Net technologies, I am fighting to keep my head above water. I probably shouldn’t say that. Some might argue that I am underselling myself. The reality is that is how it feels in a high-speed no drag team.

As I look back to the past two years, I’ve learned and grown by leaps and bounds. But it certainly doesn’t feel that way when you are fighting your way through the developer jungle everyday.

Here are some of the things that I have learned or grown in over the past two years.

  • .Net Core
  • Deeper Understanding of Nuget and Usage
  • .Net Web API
  • .Net asynchronous programming
  • .Net linq (It’s mature now but keep in mind I was in Java land from 2012-2017)
  • React
  • Redux
  • ELK (Elastic Search and Kibana)
  • Deeper involvement using SQL Server
  • Using Entity Framework
  • Ionic with Angular
  • TypeScript
  • Deeper Use of JavaScript
  • SCSS… we always used plain CSS prior to Joining my current organization
  • Messaging with RabbitMQ
  • Postman (Diving deep into it’s usage)

Here are some other things that I have dabbled in as well for experimental purposes mostly.

  • Amazon Web Services – setting up databases and virtual environments
  • C++ – some tutoring . C++ has changed drastically since my early developer days but students are still using it the old way. It’s still the preferred language for teaching algorithms.
  • C – I’ve given up on C since it’s mostly used only for systems level programming and it’s just not an area that I want to put any energy into
  • Python – I still really like Python for it’s ease of use
  • Algorithms and Data Structures – I’ve learned a lot more about algorithms and data structures. At one point I was convinced that there were a finite number of algorithms and variations. Now, I’m truly convinced that there is an infinite number of algorithms and their variations.
  • React Hooks – I’ve only touched on some things like useState and useEffect with functional components but not deep enough to know how to fully replace redux.

Currently I am preparing to teach a free JavaScript Course. The class will start this Sunday 2-5PM CST. I didn’t do a lot of advertising on social media because it’s mainly for people I know that I want to introduce to programming. Some other students are people I know that are already programmers but don’t know Javascript.

It’s been a truly humbling experience to get back down in the programming trenches for the past two and half years and take it all in. Programming has gotten much more complex. I can only hope that the next two years will be just as good an opportunity to continue growing and learning.

So if you didn’t know why it took me so long to write another blog post, now you know.

If you are interested in taking the JS Course shoot me an email at BeginningProgrammer.om@gmail.com and say “I want to enroll”. I will send you all the information.

Until next time…. hopefully much sooner than 7 months.

The 10X Developer

You may be thinking “Not another 10X Developer post… haven’t we had enough about this idea?”. This concept is pretty old and you are either on the side of “There are 10x Developers” or on the side of “The 10X developer is a myth”.

There are so many arguments against the idea of a 10X developer. Yet… I believe there is such a thing as a 10X developer that can produce much more than the average developer.

First let me tell a story. In 6th grade we had certain activities that we were to complete on a regular basis. One of the assignments was related to completing word definitions. The details of the exact assignment escape me, but I remember that it consisted of taking something like a list of 20 words, write out their definitions and use them in a sentence. The lists were pull as needed. Once you completed one list of words you could pull the next list.

In the class there was this kid let’s call him Bert. Bert would complete 5x as many words as I did and also many times as many words as the average student completed. I think completion only affected our grade minimally.

What we received instead was recognition and probably a star next to our name card on the wall. I always admired Bert and could never figure out how he got so many words completed each week.

Perhaps Bert had a talent for vocabulary. Perhaps he really enjoyed learning new words. Once we got into high school one day Bert just dropped out. I don’t know why that was but I have a feeling that school probably bored him because Bert was extremely smart. Maybe he got burned out who knows. The point of the matter is that Bert could produce 5 to 10x the results of other students.

In this profession I’ve had the opportunity with many different programmers. I’ve had programmers that produce better results than others. Some programmers are better at their craft than others. Some developers produce more than others.

And I know, I know… code lines are not a way to determine productivity. That is because at times a great developer will actually get a negative count by deleting lines of code rather than adding lines of code.

By that same criteria we can’t really consider commit history or number of commits are higher productivity.

One way you can observe productivity and get an educated measure is by counting story points. But… you can’t simply count story points from one member in one team and compare them against another member in another team.

You also can’t use it on a team that isn’t mature in their practices. How do you know when you have a mature team? I’m not certain of the entire set of criteria but I think that a good start is working on a team that passes the Joel Test

What you can do, is compare the number of story points completed by one member compared to the story points of another member in the same team. So if you have a developer in one team consistently producing 2 or 3 or possibly 10 times as many story points, does that make them a 10x developer. Hmm… well… no not exactly.

Another thing to consider is that you must also have solid coding practices and architecture in your team. If you are in a legacy product that is full of spaghetti code, you may have someone producing really bad code really fast. That does not qualify them as a 10x developer.

So how then do you determine a 10x developer? I think that in order to do that first we must define the criteria for a 10x developer.

A great developer, must produce 5x to 10x the number of results as the average developer. Wait… what? “I thought we were talking about 10X developers… why the 5X”. What if your team is already filled with a bunch of 2X developers? I ask.

A 10x developer must also have demonstrated a practical solid understanding of OOP and Design Patterns and algorithms. They must be able to grasp domain knowledge easily and have a lot of experience with architecture. They must understand patterns and also anti-patterns.

They must be craftsman that can identify logic and design fallacies. Let’s face it, a 10X developer likely has a higher than normal IQ. They are likely someone with extremely good memory and problem solving skills.

A 10X developer is a rare anomaly but I believe they exist. Anything above a 2X developer is something to really celebrate in your team. I’ve seen many 4 and 5X developers. Let’s call them nX.

But let’s all keep one thing in mind… an nX developer is only as good as his ability to lift up his team.

We must also not confuse a nX developer with someone that just works a lot of overtime. That could also be bad and he could end up burning out like Bert.

default(T) in C# and why Java does not have something similar

When you use generics ,your classes or functions behave like templates. We don’t call them templates in C#. In C++ we call them templates but in C# and Java we simply call them Generics but let’s face it, they are templates… in the true meaning of templates. I say that because they serve as templates for the compiler. The compiler uses the code for generics to actually compile the strong typed version of the class.

The whole argument of whether they are templates or not is probably something up for academic debate and that’s besides the point in regards to intent of this post.

Recently I was trying to create a data structure that used a doubly linked list. I created the Node internally. The structure required a Node that had an attribute named data of type T. The structure had a removeFront method. The method was similar to a pop or dequeue. It required the method to find the first item and remove it from the list and return its value.

However, since it removes a node from the list what should the return value be when the list is empty. Let’s acknowledge that most data structures such as queues and stacks normally throw an exception when removing from an empty list (e.g. such as in pop or dequeue). However, let’s say that we, instead of throwing an exception, want to return value of type T.

C# happens to have a reserved key word for this; default(T). In that case if the value is a primitive such as an integer it will return 0. If the value is a reference class, it will return null. But… my code was in Java and Java does not have default(T).

public T removeFront(){

   if(size > 0){
      T temp = head.data;
      //do something to remove the node and advance the head
      return temp;
   }
   
   //what do we return here for T
   throw new Exception("Removing from empty list is not allowed");
   //Can't do the following because that's not valid
   //T result;
   //return result;
   //or
   //return T
}

Well, to be honest, I had to look up the answer to this problem. In the process of finding the answer, it made perfect sense. I don’t know why I didn’t see it before. All you have to do is return null. null is and should be the default value to all generics in Java.

Wait… what if it’s a primitive like an int or a double? Well… the reality is that in Java, generics cannot be created against primitives… only reference types. All reference types can be set to null. But what about generics agains int and double. Java has the class version of each of those such as Integer and Double. That means that even in cases where you want to use primitives you have to use the class version of those and then Java uses boxing and unboxing to handle the conversion between the reference type and the primitive type.

public T removeFront(){

   if(size > 0){
      T temp = head.data;
      //do something to remove the node and advance the head
      return temp;
   }
   
   return null;
}

I can’t believe I was stuck on this problem for as long as I was. I was stuck on the idea that the return could be 0, or Null depending on the data type of T. The return will always be valid as null. The solution is so simple but I was so focused on .Net’s solution that I forgot to consider that Java is not .Net and Java does not have the capability of making generics with primitives.

Learning Programming is the Easy Part

Learning programming may or may not be easy. There are many factors that determine that. If you are having fun it may be easy. If you are learning at the right pace it may also be easy. If you have a decent IQ it could also be easy. But… the reality is that it’s hard for most of us. Once we’ve done programming for a year or two it becomes relatively easy.

After tutoring over 200 students, I’ve come to the realization that learning programming can be very hard for some people. Everyone is not wired the same way and some people may just not have as much fun learning as others.

At the same time, seasoned programmers tend to take for granted the journey that got them to their level of mastery. Therefore, it all appears quite easy. One thing I’ve noticed through tutoring is that students are in over their heads many times and what works for one student may not work for the next.

Now that we got that discussion out the way, let’s assume that learning to program is easy. It probably wasn’t easy to learn, but now that we’ve mastered it, it appears that way at least. But… let’s just say it is.

By comparison, creating and maintaining applications is hard.

A significant application with volume is riddled with complexities.

I’m not going to cover each in much detail. I recommend that you google each of these topics, just to get an idea. Here is the list of complexities that you may have deal with on a real applications making working on real applications hard.

  • Authentication – e.g. JWT management
  • Authorization – Role-based permissions
  • Dynamic Menus – All good applications need a good menu system
  • Modularization – many smaller applications. This could be micro-services, subsystems, daemons or windows services
  • Inter-module or inter application communication – at some point application A will need to talk to application B and vice versa
  • Load balancing – Applications have to be scalable and they have to be architected in way that they can be
  • Error logging – Simple as it may sound it requires understanding of a logging framework
  • Performance monitoring and alerting – you need a way to keep track of how your application is behaving. A poor system is hard to search. A good system has quite a learning curve. Think of ELK here.
  • Exception Handling – You can’t just litter exceptions through the entire application. You need something like Polly to break or retry.
  • Endpoint Access – You will need tools like Swagger and Postman for manually testing your end points. Keep in mind that you will also need to consider them being secured.
  • Design Patterns – You will need to know some design patterns to create a solid architecture for your application
  • Dependency Injection – This is detrimental for unit testing. This leads you know have a good understanding of a good framework and what all the different configurations mean. E.G. Ninject, StructureMap
  • Managing Dependencies – This can be a nightmare sometimes. There are package managers but that can be quite a challenge at times. (NPM, Nuget, Ruby Gems, Maven, etc)
  • Use of third party dependencies – There’s third party libraries so that you don’t have to reinvent the wheel but now you must learn how to use the wheel that someone else invented.
  • Data Modeling – This requires you to understand concepts like data normalization and database theory. Also you have to know how to make the OOP language talk to the database.
  • Messaging – Long running processes should run on their own schedule. E.g. Rabbit MQ, JMS, etc. A good example is submitting an order. On a high volume application like Amazon your order goes to a queue and gets processed at a later time. The reason I make this assumption is because I’ve had orders get rejected long after they were submitted. If they were submitted how did they end up rejected. Well…that’s because they were only queued to be processed later. Once they were actually processed the submittal failed.
  • Clean Code – Understanding of concepts like DRY, SOLID, YAGNI, and how to make your code more readable. But this also adds complexity because it may end up creating a lot more little classes throughout the system.
  • Unit Testing on Complex Classes – Mocking, Assembling, Unit Test Framework
  • Working with Async Processes –
  • Job Queues – When you have your system talk with other systems or they have to run long running processes you need to have some time of system that can run jobs.
  • Batch Processing – Similar to Job Queues could be the same.
  • Understanding requirements and acceptance criteria.
  • Complex Business Rules – Sometimes the main complexity is knowing what the requirements are. Others the rules make little sense at all.
  • Understanding the domain you’re working in

There you go…. a big list of things that make application develop extremely hard. Most of your difficult work does not even come in those tough algorithms that your professor gave you. Most of it is just piecing things together and making them work.

JavaScript Truthiness

JavaScript Terms – Part 2

JavaScript is different in many ways than other popular languages, for many reasons. It introduces many different terms as I mentioned in my previous post; Higher-Order Functions. That’s why in this post I am going to introduce two other common JavaScript terms; truthy and falsy.

But First… Introducing the Equality Operator

JavaScript has a boolean data type and the equality operator along with the greater than, less than, less than or equal, and greater than or equal to operators can produce a boolean type during assignment.

These conditions can be used inside the if, else if, for loop, while and do while loops to determine a condition. The condition can also be returned from a function in the form of a conditional boolean statement.

In languages like C#, you must use a boolean condition for those things mentioned above.

//C# and Java
if(a == b){
   //do something
}

In the code above Java and C# will compare a and b and if they are equal and execute the statements inside the body of the if statement. In those languages the condition must always be a boolean. This course is not about Java but it’s worth mentioning that, in Java, if a and b are of the type String then they must use the String.Equals method, nevertheless it is still a boolean condition.

In JavaScript, the condition is not required to be a boolean. The condition can, instead, contain any data type and any value.

When the condition is a boolean, things will behave as expected… sort of. I say sort of because JavaScript has two equality operators the abstract equality operator (‘==’) and the strict equality operator (‘===’).

The difference between the two operators can be seen in the example below.

let a = "5";
let b = 5;

console.log(a == b); //prints true to the console
console.log(a === b); //prints false to the console

As you can see above, one statement produces true and the other produces false.

This is an important distinction because it may not be what you intended. In order for both statements to evaluate to true both a and b must be of the same data type.

The abstract equality operator “==” does something called coercion to allow the evaluation to be true. It basically changes the right variable’s data type temporarily to the same type as the data type of the variable on the left side of the operator.

That may lead you to believe that you will know what to expect for any given mix of types but that is not quite so simple, as we can see in the example below.

var c = "true"
var d = true

console.log(d == c); //prints false to the console
console.log(c === d); //prints false to the console

You might have expected the first console.log statement to become a boolean type, but that is not the case at all.

Therefore, you should stick to using the strict equality operator most of the time.

Strict and abstract operators for greater than or equal to, less than or equal to, and not equal to (negation… !condition) are also available.

Truthy and Falsy

Like I said in the beginning of this post, JavaScript has different rules for the condition inside the if statement. The condition in the if statement can be any data type’s value. Some values evaluate to true and some evaluate to false. Because these values are not explicitly boolean, we say they are “truthy” or “falsey”.

That means they can be used as conditions inside of the if statement and we can expect certain behavior from them. In other words, we should know which values result in true and which values result in false.

Let’s take a look at a few.

function examineTruthyness(info, val){
  if(val){
    console.log(`${info} \'${val}\' evaluates to true`);
  }
  else
  {
    console.log(`${info} \'${val}\' evaluates to false`);
  }
}

let val;

examineTruthyness("EMPTYSTRING", "");      //false
examineTruthyness("SPACE", " ");           //true
examineTruthyness("EMPTYARRAY",[]);        //true
examineTruthyness("FULLARRAY",[1,2]);      //true
examineTruthyness("TRUESTRING","true");    //true
examineTruthyness("FALSESTRING","false");  //true
examineTruthyness("NULLVALUE",null);       //false
examineTruthyness("UNDEFINEDVALUE",val);   //false
examineTruthyness("ZEROVALUE",0);          //false
examineTruthyness("ZEROSTRING","0");       //true 
examineTruthyness("NONZEROVALUE",1);       //true
examineTruthyness("EMPTYOBJECT", {});      //true

You might have already guessed it but pretty much everything else not mentioned in the above falsy results will result in true.

So… you can use these values inside if statements to execute logic. However, just because they are truthy that does not mean they can be compared to the value true. That is a fact with either abstract equality operator or with the strict quality operator.

if([] == true) //will evaluate to false

As you can see truthy values are not the same as having the value true.

Summary

Beyond the explanations above there is not much to using booleans in JavaScript. They are just like the other languages.

If you find this post helpful please be sure to subscribe to my blog. You can also follow me on twitter @fernandozamoraj or linkedIn https://www.linkedin.com/in/fernandozamoraj/

C# vs. Java

Java has been the dominant language for a long time. The thing that made Java so popular is that it can run anywhere.

At my last job my team maintained a Java application. Because Windows dominates the user desktop in the corporate world, we developed that application in our Windows machines but deployed it to Unix servers (Solaris). We essentially wrote the application once and if it worked in our machines we knew it would work on the Unix servers (except for those pesky works on my machine errors that are common even within the same OS).

That’s the beauty of Java. It runs anywhere or “everywhere” as Oracle likes to promote. If you have ever run the Java’s JDK installation, you may have noticed their advertisement “Java Runs on 3 Billion Devices”.

The reason that Java programs runs on so many devices is because Java runtime can run on any operating system and, by today’s standards, it doesn’t require much space (123MB). That could be a lot for some firmware but it really is not that high of a requirement.

The way Java works is that a program gets compiled to a class or jar files. These files are binary but they are not in and of themselves directly executable. They must be run by the Java Virtual Machine. The JVM, sometimes called the Java Runtime, is a program that knows how to execute the binary files.

From early on Sun (the former owner of Java) wrote the JVM (or several versions of the JVM) to target different platforms. As long as there is a JVM for the host operating system, a Java program can run.

Java got an early start on being able to target multiple operating systems. That was very appealing to software developers because they could target multiple platforms or operating systems. There is a lot of flexibility when a program can run on different operating systems. It provides the developer with more options.

If you know anything about the software development, you know that the software code is a heavy investment and you can’t just port your code over from one language to another, or even adapting it from one OS to another within the same language (C++). Doing so comes at a very high price.

Java programs are written once and run on different operating systems. This also made it possible to target different types of devices. Because Java was a pretty advanced language, it made the coding process much easier and thus faster.

Java was like C++ but debatably easier to code in. Java offered many things that C++ lacked (e.g. automatic garbage collection, elimination of header files, out of the box libraries for just about anything, better security).

Another appeal to Java is that since it can run on anywhere it can run on free operating systems like Linux. It can also take advantage of open source solutions like Apache and Tomcat. This capability meant that organizations could leverage this advantage to lower their operating costs. Running on free operating is cheaper than paying the MS Windows licenses.

Microsoft introduced .Net Framework around 2003. With it, it introduced C# and VB.net. I think VB.net was to lure the many developers that were already developing in VB, since VB.net has a very similar syntax. C# was another C family language (resembled Java quite a bit). For C++ programmers it was an easy transition to C#. The introduction of these two languages made it very easy to bring over the many VB and C++ developers that were prevalent at the time (I don’t think it targeted the Java people yet, well maybe a little with their J# language).

When the .Net framework was first introduced, the big selling point was that it was language independent. You could develop in any language of your choice from C#, VB or COBOL.net as long as the code compiled to the intermediate language (As a disclaimer I don’t know if there ever was a COBOL.net language). This approach meant that you could write some code in one language and other code in a different language (as separate projects creating separate DLLs or Exes) and in the end they both produced a binary that was understood by the CLR. The best part about it is that these binaries could communicate and understand each other.

I think this selling point kind of confused people a bit. Why did we need something that could allow the creating of different languages? But now that I think about it, it was in many ways like Java because the code compiled to an intermediate language. The real reason was that Microsoft had a brand new product and it created a bridge for developers from all languages to make the transition(C, C++, VB, COBOL) into this new .Net thing.

As time went on the .Net framework along with C# got better with each version. Java has gotten somewhat better and has many of the same features but they are usually a version or two or three behind. In my opinion, initially C# stole many ideas from Java, at least the good parts, but then it eventually surpassed it.

C# has many features that make it easier to code in than Java. The languages are very similar but certain things about Java will drive a developer crazy (look up getters and setters compared to properties and also checked exceptions). Also, C# has a history of introducing new features while Java will eventually introduce them some time later. Microsoft also has a way of great marketing to introduce each version.

I found the C# community more involved that the Java community; more blogs, more how to’s, more videos. I developed in C# for many years and then switched to a Java for about 5 years and I found it troubling at how hard it was to find helpful information outside of the official Java documentation. If you’ve ever read the official Java documentation you know that it leaves a lot to be desired.

I think initially Microsoft’s approach was to keep .Net and C# proprietary and their approach was for it to only support their licensing efforts, but they have, in recent years, changed their position by embracing open source and allowing their flagship products to run outside of Microsoft environments.

Microsoft introduced .Net core a couple of years ago and they have made great strides since. .Net core is a version of .Net written from the ground up that runs on most operating systems (Linux, MacOS, Windows). This is a big step from the old .Net that only ran on Microsoft Operating Systems.

Up until today .Net core was great for creating web application and web APIs. However, it did not allow you to develop Windows Forms or WPF applications. Today (September 23, 2019) during the Dot Net Conference, Microsoft announced support for Windows Forms and WPF.

That’s pretty exciting because that means that programmers will be able to create Windows Forms and WPF applications in and for any operating system. If this means what I think it means, Java now has a true competitor.

I say that as if it wasn’t already a competitor, with just the web alone. It has been a competitor, specially since the web is where the majority of applications are. However, by also entering the desktop application space there is little if any gap left unfilled.

To me it seems that soon there will be little difference between what Java is capable of and what C# is capable of, except that C# is a much nicer language than Java in many ways.

I don’t think this means the end of Java but it could be the beginning of the end. At a minimum it could mean a very heavy loss of market share.

After all, Microsoft is a master at creating awesome tools. They are great at pushing their products. They are good at updating their systems. Most of all, they excel at making developers life easier.

What do you think? Will C# take over Java’s Reign?

P.S. I can’t forget to mention that Java is also a multi-language (e.g. Kotlin), so… only time will tell which language dominates the developer world.

Higher-Order Functions

JavaScript Terms Part 1

I think many programmers would agree that learning JavaScript is one of the most challenging tasks compared to learning other languages.

Many terms are, for the most part, unheard of in other languages. Among them are terms like higher order functions, hoisting, truthy, falsey, coercion, currying and closures.

Because these things exist in JavaScript, it can be very confusing to learn JavaScript after learning other languages. Most of the time, to go from one language to another all you have to do is translate your syntax knowledge from language a to language b. But that is far from true with JavaScript.

In addition, JavaScript behaves in different ways than the way most other languages behave in certain scenarios. Some examples of that are the use the key word “this” as well as when comparing values.

Because of these concepts, you can’t just use a syntax cheatsheet to learn JavaScript. In fact, you have to throw away much of what you already know and learn it JavaScript from the ground up. Do not make the mistake that many programmers make and just hack your way around it. You will spend many hours of frustration if you do.

This not only causes confusion for seasoned programmers, but it also makes JS harder to learn as a first language.

I want to write a series on on these topics and today I am going to start with higher order functions.

Functions Are First Class Citizens

You may have heard that functions are first class citizens in JavaScript. In most other languages functions and even methods are not first class citizens. They are just a process that can be invoked. In other languages functions require extra work to handle the scenarios below:

  • store function as a variable
  • pass a function as an argument
  • return a function from a function
  • extend a function with functionality
  • decorate a function or simplify a function
  • declare a function anonymously
  • invoke a function immediately after declaring it

In JavaScript functions are objects. If you remember, in JavaScript you can extend an objects behavior and state by adding attributes and methods.

Because functions are Objects they can be handled just like any other data type instance. You can stored them in variables, pass them to other funcions, return them from functions and even add state and additional functionality.

In this post we will focus on the aspect of storing them in variables and passing them around to other functions. The concepts in this post are essential for understanding the concept of higher-order functions.

Function Stored as a Variable

Let’s start with the most common scenario, to store a function as a variable. You may have seen a function declared anonymously and stored in a variable.

let add = function(a, b){
   return a + b;
}

In the example above we have created a variable named add and assigned a function to it that returns the sum of the parameters a and b.

Later we can invoke the function by its variable name and using parentheses along with parameters to invoke it.

let sum = add(5,10);

Since the function is stored in a variable, we can also pass it to other functions

function outputSum(a, b, mathOperation){
   console.log(mathOperation(a, b);
}

outputSum(5, 10, mathOperation);

The function outputSum above is an example of a higher-order function because it takes a function as a parameter. It then invokes that function to produce the result.

You may be wondering why I named the parameter mathOperation. That is because the output sum may accept other 2 parameter functions such as multiply or divide.

let multiply = function(a, b){
   return a * b;
}

outputSum(5, 10, multiply);

Notice that the outputSum function requires no changes yet it will behave differently depending on the function passed in.

When passing functions as parameters these are sometimes referred to as callbacks. Callbacks are very common in non blocking code. The reason is that the invoked function does not necessarily know what to do with the results and instead provides an opportunity for the caller to define that in the call back.

When Functions Return Other Functions

Sometimes functions return other functions. There are many reasons why a function must return a function instead of a concrete result.

function getPortionCalculator(amount){
   return function(contributors){
      return amount/contributors;
   }
}

let calculate = getPortionCalculator(1000);
let portion = calculate(10);

In the example above the function getPortionCalculator returns another function. That function can then be used to calculate the amount for each contributor. This is another example of a higher-order function because it returns a function.

Don’t concern yourself too much with the real world uses for this type of coding. You will run into them soon enough if once you start coding in JavaScript. You will also need to understand this concept in order learn other more advanced concepts.

Two Ways to Declare a Function

You may have noticed that I declared a function two different ways.

let doSomething = function(){
   //code to do something here
}

In the code above I declare a variable and store a function in it.

In the code below I simply name the function.

function doSomething(){
   //do something here
}

So… which way should you use and when? That is an excellent question. Let’s go back and look at an earlier example.

outputSum(4, 10, function(a, b){
      return a + b;
   }
}

Notice how I declared the function right in the location where I passed variable earlier. Sometimes the definition of the function can be pretty long. It can help to clean up the code by storing the function in a variable and then passing the variable instead of declaring the function inline. It would make the code cleaner.

Another consideration to keep in mind is hoisting. We are not going to talk about hoisting in detail in this post. However, it is important to know that when you declare a function and store it in a variable the function is not available up higher in the code.

That is because even though the hoisting occurs, and the variable exists, the function has not yet been assigned to it. The variable exists but it has a value of undefined.

function doSomething(){
   foo();
}

doSomething();

var foo = function(){
   console.log("foo");
}

The function above will result in an error. The error will indicate that foo is not a function. Notice that it does not say that it is not defined but rather that it is not a function. The reason for that is hoisting. This what the code looks like to the compiler (or JS engine).

var foo;

function doSomething(){
   foo();  //foo is undefined
}

doSomething(); // calls foo before being defined

//foo is defined after do something tried to call it
foo = function(){
   console.log("foo");
}

Take the code example below and you notice it is not much different. However, the function below will run and output “foo” to the console. Hopefully you can tell the difference between the two ways of declaring a function from this example.

function doSomething(){
   foo();
}

doSomething();

function foo(){
   console.log("foo");
}

Summary

JavaScript is different in many ways than most other languages and specially static languages. In this session we covered one small portion of the many terms that complicate JavaScript, higher order functions. Please subscribe so that you can get the notifications when I public the upcoming posts related to JavaScript terms.

Welcome to my new blog!

This is my very first post at my new site

Some of you may be familiar with my previous blog beginningprogrammer.com.

Why a new site?

  • I didn’t plan on creating a new blog and actually I hated losing all my old content but some things happened suddenly and I will explain?
  • The old name had been bothering for some time. At first beginning programmer seemed like a good idea but I felt that it was not really advertising the true core of the site.

As I said, things took a sudden turn. As I was preparing to go on vacation a few weeks ago, I decided to check my personal email. I used that email for so many things that I tend to not check it as much as I should. So… as I was browsing through my updates. I noticed an email from GoDaddy that said “Thank your for your renewal”.

I did not realize that my site with GoDaddy was setup for auto renewal. I should have. After all, that’s normal business with GoDaddy. So… when I signed up my hosting with GoDaddy the price was something like $250 for 3 years for a premium account. I thought it was a great deal back then and it sort of was until later I started noticing that my blog was really slow responding during administration and I believe even during visitation.

When I opened the email and read the renewal amount I had been charged I couldn’t believe it. I had dropped the ball big time. The renewal invoice was for $1250 for three years. Now I don’t know about you and your earnings but for me an unexpected $1250 withdrawal from my account is a lot of money.

I immediately contacted GoDaddy to ask about it. Apparently they had sent me emails days in advance that the renewal was taking place soon. Since I am not constantly in my personal email inbox I missed those emails.

Being that I was in panic mode I told the GoDaddy rep that I wanted to cancel my subscription which they would do. In the process though, I would lose all of my content. They asked me if I would also like to cancel the domain name registration and I said yes because I thought it was part of the package. In retrospect giving up the domain name was a good idea because I think it was not befitting of the brand I want to pursue.

I had backed up my site locally about two weeks prior. However, I only backed up the site and not the MySql database. The database is where all the posts are stored. So… my old content is gone forever. I will miss it because some of that content also serves as a reference for solutions I need from time to time. But oh well, out with the old and in with the new.

Here we are with a new site and whole bunch of ideas for the direction I want to pursue with my fresh new blog.

No bad experience should ever go to waste. There are a few things that I have learned from this experience.

From now on I will make sure that I backup my entire site. By entire site, I mean the static content as well as the database.

Also I will make sure to use something other than PayPal and my bank account for automatic renewals. With PayPal even though I cancelled before the cancellation could go through the payment had to go first. That process can take days and it did. As a result I ended up throwing my checking account out of balance and getting a bunch of unnecessary overdraft and insufficient fund fees. It was not my primary account and as a result it was not prepared to handle that transaction. Even when I tried to pad it, I forgot about one other auto withdrawal and still got hit with ridiculous overdraft and insufficient fund fees.

I will also make sure to be more diligent about scanning my personal email at least daily for anything avoidable surprises.

With that said, thanks for reading my blog and I hope that you will subscribe so that I can entertain with fresh new content periodically.