JS Questions: What is MongoDB?

This is the fourteenth in a series of posts I’m writing that aims to provide concise, understandable answers to JavaScript-related questions, helping me better understand both foundational concepts and the changing landscape of language updates, frameworks, testing tools, etc.

What is MongoDB?

MongoDB is an open-source database program. There are several database management systems; some of the most popular are Oracle, MySQL, and PostgreSQL. MongoDB has been gaining popularity in recent years and is different from the ones above, because it’s a NoSQL, or non-relational, database management system.

First, Relational Databases…

Relational databases have rows of data stored in tables. A row of data can contain columns with keys that link one record to another. For instance, if there were a relational database containing data about the show Comedians in Cars Getting Coffee, it may have a table for episodes and another table for comedians. Every episode features one comedian (aside from the comedian host, Jerry Seinfeld) so each episode record could have a column called comedian_id that contains a key corresponding with a comedian from the comedian table.

Below is a visual showing how the data would be stored. The only episode in the episodes table has a comedian_id of 2. Kristen Wiig is the comedian in the comedians table with the primary key 2, so she is the comedian for this episode.

Screen Shot 2018-01-22 at 10.47.32 AM.png

Using the database querying language, SQL, tables can reference each other’s data through JOIN statements. Here’s an example:

SELECT Episodes.Title, Comedians.Name FROM Episodes INNER JOIN Comedians ON Comedian.Id = Episodes.Comedian_id;

This is saying: show episode titles with their corresponding comedian names by using the episode’s comedian_id to find the comedian with an id of the same number.

Now, NoSQL Databases…

Records are stored differently with MongoDB. Instead of table rows, data is stored in JSONlike documents.

A document can contain nested information. For instance, an episode document may contain a nested comedian document. Or, a document for the show’s seasons could have a nested array of episodes.

Below is an example of what a document might look like for an episode with one comedian.

mongo_ex.png

A grouping of documents–all comedians, for example–is called a collection. It’s the equivalent to a table in a relational database, though unlike a relational database, items do not need to have the same schema.

The mongo shell can be used to interact with a database and perform actions, such as retrieving all documents from a collection. The below code would grab all comedians from a database (db) with a comedians collection, using the .find() operation:

db.comedians.find()

Since documents can store nested data (such as an episode’s comedian), the need to perform a costly ‘join’ in order to access data is reduced. (MongoDB does have the functionality to join collections when needed.)

MongoDB in context…

MongoDB is generally associated with the latest wave of web applications and tech startups. Of course, different database management systems are suitable for different projects, but these are a few reasons (I think) MongoDB is gaining momentum.

MongoDB is well suited to the Agile style of software development that has become popular. Engineers using a quick, iterative development approach can easily change their schema and models as needed.

For startups and fast growing applications, there’s also the benefit of MongoDB’s distributed database design. Data is stored across multiple machines by default, so the database can easily expand as needed.

The 2017 Stack Overflow Developer Survey has a correlated technologies graph showing MongoDB closely linked with the frameworks Angular, Node.js, React, and Cordova, as well as the languages, JavaScript and TypeScript (a syntactical superset of JavaScript). While it’s not necessary to pair MongoDB and JavaScript (there are several ‘drivers‘ that can be used to interact with MongoDB with different programming languages), building full stack applications entirely with JavaScript is growing in popularity. Two common stacks for building modern web applications are MEAN (MongoDB, Express, Angular, Node.js) and MERN (MongoDB, Express, React, Node.js).

Part of the excitement about MongoDB can also be attributed to the fact that it’s new, has an excited community, growing features, and pretty approachable documentation and educational features on the MongoDB site.

Final note: There’s a lot of debate about whether MongoDB is better than SQL options. MongoDB may be faster in some cases (such as the previous example of reading an episode’s comedian), but SQL databases have their own advantages, including the reliability of a mature system (Oracle has been around since 1977). This Sitepoint article offers an introduction to best use-cases for SQL and NoSQL databases.

Resources

 

Advertisements

JS Questions: What is Express?

This is the thirteenth in a series of posts I’m writing that aims to provide concise, understandable answers to JavaScript-related questions, helping me better understand both foundational concepts and the changing landscape of language updates, frameworks, testing tools, etc.

What is Express?

