Adventures in Javascript

Category Archives: javascript

When entering a new field, you not only have to learn a new set of skills, but also the industry jargon you might not be familiar with. Before becoming a software engineer, a ‘slug’ to me was a pest in our garden that my siblings and I would pour salt on and/or run away from. Now ‘slugs’, and what it means to ‘slugify’ a string, have taken on a whole new meaning.

Slug

A slug is a part of a website’s url, usually the part at the end that comes from the title of the page or section. On this blog, if you were to click on the “About” section, the url would become https://aimeerosato.com/about-2/. The slug, “about-2”, comes from the fact that it’s about the “About” page. By convention, slugs are usually lowercase, have spaces in a phrase replaced by a dash or underscore, and have punctuation marks removed. Sometimes smaller words are dropped or changed to make the slug more readable. For example, with the article entitled “The U.S. is still using floppy disks to run its nuclear program” from cnn.com, http://www.cnn.com/2016/05/26/us/pentagon-floppy-disks-nuclear/index.html, you can see the slug for that article became “pentagon-floppy-disks-nuclear.” Interesting article by the way – I remember those huge floppy disks!

Tools to Slugify

When you are writing a program, you might find the need to turn a string into a slug, i.e. to slugify it. While you can spend the time writing code that cleans up your string, many people have created tools that are ready for you to use. For instance, there’s an npm package to help with this and also a lodash addon. A quick search around the internet leads to many other tools like these to help slugify strings. Happy slugifying!

Last week, I wrote about blocking vs. non-blocking code and the asynchronous nature of JavaScript. This week I wanted to deep dive into the event loop to explain one way JavaScript is able to deal with asynchronous functions and enables it to have non-blocking behavior.

Runtime Environment

Many people use JavaScript for the client-side of their app, but it can also be used on the server-side while using NodeJS. No matter where the code is being executed, i.e. its runtime environment, the event loop impacts the order that functions are called.

The JS engine goes through every line of code in your application and has to make decisions about when that code should be run.

The Infamous Call Stack

A stack! Okay, so not a call stack, but delicious nonetheless.

A stack is a common data structure. It functions exactly the stack of pancakes my dad makes for the whole family during the holidays – one at a time, people are able to remove a pancake from the top of the stack and to their plate. A stack works the same way – data on top of the stack can be removed, as well as added to the top of the stack until it needs to be processed.

The call stack is a special kind of stack in the JS engine. It processes one line of code at a time, and it executes whatever is on top of the stack. As soon as that function is finished executing, it is removed from the stack, and the line that was previously second in line is pushed to the top and executed.

Callbacks and Event Queues

Say we arrive at a line of code that needs this asynchronous behavior. Maybe you wrote a setTimeOut in your code to invoke a function at a later time, or perhaps a function that needs to get data from the database. These are called callback functions and the JS engine has a special way of handling them.

Instead of putting them directly into the call stack, the JS engine puts them into an event queue where it waits to be executed. Once the call stack is empty, it checks out the event queue and moves any function that is next in line to the call stack where it is executed.

Event Loop

The event loop is this process the JavaScript engine uses to execute functions on the call stack while also checking and eventually executing the next function in line in the event queue. As the user interacts with an application, the call stack and event queues are constantly moving and cycling through the code and reacting in response to user behavior. This keeps your program running smoothly!

While this is a very simplified version of what happens inside of a JavaScript engine, it is important information to keep in mind when writing code.

Structural Considerations:

This was my first project using ReactJS and Redux. Redux allows for what they call a “unidirectional” flow of data. The concept is simple enough, but actually seeing how the flow of data travels through the application took a while for me to understand. Also, the set-up is a lot to process the first time through, but the benefits are immense once you get it working. When using an MVC framework like Backbone, every time you make a change to the model, you also have to re-render the view which can get complicated as your app grows and gets complicated. But, ReactJS takes care of all rendering of the view for you, and Redux keeps track of all changes in the state of your app.

Thought Process:

The user has a dashboard that displays all their saved jobs which they can then click on to get to an individual job view page. We thought this would be a logical place to delete a job because you might read the details of a saved job and decide that it really wasn’t what you were looking for.

Before typing any code, I made a mental list of all the places that would be impacted by this button, which looked a little like this:

Create a delete button component

Import button into the job view container

Create a method that initialized the process of deleting a job from the database in the Job View Container

