Elm Web Development - Ajdin Imsirovic - E-Book

Elm Web Development E-Book

Ajdin Imsirovic

0,0
32,39 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Explore why ELM is a great alternative to using pure JavaScript and other JS-based solutions by building complete apps and websites.

Key Features

  • Develop your own scalable and modular web applications with Elm to make web development less messy compared to your JavaScript apps
  • Create personal portfolio website, a weather application, and a unit conversion website, and integrate your Elm apps with Rails 5
  • Boost the performance of your application with no runtime exceptions and JavaScript interoperability

Book Description

Web development with JavaScript usually involves dealing with performance and maintenance issues. JavaScript fatigue makes it difficult for many developers to keep up with the increasing complexity posed by the multitude of JavaScript frameworks with changing versions, and the need to use different tools such as task runners, module bundlers, compilers, testing suites, linting and debuggers. Elm is an easy-to-learn, functional programming language that simplifies web development by eliminating the complexity associated with using JavaScript for web development. Elm is a statically typed language and thus makes a front end web developer's life easier by preventing run-time errors.

You will begin by seeing the bigger picture of where Elm fits into the web development world and learning the basics of Elm programming. Firstly, you will get a taste for web development with Elm by developing a simple fizz-buzz app. Next you will get hands-on with advanced Elm concepts as you develop your own personal blogging website, a unit conversion app and a weather app with Elm. Finally, you will also learn how to integrate Elm with a Rails 5 app with the help of Webpack. By the end of the book you will have learned Elm programming, and its applications, and will appreciate how Elm simplifies web development for you.

What you will learn

  • Programming with the Elm language, its syntax and core concepts
  • Using Elm for front end web development projects
  • Developing complete websites with Elm
  • Decoding JSON into Elm
  • Integrating Elm with the standard front end web development technologies
  • Integrating Elm with back-end frameworks
  • Testing your applications in Elm

Who this book is for

This book is for frontend web developers who want to learn a simpler way of developing their applications. A knowledge of the basics of CSS and Bootstrap is required.

Ajdin Imsirovic has been working with frontend technologies, as well as web and print design, for almost 2 decades. He is an accomplished video course creator and the author of Bootstrap 4 Cookbook, by Packt Publishing. In his second book, Elm Web Development, he eases in the newcomers to the Elm language in several fun projects.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 314

Veröffentlichungsjahr: 2018

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Elm Web Development

 

 

 

 

 

 

 

 

An introductory guide to building functional web apps using Elm

 

 

 

 

 

 

 

 

 

 

 

Ajdin Imsirovic

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Elm Web Development

Copyright © 2018 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Commissioning Editor: Smeet ThakkarAcquisition Editor:Siddharth MandalContent Development Editor:Arun NadarTechnical Editor:Rutuja VazeCopy Editor:Safis EditingProject Coordinator:Sheejal ShahProofreader: Safis EditingIndexer:Aishwarya GangawaneGraphics:Jason MonteiroProduction Coordinator:Shantanu Zagade

First published: March 2018

Production reference: 1280318

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78829-905-3

>www.packtpub.com

mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

PacktPub.com

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.

Contributors

About the author

Ajdin Imsirovic has been working with frontend technologies, as well as web and print design, for almost 2 decades. He is an accomplished video course creator and the author of Bootstrap 4 Cookbook, by Packt Publishing. In his second book, Elm Web Development, he eases in the newcomers to the Elm language in several fun projects.

I thank my wife Lejla for being supportive in writing this book. Without her help, this book would not have been possible.

About the reviewers

Jasmin Djedovic is an experienced programmer focusing mainly on C++, C#, and the Elm language. He works as a teaching assistant at the faculty of electrical engineering at the University of Tuzla. He also works as a full-stack developer in a fintech company, working on multiple desktop applications used in stock exchange trading.

I would like to thank Ajdin for inviting me to this great journey of publishing a book about Elm. Thanks to Amer Hasanovic, my mentor who shared his knowledge and encouraged me to dig into functional programming using Elm language. Last and not least, thanks to my family, friends, and colleagues for being supportive.

 

 

 

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Title Page

Copyright and Credits

Elm Web Development

www.packtpub.com

Why subscribe?

PacktPub.com

Contributors

About the author

About the reviewers

Packt is searching for authors like you

Preface

Why learn Elm?

The goal of this book

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Conventions used

Get in touch

Reviews

Why is This a Great Time to Learn Elm?

What is Elm?