The backend framework Express, released in 2010 and supported by Node.js, can be used to handle routing, generate ‘views’ for request responses, and define an application’s basic specifications. Express can be used with any database that Node supports, such as MongoDB, PostgreSQL, and Redis (though it’s not necessary to use a database with Express).

The following code creates a server without using Express. The server runs on port 3000, allowing a user to go to “localhost:3000/” and see the string “Hello World!”.

This illustrates that it’s not necessary to use Express to employ Node’s HTTP request response cycle. However, Express makes it easier to define routes and set up some basic specifications for an app. After installing Express, the following code should also render “Hello World!” at “localhost:3000/”:

Express’s website describes the framework as “fast, unopinionated, minimalist,” because its simply a layer on top on Node.js that allows developers use any file structure, pattern, or additional middleware they choose. This makes it easy to build simple applications without unnecessary bulk.

Express is used in production by some high profile companies (Uber, IBM, MuleSoft, to name a few) and is a part of the JavaScript stacks MEAN (Mongo, Express, Angular, Node) and MERN (Mongo, Express, React, Node).

Resources

 

JS Questions: What’s the Event Loop?

This is the eleventh in a series of posts I’m writing that aims to provide concise, understandable answers to JavaScript-related questions, helping me better understand both foundational concepts and the changing landscape of language updates, frameworks, testing tools, etc.

What’s the Event Loop?

Like any programming language, JavaScript has a specific process for handling function calls in a program, and more specifically, deciding when each function will run. Unlike other languages, JavaScript can be run in a browser, meaning that users may be interacting with the program by clicking a mouse or scrolling, for instance, simultaneous to other processes that are already running. The event loop helps create a fluid experience for users, by dictating a flow that allows for relatively long running processes to occur alongside client-side interactions.

Without features built into Node and browsers, JavaScript would only be able to handle one event at a time. Each function call would be added to a stack and one-by-one, popped off the top and run. It’s easy to imagine how this could become problematic in a web app. If a notice telling a user she had successfully updated her account were rendered to a webpage for three seconds using setTimeout, the user would not be able to interact with the page until the setTimeout had completed.

Some events do happen synchronously in JS. Loops will run in the call stack and prevent a webpage from re-rendering until they have completed.

However, due to the event loop built into browsers, processes such as AJAX requests and timeouts can run in the background, with their callback functions placed in a queue that are added to the call stack only when the entire stack has cleared. The below code snippet illustrates this.

If you paste this in your console, you’ll see 1 logged, then 2 returned, then 3 logged. Here’s what happens:

  1. The eventLoop function gets added to the call stack.
  2. The setTimeout timer begins and the callback function is added to the queue after 0 milliseconds.
  3. The number 1 is immediately logged.
  4. The eventLoop function returns 2 and the call stack is cleared.
  5. The setTimeout callback runs, logging 3.

Note that the call stack runs functions in ‘first in last out’ order (meaning that the first function added to a stack is the last to run). That’s why, in the code below, the strings are already concatenated when logged:

First, the greet function is added to the call stack. Then, the concat function is added to the call stack. Concat runs, the greeting is logged, and the greet function is cleared from the stack.

Meanwhile, the queue runs callback functions in ‘first in first out’ order. The first item added to the queue is the first to be added to the call stack. That means, if multiple AJAX requests are made, for instance, the first request to finish will be the first to have its callback function run.

In sum, the event loop in JavaScript refers to the synchronous and asynchronous flow dictated by the call stack and queue in browsers.

Resources

 

JS Questions: What is Node.js?

This is the ninth in a series of posts I’m writing that aims to provide concise, understandable answers to JavaScript-related questions, helping me better understand both foundational concepts and the changing landscape of language updates, frameworks, testing tools, etc.

What is Node.js?

Unlike Ruby (and many other programming languages), JavaScript wasn’t built to be executed outside of the browser. A Ruby program can be run by simply typing the path to the file to be run prepended by ‘ruby’ in terminal:

ruby filename.rb

Node.js (also called simply Node), which is built on the Chrome V8 JavaScript Engine, can be used to run JavaScript code outside of the browser. To try it, download Node and run the Javascript file from terminal:

node filename.js

Nodejs.org refers to Node as a runtime. Runtime environments dictate how a program is executed. All runtime environments have an event loop, or set of instructions how a programming language handles incoming events and dispatches them.

