What I wish I knew when I started using react testing library

I started testing with the react-test-library and ran into a lot of pain. Most of my pain came from the fact that I did not take the time to learn the library first. Thus I had no understanding of how it worked. I tried to make it work from existing examples and from a lot of trial and error but without the understanding, it caused a lot of frustration. I stumbled several times and scraped my knees and elbows along the way.

I then went through portions of a course on Plural sight and got somewhat of a better understanding. But when I went back to try them out on my code I still had trouble making them work. So I had to dig a little more.

Hopefully this post will get you a better understanding and you won’t stumble as much as I did.

First things first, the library is actually called Testing Library. I know! I know! very generic name… but that’s what it is. But wait you may think “I thought it was called ‘react testing libary’?” Well react testing library is a just a react specific API from Testing Library to React code. In the same manner the library provides different APIs such for libraries like reason, native, Vue, Angular and many more.

With that in mind, you must know that there is a Core API portion. The Core API portion has all the core functionality of the API. We can get access to that in our React app by including the React Testing Library.

The Core API

The Core API library is composed of two main concepts; Queries and User Actions. Queries are the API pieces that allow you to query your react DOM. User Actions allow you to fire events to force the component to change its state such as button clicks and changing text on input controls or even doing things like changing focus (i.e. forcing blur events).


Queries on an element are getBy…,queryBy…,findBy…, notice the …. That is because those queries are combined with ByRole, ByLabelText, ByText, ByTestId and so on. For example you could have getByText(‘Click Me’) and it would query the element or component for an element that has the text ‘Click Me’ (notice I said element because it will not restrict it to a button). You can also use regular expressions with getByText, like getByText(/click me/i) which will ignore casing. You can also getByRole(“button”) and that would get an element that has the attribute role=”button”.

The queries can return singular values as in the example above or return multiple values by using the getAll… instead of get and findAll… instead of find, etc. For example getAllByText(‘foo’) would return an array of elements with the text ‘foo’.

The getByText gets the element that has the text in it. For example


would get me this element

<div ...> foo  </div>

Understanding the different types of queries

Another concept to mention regarding the different query types is in how they behave. All of them will throw an error if the results are greater than one. The queryBy is the only one that will not throw an error if the result is less than one. And findBy is the only one that is asynchronous. So… findBy must be combined with await inside of an async function. GetAll and Find can return 1 or more elements. Still have not researched what getAll, findAll and queryAll return when no item is found but be aware when you use it. It may throw an error or return an empty array.

What this means is that you have to know what your going to do with the results of the query. If your intent is get the element because it should exist getBy is fine. On the other hand, if your intent is to make sure the element does not exist you probably need to use queryBy. Since queryBy returns null, you can then check for null for your test. We haven’t discussed how to test yet but we’ll get there.

There is one alternate method to all the api queries and that is the querySelector which is practically a like a regular DOM selector for anything you can think. It is extremely generic an its use should be justified.

The React Testing Library

To use the react testing you should refer to the official API pages but as of this writing I’ll do my best to highlight it’s usage. First you must install it. Second you must import the functions that you would like to use. Some common ones are render, fireEvent, waitFor, and screen.

import {render, fireEvent, 
               waitFor, screen} from '@testing-library/react'
import '@testing-library/jest-dom'

Like most unit testing you can take advantage of the beforeAll, beforeEach, afterEach and afterAll functions for any setup and tear down of your tests.

beforeAll( () => ...dosomething);
beforeEach( ()=> ...);
afterEach( () =>...);
afterAll ( () =>...);

Then you can begin writing tests in the format of