Why is it worth learning Elm?

Blazing-fast virtual DOM

Friendly compile-time errors

Zero runtime exceptions

Constraints as guarantees

Piped syntax

Easy refactoring

Helpful type system

Increased productivity

Getting started with writing Elm code

Getting started fast with Ellie-app

Adding type annotations

Getting started fast with create-elm-app

Getting started with Elm on Windows 10

Installing apm (Atom Package Manager)

Summary

Building Your First Elm App

Let's build an app

Immutable data structures

The Elm architecture

The Model

The View

The Message

The Update

Unidirectional data flows

Our app requirements

Building the Fruit Counter app

Exposing everything we need

The Model

The View

The Message

The Update

Adding the beginnerProgram function

Views, buttons, and events

Constraining the Decrement message

Values, expressions, data structures, and types in Elm

Primitive types in Elm

Char and String types

The number type

Booleans

Data structures: lists, tuples, records, sets, arrays, and dictionaries

Lists

Tuples

Records

Sets

Arrays

Dictionaries

Functions, if expressions, and types

Revisiting Elm messages

Functions, pattern matching, and case expressions

Improving the Fruit Counter app

Building a simple FizzBuzz app in Elm

Summary

Creating Your Personal Portfolio with Elm

Creating our portfolio with elm-make-app

Building a static single-page portfolio

HTML for Elm

Function signatures for HTML elements

Function signature for text function

Adding our view function

Calling the view function from another file

Adding some style

Splitting the view into multiple files

Completing our Writer's portfolio

Rendering sections of our page using case expressions

Improving our messages

Adding the type alias of Model

Working with List.map and List.filter

Revisiting the FizzBuzz app

Implementing FizzBuzz with List.map

Summary

Preparing a Unit Conversion Website in Elm

What are we going to build?

Building our Unit Conversion app

Updating the init function

Type annotations and type aliases

Updating the view and update functions

Adding the conversion logic

Improving the input function

The stumbling block

Dealing with the Result.Result error

Using the Result type to fix our app

Calculating the conversion

Refactoring our app using a let expression

Making our app look nicer

Adding Bootstrap styles

Revisiting the FizzBuzz app

Giving our FizzBuzz app some logic

Summary

Completing the Unit Conversion Website in Elm

Improving the Unit Converter app

Separating UnitConverter into a different module

Adding type alias Model, initModel, and Main

Updating the Main.view function

Understanding Html.map

Updating the Main.update function

Learning from compiler error messages

A Bootstrap-based HTML layout for our app

Converting an HTML layout into an Elm view

Adding the improved view to our functioning app

Summary

Exploring Elm in Greater Detail

Destructuring values in Elm

Destructuring tuples in Elm using let-in expressions

Destructuring tuples in Elm using case-of expressions

Building a FizzBuzz app using tuple destructuring inside of a case-of expression

Destructuring nested tuples using let-in expressions

Destructuring records in Elm using let-in expressions

Destructuring records on the fly

Dealing with randomness in Elm

Commands in Elm

Subscriptions in Elm

Improving the Elm architecture by adding effects

Understanding partial application

Summary

Making a Weather App in Elm

Obtaining the weather data from a third-party API

What are we going to build?

Building our weather app

Installing the HTTP package

Adding all the imports

Conceptualizing the model

Setting up Msg union type

Result and Maybe

Working with Result

Working with Maybe

Result and Maybe with Defaults

Updating the update function

Decoders and encoders

Decoding primitive values

Decoding a JSON string returned from the API

Decoding nested objects

Adding getTemperature and decodeTemperatureInfo

Updating the view

Summary

Adding More Features to the Weather App

Importing Material and Round modules

Adding elm-mdl to our Model

Updating the init function

Updating the Msg union type and the update function

Updating the view function

Understanding the Textfield function

Understanding the Button function

Understanding the Card function

Understanding the use of Card.view

Rendering the Card.title content block

Understanding the Card.actions code

Adding color schemes

Updating decodeTemperatureInfo

Summary

Testing in Elm

Introduction to Elm testing

Understanding how testing works in Elm

The describe function 

The test and Expect functions

Writing unit tests in Elm

Using let-in expressions in our tests

Decoding JSON in our tests

Building custom expectations while decoding JSON

Writing fuzz tests in Elm

Working with more than one fuzzer

Summary

Integrating Elm with Rails

Setting up a basic Rails 5.1.5 app using Codeanywhere