All of my initial thoughts were mostly about the front-end. It also made me realize that I had some questions about how properties and elements were passed between components and containers in React. Before I started coding, I researched some example projects online, as well as other parts of the app that other members of my team had worked on. I was then able to create a button in the job view container, as well as a skeleton for a handle-delete method that would be called when the button was clicked. At this point, I had to go back into research mode to try to figure out how Redux would help us make the change to the database as well as communicate with the React components of our app to actually delete the job from our view.

Redux:

I love Redux, and I highly recommend getting started with it by watching the series of videos on Egghead.io by its creator Dan Abramov which you can find here.

At the heart of Redux is a single STORE which is basically an object that keeps track of the entire state of your application. That store can be modified with specific actions which are then put into play using a reducer.

Actions are simply all of those things that need to happen to make your app work. In our project’s case, we have actions that add users to the database, add jobs, refresh the database, etc. Reducers….reduce (if you need a refresher on what reduce does, checkout my Re: contains post). In terms of Redux, a reducer takes an ACTION and applies it to the PREVIOUS STATE and reduces it to get a new state.

This is such a simple concept, but putting it into play when implementing the “Delete Jobs” feature from start to finish is finally how I was able to put this into practice.

In terms of my thought process, before I wrote my code I wrote comments and pseudo code in every file I had to touch to make this successful. This included our reducer file, actions file, and action types files. I hope to explain exactly what I did in the code in my next post.

VIEW ONLY

Model-view-controller (MVC) is a software architectural pattern. Different frameworks, like BackboneJS for instance, started popping up to help software developers architect web applications that kept the logic of the view of the page separate from model it was displaying and how it was actually getting displayed on the page via the controller. This helps keeps your code organized and logical – otherwise, your code might start getting….spaghetti’ed….i.e. – really tangled up and confusing.

React has gotten a lot of attention in the past few months, but it’s important to realize that React, only helps you take care of the view. As a programmer, you get to make decisions about how to structure the rest of your technology stack.

JSX Intro

JSX is html-like and awesome in my opinion! According to the React documentation itself, “JSX lets you create Javascript objects using HTML-syntax.” JSX is not requiredwhen using React, however it is commonly used and pretty simple once you get accustomed to the syntax. React helps you separate concerns in your code, so components will help you isolate exactly one part of the DOM that you need to update.

Tips:

1. {/* COMMENT HERE */} - This is the syntax you use if you need to make a comment in your JSX. The normal ways you would comment in JS, such as // or /* */ will not work.

2. Wrap new components in a div or span tag. If you don’t, they won’t get properly converted and placed to the DOM correctly.

3. return ( ); – React components return the part of the DOM you specify with the JSX. All of the JSX, or pseudo-HTML as I like to think of it, gets returned inside of two parentheses.

React has taken a period of adjusting to the way it works, but I hope to use it more for future projects.

File path shortcuts are commonly used in coding. Here is an example from a file where I was configuring authentication using passport:

In order to finish this feature of my site, I needed to use information from two other files, which I required on lines 4 and 5. I used to get confused about what one dot (.) vs. two dots (..) meant, but it’s actually very straight forward!

. means the file is on the same path level as the current file. Line 5 of my code uses this because I’m requiring the file auth.js, which is in the same directory as the current file passport.js... means the file is one path level up. Line 4 of my code uses this because the user.js file it needs is in the models directory, which is one level up from passport.js.

This type of path syntax is called a “relative path” because the path in question is being written in a way that tells its relationship to the path in question. You have to be careful if your file structures changes because then the paths will no longer work!

Last summer, I went to a Girl Develop It NYC panel where 6 women developers shared their experiences about how they got into the tech field and about what their day-to-day life was like. One of them said that the biggest lesson she learned was how to know what question to google when debugging her problem on the internet.

This is still something that I’m learning. Sometimes when I hit a wall when I’m coding, I can only see the problem from one point of view.

Example from Group Work

For a group project, my team and I created a Stack Overflow clone (http://stackoverflow.com/) which is a question and answer forum for developers. Our idea was to create a similar website, but only for people in the Hack Reactor Remote Community since we noticed that a lot of great resources and information were getting lost in our group messaging app. We’re proud of how it turned out (you can read my teammate’s write up o
f it here)!