A ‘non-blocking I/O model’ differentiates Node from other runtime environments. Input and output (I/O) refers to the interaction between the processing system and user or other input making a request. A user clicks their mouse, for example, and the server returns requested data rendered in the browser.

In contrast to a non-blocking model, a blocking I/O is one in which JS code cannot run until the previous operation is complete. In other words, the event loop pauses until the process finishes. Node allows asynchronous, non-blocking events to occur, meaning that a process doesn’t need to finish in order for another to start. This allows an application to handle frequent incoming requests with minimal downtime.

Node is widely used to make server-side applications. The server side of an app takes in requests and responds with data to the front end of the application. This allows requests to create, update, or delete data to be persisted in a database, as well as for information to be accessed from the database and rendered in the front end.

Scalability, low latency, and high bandwith are often noted as key benefits of using Node over other server-side options, due to its non-blocking I/O. More information about how Node works as compared to Ruby’s Event Machine, for example, is available on nodejs.org.  There’s also a ‘hello world’ example for creating a server with Node and hosting it on a port.

Node also has a popular JavaScript package manager, npm, which allows developers to install JavaScript packages, pieces of software made available to developers to download and use with their own projects. Some commonly downloaded JS packages include express, react, and babel-core.

“Node’s package manager, npm, has transformed from hosting utility modules for server-side apps to the canonical place to store distributable JavaScript code.” –The future of Javascript in 2017 and Beyond

Finally, node is also open source and has a community of contributors.

Resources

 

 

JS Questions: What is a First-Class Function?

This is the fifth in a series of posts I’m writing that aims to provide concise, understandable answers to JavaScript-related questions, helping me better understand both foundational concepts and the changing landscape of language updates, frameworks, testing tools, etc.

What is a First-Class Function?

In JavaScript, functions can be assigned to variables, passed as arguments to other functions, returned by functions, and stored in data structures. Basically, functions are instances of JavaScript’s Object type, just like strings or arrays.

Below is an example of a JavaScript arrow function being assigned a variable name, exclaim. JavaScript’s map function is called on an array of words, and passes in the exclaim function as an argument. These are two ways first-class functions can be used.

When a function takes in another function as an argument and/or returns a function as its value, it is known as a higher-order function. The map example above is a higher-order function.

A function passed as an argument to another function is known as a callback function.

Not all programming languages have first-class functions. With Ruby, for example, methods cannot be assigned to variables or be passed to other methods.

Sources

JS Questions: What is JSON?

This is the fourth in a series of posts I’m writing that aims to provide concise, understandable answers to JavaScript-related questions, helping me better understand both foundational concepts and the changing landscape of language updates, frameworks, testing tools, etc.

What is JSON?

JSON, or JavaScript Object Notation, is a syntax that is useful for sending and receiving server data. Since a server can only send and receive data as text, JSON is used to convert data into text, as well as transform text received from a server into an easily readable format for developers. These transformations are made using the JSON.stringify() and JSON.parse() methods, respectively.

Modern webpages frequently make requests using the AJAX request and response cycle. Once a response has been received, it can be parsed to JSON. From there, a developer can access data in the JSON object.

JSON is compatible with many programming languages (not just JavaScript). A ruby developer can treat the JSON object like a ruby hash, for example, using dot or bracket notation to access nested key-value pairs. A JavaScript programmer would treat the JSON object like a JavaScript object.

The data types that can be converted with JSON are:

  • number
  • string
  • boolean
  • array
  • object
  • null

Sources

 

 

JS Questions: What is a Dynamic Programming Language?

This is the first in a series of posts I’m writing that aims to provide concise, understandable answers to Javascript-related questions, helping me better understand both foundational concepts and the changing landscape of language updates, frameworks, testing tools, etc. 

I’m starting with the basics: what is a dynamic programming language?

A dynamic programming language is a high-level language that compiles at run time. Run time is the moment when a program is executed. Compiling means translating the higher-level code (such as the js code written by a programmer) into a lower-level code–machine code–that the computer can run.

Dynamic languages lend themselves to certain types of behaviors, such as metaprogramming–code that can manipulate code. In dynamic languages, variables can be reassigned, and values can even be coerced into different types (such as using parseInt() on the string “1”).

In general, programs written in dynamic languages can be developed more quickly, but won’t run as quickly as those written in static languages.

Some examples of dynamic languages are:

 

  • Javascript
  • Python
  • Ruby
  • Perl
  • PHP

Sources