Installing Ruby 2.5.0 and Rails 5.1.5 on Codeanywhere

Creating a brand new Rails project

Integrating Elm with Rails 5.1.5

Adding our Elm weather app to our Rails app

Summary

Visit elmcasts.com

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Elm is a wonderful functional programming language for frontend web development. There are a number of reasons why learning Elm will be a useful and enjoyable experience.

Why learn Elm?

Elm is easy to get started with. The learning curve is not too steep. Elm does not introduce an overwhelming amount of new concepts to understand and learn; actually, it is quite the opposite. Once you learn the Elm way of doing things, with the focus on some key concepts of functional programming, there is not a huge number of new topics to understand.

It can be a great way into the more advanced concepts of functional programming. It's probably among the easier ways to start thinking in terms of the functional programming paradigm.

Even though is it easy to learn, the return on investment is pretty high; imagine all the time you will save not having to do JavaScript-style debugging! In the long run, this ROI compounds. The way that Elm achieves this is by having no runtime errors. All the errors are caught at compile time (so you can forget about things like undefined is not a function on a live project). Compile time is very fast. Also, Elm has one of the friendliest and most helpful compilers around.

If you are a bit tired of JavaScript and want to look at alternatives, you will most likely love Elm. Along the same lines, if you have had trouble trying to make up your mind about whether you should learn Angular, or React, or Vue, or any other JS framework, Elm is a viable alternative.

If you are learning React, understanding the Elm architecture will help you wrap your mind around Redux. An interesting bit of trivia: Redux was inspired by the Elm architecture.

If you already have some experience with JavaScript, it will give you a new perspective on it, and actually make you a better JavaScript developer. You can even use Elm and JavaScript together! Elm interops with JavaScript so you can use both languages side by side in your projects.

Elm is declarative. Scaling your Elm apps is actually a pleasant experience. Elm has a great community and excellent documentation.

The goal of this book

This book was written with the goal of introducing a complete beginner to the Elm language with some of its basic concepts and taking those concepts and building simple web apps in Elm from the get-go.

This book does not cover all the features of the Elm language, but rather gives you a solid foundation that you can build from.

One of the goals of this book was to make it easy for those who read it understand more advanced Elm apps and topics. Another goal of this book was to give you enough knowledge that you can confidently build your own apps in Elm once you complete it.

Who this book is for

This book is intended for web developers of all levels of expertise to use to understand the Elm language and build simple and practical web applications in it.

The beauty of the Elm language, among other things, is in the fact that you don't need to worry too much about HTML and CSS when you write it. So in this book, the focus is mostly on the Elm language itself. 

Familiarity with HTML, CSS, and the DOM, as well as how the web works, would be helpful, but is not necessary. Also, some experience with the Bootstrap framework and Material Design Language is welcome, but not compulsory.

This book was written with the goal of finding a sweet spot between giving enough knowledge so that readers can be productive as soon as possible, and being overwhelming. 

The book was also written with the idea that someone who is brand new to web development should find it easy to understand. Therefore, the book doesn't assume knowledge of JavaScript, nor does it extensively compare JavaScript with Elm, or if it does, it tries to limit this comparison to the level of broad generalizations.

In a sentence, this book is aimed at beginners and experienced developers alike, regardless of their level of knowledge of JavaScript.

What this book covers

Chapter 1, Why Is This a Great Time to Learn Elm?, covers introductory topics: what is Elm, what is unique about it, how it compares to JavaScript, how to get started with it, and some very basic Elm concepts with simple code snippets.

Chapter 2, Building Your First Elm App, describes immutable data structures, the Elm architecture (model, view, and update), unidirectional data flows, using HTML functions in Elm, expressions in Elm (if-else and case expressions), Elm data structures, union types, and some operators.

Chapter 3, Creating Your Personal Portfolio with Elm, discusses type aliases, mapping and filtering values, adding Bootstrap 4 styles to your Elm apps, understanding function signatures, and modularizing your Elm apps.

Chapter 4, Preparing a Unit Conversion Website in Elm, looks at using the Result type as a way to handle errors, and reinforces concepts covered in the previous chapters in a fun project.

Chapter 5, Completing the Unit Conversion Website in Elm, explains using Html.map, working with complex views and multiple models, and shows how to improve the existing Unit Conversion website.

Chapter 6, Exploring Elm in Greater Detail, covers the topic of destructuring values in Elm, the ways in which Elm deals with randomness (through commands and subscriptions), understanding partial application, and working with Html.program.