test('renders alert', async () =>{
  const {getByText, getByRole} = render(<MyComponent val1={"..."} />);

  //notice the await and async up top
  await waitFor(() => getByRole('alert'); 

  expect(getByRole('alert')).toHaveTextContent('Oops, somethig failed'); 

Note how the getBytext and getByRole are not imported but rather they are extracted from the object that the render returns. There is also another way to do this using screen. Let’s take a look.

test('renders my component',   async () =>{
  render(<MyComponent val1={"..."} />);

  //notice the await and async up top
  await waitFor(() => screen.getByRole('alert'); 
     .toHaveTextContent('Oops, somethig failed'); 

In this second example notice that I did not extract the get getByText and getbyRole functions out of the renders return. Instead they automatically get set in the screen object that was imported at the top of the file.

One more piece to this and can be very significant is the debug function. Whenever you render a component, you can call the debug function



const {containter} = render(<MyComponent/>);

The debug will spit out the information html to the console screen. this can be very helpful when you need to see what is in your DOM.

There are some advanced features and much more that you can get from the official site but hopefully this will give you a better head start then going directly to the official site.

Well to summarize these are the things that I wish I knew before I got started. There is definitely a lot of ground that I did not cover. You can find it as needed from the APIs documentation. I didn’t even touch all the different types of assertions that you can make but you can find those in the documentation.

Separating C++ Templates Into h and cpp files

C++ is known for separating classes into .h and .cpp files or header and source files respectively. A variety of reasons and motivations justify this approach. Among them are first and foremost the idea that C++ compilers need to know what to expect ahead of time in order to link properly. Another useful idea behind this is that a developer can separate their declaration from their definition and hide the implementation details.

Say for example that you have a super fancy proprietary compression or encryption algorithm, you can hide the implementation details in the .cpp file while still providing the API interface to use this CompressionWidget class.

//CompressionWidget.h class file
class CompressionWidget{

   //... any private variables go here
   void Compress(const char *sourceFilePath, 
                 const char *destinationFilePath);
   void Decompress(const char *sourceFilePath,
                   const char *destinationFilePath); 

//CompressionWidget.cpp source file
void doCompress(const char* sourceFilePath, 
                const char* destinationFilePath){
      //implementation details here

void doDecompress(const char* sourceFilePath, 
                const char* destinationFilePath){
      //implementation details here

void Compress(const char *sourceFilePath, 
                 const char *destinationFilePath){
      //do compress
      doCompresss(sourceFilePath, destinationFilePath);

void Decompress(const char *sourceFilePath, 
                 const char *destinationFilePath){
      //do decompress
      doDecompresss(sourceFilePath, destinationFilePath);

As you can see in the code above you can hide the details in the cpp file. In fact you can hide even more by hiding the helper functions that help you compress. Instead of even hinting at which other dependencies you may have hide a lot in the cpp file.

But what about separating templates?

In C++ you can create template classes. If you are more familiar with a newer language like Java or C# you may know these as generics (similar idea but possibly not exactly the same). The idea is that you create one class that can work with any data type. Let’s say for example you ave a data structure class like a Stack and you want to separate the declaration from the implementation. This can get pretty tricky with templates.

The reason it gets tricky is because a template is not really source code. The source generation occurs when you actually declare the instance of the class.

template <typename T>
class Stack{

    void Push(T item){ ... }
    T Pop(){ ... }
int main(int argc, char *argv){
   //This causes the compiler to compile the Stack for doubles
   Stack<double> stack;   

//This or something like this is what the compiler creates
class StackDouble{

    void Push(double item){...}
    double Pop();


So… if you try to separate the Stack class into separate h and cpp files you will get a series of errors that will have you pulling your hair. In the example above I declared the the Stack class with the member functions inline. You can still separate them but they must be in the same class. You cannot put the implemenation in a C# file.

If you put the implentation in a Stack.cpp file you will run into compiler issues.

The Solution

One way to get around that problem and this is something that I saw a student do before is to put include the .cpp file at the end of the .h file.

template <typename T>
class Stack{

    void Push(T item){ ... }
    T Pop(){ ... }

#include "Stack.cpp"

The approach works and if you are using a light code editor you probably won’t have much problems. However, you will run into problems because a compiler may have issues with this approach because it will try to compile the Stack.cpp file and not find definitions from the .h file. Another problem that you may run into is that when you run the compile command the compiler will try to compile the .cpp file when in fact it should only compile the .h file.

$ g++ *.cpp -o program.exe

Recently I discovered a solution that works quite well. So instead of a .cpp file for your implementation, use a .tpp file.

#ifndef STACK_H
#define STACK_H

template<typename T>
class Stack
    T data[20];
    int topIndex;
    Stack(/* args */);
    void push(T entry);
    T pop();
    T peek();
    T empty();
    T clear();
    int size();

template <typename T>
Stack<T>::Stack(/* args */)
    topIndex = -1;

template<typename T>

#include "Stack.tpp"

#endif // !STACK_H
template <typename T>
void Stack<T>::push(T entry){

  if(topIndex + 1 < 20){
      data[++topIndex] = entry;

template <typename T>
T Stack<T>::pop(){
   if(topIndex >= 0){
       return data[topIndex--];

    //throw exception here
   T t;

   return t;

template <typename T>
T Stack<T>::peek(){

   return data[topIndex]

template <typename T>
T Stack<T>::empty(){
    return topIndex < 0;

template<typename T>
T Stack<T>::clear(){
    topIndex = -1;

template <typename T>
int Stack<T>::size(){
    return topIndex + 1;
#include <iostream>
#include "Stack.h"

using namespace std;

int main(int argc, char *argv[]){

     Stack<double> stackD;
     Stack<int> stackI;


     cout << stackD.pop() << endl;
     cout << stackD.pop() << endl;

     cout << stackI.pop() << endl;
     cout << stackI.pop() << endl;
    return 0;

The solution above allows you to separate declaration from implementation. Does it fully allow you to hide the details? probably not since you will likely need to provide the .tpp file. If you have proprietary code in templates, there is not much you can do about it.

About the only thing you get out of this approach is that you are able to keep your code a bit cleaner. So, likely you would not want to implement proprietary valuable IP code in templates.


The long story short with this exercise is that you are able to separate implementation from declaration for templates. It does not solve the problem of hiding implementation details. The biggest take away is that you have a better understanding of templates and while you do not get the true benefits of separating declaration from definition, you do now know how to properly separate them if you need to. Like anything else, knowledge is power and at least you won’t be pulling your hair like I did when faced with this problem.

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


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

   #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]


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;
   //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){
    console.log(`${info} \'${val}\' evaluates to true`);
    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.


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.