When we planned out our scope of work, I was put in charge of researching how to use GitHub to authenticate users when they logged onto the website. I researched and I found that Passport was a common module people use to help them with authentication (http://passportjs.org/). I set out to explore how it worked and to understand it. I was able to make a small application that used passport to login users. However, when I tried to connect it to my group’s larger and more complicated app, I was lost. Try as I might, I could not get it to work.

The Perspective I was Missing

I spent a lot of time researching how to authenticate using GitHub, however, I failed to take into account other technologies in our stack and how they influenced what was happening to my code. Sometimes when I’m feeling frustrated with a bug, I tend to take it personally. This time, I became frustrated with myself for a day or so because I couldn’t figure out how to make it work.

With the idea of research in mind, the question I was not asking had to do with how Angular (the front-end framework we used) could make authentication challenging. Turns out, other people at one point or another had this problem as well, and developed tools to solve it. The great thing about open source software is that people develop and share specific tools to use to help solve problems. One of these tools ended up being the answer to our authentication problem.

Benefits of Teamwork

Even though I was not able to get Passport to work, I was able to document my code clearly and explain my thinking to my teammates. One of them took my code to try to make it work and was running into the same issues as I was. However, he researched authentication with Github AND Angular on the internet, and ended up finding Satellizer (https://github.com/sahat/satellizer). We ended up being able to use this tool to successfully fix our authentication issues.

Lessons Learned When Truly Stuck

Talk out the problem with a teammate – they might know something you don’t, or they might be able to see the problem from a different perspective

Think about how the entire tech stack you’re using could be influencing your bug

Move onto something else and come back to the problem later

Keep at it – be resilient in the face of a problem. Programming is all about keeping a cool head and problem-solving.

Servers……eek! I often heard terms like ‘client’ and ‘server’ being thrown around when getting into coding. Because I was mostly focused on learning front-end development, or basically the part of a web app that the user sees and interacts with (aka, the ‘client’), I never thought about the backend, or server-side until about two weeks ago. I’m going to attempt to break down what I’ve learned.

Big Picture

Let’s say you’ve been working on a web application for weeks. It has some basic functionality that you are able to use by opening it up in the browser. You feel proud of yourself, and your friends who’ve seen it think it’s pretty great too. But, how can you get it to a wider audience?

A server is basically a computer that is responsible for holding onto a website (or ‘hosting’ it). As people visit that website and interact with it, that server is responsible for getting and sending out data that the people visiting the site want to use. People using the site (sometimes referred to as clients) request data from the server. The server responds to requests with a response.

Example cat loaf photo of Valcore – the friendliest cat on the East Coast.

Pretend your app is a site for browsing and sharing cat pictures. When you visit the site, you can browse cats in a variety of categories (“Mischievous Cats,” “Cats Sleeping,” “Cat Loaves”, “Kittens at Play,” and “Cat Hunting Conquests”). If you’re really into cats causing mischief, you might click on that album. The server is hit with a request for those pictures, and will respond with showing you all the pictures of cats causing mischief it has.

Alternately, maybe you have a cat picture you want to share on the site, such as the example to the right. In this case when you upload the photo on the website, the server is hit with a request to get your photo and store it somewhere (probably in a database). Now, other people visiting the site can enjoy the cute cat photo you posted too.

This is a basic overview, but it is essentially what happens between a server and a client. Clients can send GET requests to the server, when they are asking for data, or POST requests when they are asking the server to handle data for them.

Zoom In: Local Server

I jumped ahead to talking about external servers in the previous example. Let’s turn back the clock in the development of our cat pictures site a few weeks. Before finding an external server to host your site, most developers will want to test their site locally. This allows them to fine tune the way their app handles different types of requests, and debug anything that might change functionality when refactoring code to have a server.

When developing the front-end, you might test functionality of the site by just opening up the index.html file in your browser. But, once you develop a server, you will run it in the browser through your local host and port number. It turns out that each computer has its own server! This initially confused me because I had an image in my mind that a server was just one of those box-like machines in a datacenter somewhere. Nope, you have a local server too.

My Foray into NodeJS

I have spent the past few weeks learning how to use NodeJS to make a server. There are many resources on how to make a basic server with Node, but once it came time to actually use it I realized that I was missing some fundamentals about how they work!

Things to Remember

You must specify a port number when you make a server. Ports help computers communicate across networks. There are some port numbers that have certain rules and specifications surrounding them, but many others you can use for developing your apps at home and testing them out.

To test out if your app is working once you’ve written it to include a server, you must START THE SERVER!!!!! This usually involves going into your command line and starting it up from the directory where your project is located. This depends on what you are using to create the server, but in Node you would type in node app.js, where the app.js is the file where your server code is located.

In this example, you can see that this application is connected to localhost at port 3000, and it happens to be routed to the login page:

The server on your machine is great for testing out your project, but it can’t handle a bunch of visitors from the outside. In order to get your app to a wider audience, you need to basically contract out the services of another company where your project can live on its servers. I hope to discuss deploying to a server in an upcoming post.