Chapter 7, Making a Weather App in Elm, shows how to deal with errors using Result, how to deal with optional values and nothingness using Maybe, how to decode JSON strings, how to fetch remote data with the Http package, and how to work with third-party APIs.

Chapter 8, Adding More Features to the Weather App, shows how to make our Elm apps look nicer by adding elm-mdl and how to work with the Round module, and reinforces topics covered in previous chapters.

Chapter 9, Testing in Elm, covers Elm unit testing and the role of the describe, Expect.equals, and test functions; it also deals with some specific operators and ways to use them in Elm tests, how to write tests for decoding JSON, and introduces fuzz tests.

Chapter 10, Integrating Elm with a Web Framework, shows how to integrate Elm apps in Rails 5.1 using the Webpacker and Yarn, as well as set everything up in a web-based IDE using an Ubuntu container.

To get the most out of this book

To get the most out of this book, you should be familiar with HTML, CSS, the way the web works, Bootstrap 4, and MDL.

Elm installation and setup are covered in

Chapter 1

,

Why is This a Great Time to Learn Elm?

, and will be updated in the code that comes with the book in the case of any changes, updates, or errata.

Download the example code files

You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at

www.packtpub.com

.

Select the

SUPPORT

tab.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Elm-Web-Development. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.

Why is This a Great Time to Learn Elm?

Welcome to the first chapter. This chapter is a gentle introduction to the Elm language. Our goal for this chapter is to understand the following:

What is Elm?

What is unique about Elm in the saturated field of frontend web development

How does Elm compare to JavaScript?

How to get started fast with the help of Ellie-app, Cloud9, and the Atom editor

After completing this chapter, you will be able to:

Compare the Elm code with the JavaScript code at a basic level

Set up and use Elm in several different ways

What is Elm?

Elm is a functional programming language aimed at frontend web development. In the words of Evan Czaplicki, the inventor of Elm:

"I wanted to do front-end stuff, but I wanted ... front-end programming to feel really, really pleasant." 

Evan is a functional programmer, and he wanted to apply, in practice, some of the academic concepts from functional programming, with the goal to make the whole experience of frontend web development a nicer one.

One important issue with the current way that frontend development works is the problem of accidental introduction and aggregation of small errors during development. While developing frontend JavaScript, errors will appear in our code, and very often, they will go unnoticed.

At a later point in time, these errors will result in our code breaking. That leads to a lot of time wasted on fixing the issues that we, developers, unintentionally brought to our code, through a number of obscure errors.

Elm makes it virtually impossible to introduce errors into our code. Through a combination of non-cryptic compile-time errors and a helpful type system, introducing errors into our code is on the verge of being impossible.

If we needed to point out just one thing that is awesome about Elm, it is this lack of runtime errors. Imagine working in JavaScript and never seeing runtime errors, and you might begin to appreciate the time savings that can be achieved by using Elm.

After you have worked with Elm for some time, you start to feel as if Elm is constantly narrowing the window of opportunity for errors to appear in your code, from the way it is structured to the way you work with it. You can feel that conscious effort was placed on making it less probable for errors to occur.

For example, as Elm is built around the paradigm of functional programming, it works with pure functions. Pure functions are functions that have no side effects. In other words, pure functions have no state. They accept parameters, and they return a value. That is all they do!

They will not go out and make an HTTP request. They will not mutate variables. They will not, in any way, change the state of the world. They simply return a value. This brings us to an interesting effect—as long as we provide the same values to a function in Elm, it will return the same result.

Another wonderful benefit of pure functions in Elm is that you can be certain that all the changes you make in your code are local. Changing a piece of code in your app will not cause some other piece of code in your application to stop working. 

To be fair, it is possible to write pure JavaScript applications in this restrictive functional style. However, there is nothing built-in in the language itself to throw an error if we lose our focus and start writing impure functions. Also, when working with third-party libraries, you cannot be sure that they have adhered to functional style purity. Compare that to Elm, which enforces nothing else but pure functions.

There is one caveat to this talk of pure functions. You are probably aware that a fully stateless application would be pointless. The ingenuity of Elm lies in the fact that it has a very strict way of dealing with updates to our application. The takeaway from this is that not only does Elm enforce the functional programming paradigm by forcing us to use pure functions, but it also narrows down ways to deal with the outside world.

The immutability of data that Elm has naturally leads to another great benefit: debugging. Since you can be certain that a random piece of your code will never be able to affect another piece of your code, it will simply not be possible to have to deal with the issue of not knowing which part of your code broke the application; that is, which part of your code is causing the error. In JavaScript, this is a common issue, which is literally nonexisting in Elm.

Another feature of Elm is that it works in a way that allows us to cater for events happening in our app, while still maintaining immutability. Elm is also a great way to start learning functional programming without having to understand a lot of advanced concepts (which would be the case when trying to learn other, more difficult functional programming languages).

Why is it worth learning Elm?

In this section, we will discuss some of the reasons why Elm is such an exciting language to learn.

These reasons are as follows:

Blazing-fast virtual DOM

Friendly compile-time errors

Zero runtime exceptions

Constraints as guarantees

Piped syntax

Easy refactoring

Increased productivity

Helpful type system

Time-traveling debugger

Now that we have an overview of the exciting concepts that Elm brings to the table, let's inspect each of them in a bit more depth.

Blazing-fast virtual DOM

In order to be able to discuss the virtual Document Object Model (DOM), we need to first understand what the DOM itself is. It is a standard that is proposed and maintained by the the World Wide Web Consortium (W3C). 

As defined by W3C on their website:

"The Document Object Model is a platform-and language-neutral interface that will allow programs and scripts to dynamically access and update the content, structure and style of documents. The document can be further processed and the results of that processing can be incorporated back into the presented page."

As per the W3C's DOM Specification Level 3 Core, the DOM is a way to access and manipulate documents in a tree-like structure consisting of nodes.  We can summarize the DOM as having the following characteristics:

The DOM is language-agnostic, meaning that in theory, any language could be used to manipulate it

The DOM is set up in such a way so as to allow for live manipulation of itself

The DOM consists of a set of objects (a nested, tree-like hierarchy of objects) 

The DOM also has

methods to manipulate this hierarchical structure; in other words, the DOM 

is an 

Application Programming Interface

(

API

)

Before we continue the discussion about the DOM, it is very important to make it perfectly clear just what an API is. To explain what the API abbreviation stands for, we can use the analogy of switching a light bulb on and off. In order to switch on a light bulb, we do not have to know what material it is made of, how much power is needed to run it, or how bright it is. All that we need to know is how to make it light up the room, and how to turn it off; that is, how to control its behavior.

Of course, as we are all very well aware, to control a light bulb we need to use a light switch. In the preceding example, we could say that the light switch is the API for the light bulb. In order to manipulate the light bulb (to make it do what we want), we need to access it via its API (the light switch).

In more general terms, we can think of an API as a way to access and manipulate, or control, in a structured manner, whatever it is that we want to work with.

In the case of the DOM, its purpose is two-fold. First, the DOM is the API for HTML. Using the light bulb analogy, HTML would be the light bulb, the DOM would be the light switch, and JavaScript would be pretty much the only way to access the light switch.

Secondly, the DOM is a representation of a web page. The previous sentence is crucial for our understanding of how the DOM works, so we will repeat it again.

The DOM is a representation of a web page. This representation is a tree-like structure that consists of building blocks—node objects. In total, there are 12 types of nodes in the DOM. However, this representation of a web page is not static, meaning it is not only a static representation of a hierarchical structure of a web page. Each node also includes all the properties and methods that enable us to alter the contents of this tree-like structure (the API part).

Practically, there is only one way to access the DOM—via JavaScript. There are some exceptions to this. For example, in IE 10 and lower, we could use VBScript, but for all practical purposes, it is safe to say that the only language that can work directly with the DOM is JavaScript.

In order to understand the interplay between web pages, HTML, the DOM, JavaScript, and browsers better, we need to understand what happens when you point your web browser to a web page. What follows is a very simplified explanation.

First, the browser will make a call to the server, which will return some HTML. The browser's rendering engine will then parse the raw HTML into its DOM representation. Parsing is the process of translating from one format to another. The raw HTML that is served from a web page cannot be directly manipulated. Instead of directly manipulating the raw HTML, we must use the DOM API, and therefore, the HTML of a web page needs to be internally parsed by the browser's rendering engine into its DOM representation.

Once the browser's rendering engine has parsed the HTML document into its object representation (the DOM), it is now available to JavaScript, which can manipulate the DOM representation of the HTML document.

Another way of looking at the relationship between HTML, the DOM, and the browser, is to understand that HTML is simply just text. It becomes what we see on our monitors only after the browser has parsed it into its DOM representation.

Several years ago, browsers were not complying to standards set forth by W3C. In recent years, they caught up to it, and the DOM API in all major browsers is, for the most part, standards-compliant. However, there are issues with the DOM.

HTML and CSS were not intended for modern web applications, with thousands of nodes that sometimes have to be updated according to certain criteria. Still, today, this sort of behavior on modern web pages is what users expect. Single-page Applications (SPAs) are a good example of this. In SPAs, the DOM needs to be constantly updated, and yet, the way that the DOM works makes its direct manipulation costly.

Several years ago, we would be using jQuery as the de facto standard of dealing with interactivity in our web pages. Thus, in case we'd want to update the page based on, say, a click event, we would tell jQuery to first find all the nodes in the page that need to react to that click event. Then, we would update the nodes.

Thus, the jQuery paradigm is that we are working with the DOM directly. For example, to target all the div elements on-click, and have them perform some kind of a change, we have to first set up our div selector, and then give it the event handler and the action to perform, like this:

$("div").on("click", performAction())

The issue with this is that there will probably be at least half a dozen events to listen for in your web app. There will also probably be a lot of DOM nodes that will have to be updated.

Direct DOM changes are slow. The larger your app gets, the more resource demanding direct DOM manipulation becomes, as there are more layout recomputations and reflows to be done when the DOM changes. Piling up these changes and web page reflows might lead to pages not being as snappy as users would expect.

Another issue is that as our web app grows, it gets harder to avoid bugs, because when working with the DOM directly, it is hard to separate concerns. The idea of virtual DOM is amazing in its simplicity. Instead of constantly touching the DOM, a much better approach is to have the whole DOM structure represented virtually, then keep a snapshot of the DOM, represented as virtual DOM nodes.

When the page needs to be re-rendered as a result of an event, the previous DOM snapshot is compared to the new DOM structure, and then only those changes that are needed to achieve the end result are performed on the actual DOM. 

To explain the distinction between the direct DOM manipulation and the virtual DOM better, let's look at two programming paradigms: imperative programming and declarative programming.

In imperative programming, we explain the how to get to the what. In other words, we need to give our program a full set of detailed instructions on exact steps that need to be performed in order to get to the desired result.

In declarative programming, we simply ask for the what to be performed; the inner workings of how the program should get to the desired result is not a concern. An example of a declarative language is SQL. For example, we could say:

SELECT * FROM Customers

WHERE Car='Mercedes' AND Color='Green';

We do not give SQL instructions on how to perform the action; we just tell it what result we want. In other words, we do not specify all the steps that SQL needs to take to search the database for customers that own a green Mercedes. We simply tell it what we want, but the implementation (how SQL does it behind the scenes) is not something that we have to know.

This is very similar to how virtual DOM works in Elm. We specify the result of our change, and let the Elm Runtime decide on the most effective way to get there. 

To wrap this section up, it is interesting to note that Elm has the fastest virtual DOM implementation of all the major JavaScript frameworks, which is quite an accomplishment.

Friendly compile-time errors

It is kind of interesting how there is an entire movement revolving around ideas like UX and UI. We web artisans strive to give our users the best possible experience while interacting with our websites and apps. But, besides being the construction workers of the web, ultimately, we are users too.

Before we look at an example of a JavaScript message, let's remember the only reason we are using JavaScript in these examples is because, as we discussed earlier in this chapter, it is practically the only language that works with the DOM API. Looking at some JavaScript error messages, it is interesting that we are still stuck with cryptic errors such as:

Uncaught TypeError: undefined is not a function

Why such a terse error message? Definitely not beginner-friendly.

Let's break this error message down, starting with Uncaught. Obviously, our application failed to catch this particular error. Next, TypeError. It is just one of several kinds of errors. Others include SyntaxError, URIError, RangeError, and so on. 

Finally, the message—undefined is not a function. It helps to know that undefined is one of JavaScript's primitive types. Others are string, number, null, boolean, and symbol. When a variable has been declared, but has not been assigned a value, the JavaScript engine assigns it the value of undefined. The undefined value is the only possible value of the undefined type. Thus, undefined can never be a function.

In other words, your code was trying to call a value as if that value was a function. Obviously, you can't call a non-function, hence the not a function part of the error message. Armed with this knowledge, let's rephrase our error to something that is a bit more user-friendly.

How about this:

Type Mismatch: Your code was trying to run a function call on the primitive type of undefined. That is not possible, since only functions can be called, and undefined is not a function.