Prelude
It was during the second age
that the great founder of our order Branden Iech,first stumbled upon the arcane REPL,
and learnt how to bend the fabric of existence to his very will,then was that he discovered
there was a mechanism to alter the threads
being weaven into the Pattern,then that we started experiencing the magic of JavaScript
Imagine… imagine you lived in a world were you could use JavaScript to change the universe around you, to tamper with the threads that compose reality and do anything that you can imagine. Well, welcome to the world of JavaScript-mancy, where wizards, also known as JavaScriptmancers, control the arcane winds of magic wielding JavaScript to and fro and command the very fabric of reality.
We, programmers, sadly do not live in such a world. But we do have a measure of magic 1 in us, we have the skills and power to create things out of nothingness. And even if we cannot throw fireballs or levitate (yet), we can definitely change/improve/enhance reality and the universe around us with our little creations. Ain’t that freaking awesome?
Well, I hope this book inspires you to continue creating, and using this beautiful skill we share, this time, with JavaScript.
A Story About Why I Wrote This Book
I was sitting at the back of the room, with my back straight and fidgetting with my fingers on the table. I was both excited and nervous. It was the first time I had ventured myself to attend to one of the unfrequent meetings of my local .NET user group. Excited because it was beyond awesome to be in the presence of so many like-minded individuals, people who loved to code like me, people who were so passionate about software development that were willing to sacrifice their free time to meet and talk about programming. Nervous because, of course, I did not want to look nor sound stupid in such a distinguished group of people.
The meetup started discussing TypeScript the new superset of JavaScript that promised Nirvana for C# developers in this new world of super interactive web applications. TypeScript here, TypeScript there because writing JavaScript sucked… JavaScript was the worst… everybody in the room started sharing their old war stories about writing JavaScript, how bad it was in comparison to C#, and so on…
“Errr… the TypeScript compiler writes beautiful JavaScript” I adventured to say… the room fell silent. People looking astonishingly at each other, uncomprehending, unbelieving… Someone had dared use beautiful and JavaScript in the same sentence.
This was not the first, nor will be the last time I have encountered such a reaction and feelings towards JavaScript as predominant in the .NET community. JavaScript is not worthy of our consideration. JavaScript is a toy language. JavaScript is unreliable and behaves in weird and unexpected ways. JavaScript developers don’t know how to program. JavaScript tooling is horrible…
And every single time I sat muted, thinking to myself, reflecting, racking my brains pondering… How to show and explain that JavaScript is actually awesome? How to share that it is a beautiful language? A rich language that is super fun to write? That’s how this book came about.
And let me tell you one little secret. Just some few years ago I felt exactly the same way about JavaScript. And then, all of the sudden, I started using it, with the mind of a beginner, without prejudices, without disdain. It was hard at first, being so fluent in C# I couldn’t wrap my head around how to achieve the same degree of fluency and expressiveness in JavaScript. Nonetheless I continued forward, and all of the sudden I came to love it.
The problem with JavaScript is that it looks too much like C#, enough to make you confident that you know JavaScript because you know C#. And just when you are all comfortable, trusting and unsuspecting JavaScript smacks you right in the face with a battle hammer, because, in many respects, JavaScript is not at all like C#. It just looks like it on the surface.
JavaScript is indeed a beautiful language, a little rough on the edges, but a beautiful language nonetheless. Trust me. You’re in for a treat.
Why Should You Care About JavaScript?
You may be wondering why you need to know JavaScript if you already grok C#.
Well, first and foremost, JavaScript is super fun to write. Its lack of ceremony and super fast feedback cycles make it a fun language to program in and ideal for quick prototyping, quick testing of things, tinkering, building stuff and getting results fast. If you haven’t been feeling it for programming lately, JavaScript will help you rediscover your passion and love for programming.
JavaScript is the language of the web, if you are doing any sort of web development, you need to understand how to write great JavaScript code and how JavaScript itself works. Even if you are writing a transpiled language like TypeScript or CoffeeScript, they both become JavaScript in the browser and thus knowing JavaScript will make you way more effective.
But JavaScript is not limited to the web, during the past few years JavaScript has taken the world by storm, you can write JavaScript to make websites, in the backend, to build mobile applications, games and even to control robots and IoT devices, which makes it a true cross-platform language.
JavaScript is a very approachable language, a forgiving one, easy to learn but hard to master. It is minimalistic in its contructs, beautiful, expressive and supports many programming paradigms. If you reflect about JavaScript features you’ll see how it is built with simplicity in mind. Ideas such as type coercion (are “44” and 44 so different after all?) or being able to declare strings with either single or double quotes are great expressions of that principle.
JavaScript’s openness and easy extensibility are the perfect foundations to make it a fast-evolving language and ecosystem. As the one language for the web, the language that browsers can understand, it has become the perfect medium for cross-pollination across all software development communities, where .NET developers ideas can meet and intermingle with others from the Ruby and Python communities. This makes knowledge, patterns and ideas spread accross boundaries like never before.
Since no one single entity really controls JavaScript2, the community has a great influence in how the language evolves. With a thriving open source community, and openness and extensibility built within the language, it is the community and the browsers the ones that develop the language and the platform, and the standard bodies the ones that follow and stabilize the trends. When people find JavaScript lacking in some regard, they soon rush to fill in the gap with powerful libraries, tooling and techniques.
But don’t just take my word for it. This is what the book is for, to show you.
What is the Goal of This Book?
This book is the first installment of the JavaScript-mancy series and its goal is to provide a great and smooth introduction to JavaScript for C# developers. If you are a C# developer that has had no or little experience with JavaScript before then this book will help you get started. If you have had quite a bit of experience with JavaScript but it is still frustrating and you don’t understand why things behave the way they do, then this book will boost your JavaScript Fu until you start enjoying the language.
What is the Goal of The JavaScript-mancy Series?
The goal of the JavaScript-mancy series is to make you fluent in JavaScript, able to express your ideas instantly and build awesome things with it. You’ll not only learn the language itself but how to write idiomatic JavaScript. You’ll learn both the most common patterns and idioms used in JavaScript today, and also all about the latest version of JavaScript: ECMAScript 6 (also known ECMAScript 2015) and even about the upcoming version ECMAScript 7.
But we will not stop there because what is a language by itself if you cannot build anything with it. I want to teach you everything you need to be successful and have fun writing JavaScript after you read this series. And that’s why we will take one step further and take a glance at the JavaScript ecosystem, the JavaScript community, the rapid prototyping tools, the great tooling involved in building modern JavaScript applications, JavaScript testing and building an app in a modern JavaScript framework: Angular 2.
Why JavaScript-mancy?
Writing code is one of my favorite past times and so is reading fantasy books. For this project I wanted to mix these two passions of mine and try to make something awesome out of it.
In fantasy we usually have the idea of magic, usually very powerful, very obscure and only at the reach of a few dedicated individuals. There’s also different schools or types of magic: pyromancy deals with fire magic, allomancy relates to magic triggered by metals, necromancy is all about death magic, raising armies of skeletons and zombies, immortality, etc.
I thought that drawing a parallel between magic and what we programmers do daily would be perfect. Because it is obscure to the untrained mind and requires a lot of work and study to get into, and because we have the power to create things out of nothing.
And therefore, JavaScript-mancy, the arcane art of writing awesome JavaScript.
Is This Book For You?
I have written this book for you C# developer:
- you that hear about the awesome stuff that is happening in the realm of JavaScript and are curious about it. You who would like to be a part of it, a part of this fast evolving, open and thriving community.
- you that have written JavaScript before, perhaps even do it daily and have been frustrated by it, by not been able to express your ideas in JavaScript, by not being able to get a program do what you wanted it to do, or struggling to do so. After reading this book you’ll be able to write JavaScript as naturally as you write C#.
- you that think JavaScript a toy language, a language not capable of doing real software development. You’ll come to see an expressive and powerful multiparadigm language suitable for a multitude of scenarios and platforms.
This book is specifically for C# developers because it uses a lot of analogies from the .NET world, C# and static typed languages to teach JavaScript. As a C# developer myself, I understand where the pain points lie and where we struggle the most when trying to learn JavaScript and will use analogies as a bridge between languages. Once you get a basic understanding and fluency in JavaScript I’ll expand into JavaScript specific patterns and constructs that are less common in C# and that will blow your mind.
How is The Book Organized?
This is the introductory book to Part I. Mastering the Art of JavaScript-mancy which aims to teach you how to write JavaScript with fluency.
We will start by taking a quick walkthrough through all that JavaScript has to offer from types, functions and objects, to data structures, exception handling and regular expressions.
Then we will do a deep dive into JavaScript functions which are more common-place and live more independent lives in JavaScript than in C#. You’ll learn different patterns to do defaults, multiple arguments, function overloading in both ES5 and ES6.
We will continue taking a look at objects in JavaScript and at the many improvements that ES6 brings to object literals.
After you’ve learned more about functions and objects, two core constructs of JavaScript, we will discuss the big gotchas where we C# developers usually get stuck and stumble focusing particularly in the behavior of the this
keyword.
We will finish this introduction to JavaScript with a look at some great ES6 features that will improve the readability of your code and at JavaScript data structures: the super useful and polifacetic array, the map and the set.
How Are The JavaScript-mancy Series Organized? What is There in the Rest of the Books?
The rest of the books are organized in 3 parts focused in the language, the ecosystem and building your first app in JavaScript.
After this introductory book Part I. Mastering the Art of JavaScript-mancy continues by examining object oriented programming in JavaScript, studying prototypical inheritance, how to mimic C# (classic) inheritance in JavaScript. We will also look beyond class OOP into mixins, multiple inheritance and stamps where JavaScript takes you into interesting OOP paradigms that we rarely see in the more conventional C#.
We will then dive into functional programming in JavaScript and take a journey through LINQ, applicative programming, immutability, generators, combinators and function composition.
Organizing your JavaScript applications will be the next topic with the module pattern, commonJS, AMD (Asynchronous module definition) and ES6 modules.
Finally we will take a look at Asynchronous programming in JavaScript with callbacks, promises and reactive programming.
Since adoption of ES6 will take some time to take hold, and you’ll probably see a lot of ES5 code for the years to come, we will start every section of the book showing the most common solutions and patterns of writing JavaScript that we use nowadays with ES5. This will be the perfect starting point to understand and showcase the new ES6 features, the problems they try to solve and how they can greatly improve your JavaScript.
In Part II. Welcome to The Realm Of JavaScript we’ll take a look at the JavaScript ecosystem, following a brief history of the language that will shed some light on why JavaScript is the way it is today, continuing with the node.js revolution and JavaScript as a true cross-platform, cross-domain language.
Part II will continue with how to setup your JavaScript development environment to maximize your productivity and minimize your frustration. We will cover modern JavaScript and front-end workflows, JavaScript unit testing, browser dev tools and even take a look a various text editors and IDEs.
We will wrap Part II with a look at the role of transpiled languages. Languages like TypeScript, CoffeeScript, even ECMAScript 6, and how they have impacted and will affect JavaScript development in the future.
Part III. Building Your First Modern JavaScript App With Angular 2 will wrap up the book with a practical look at building modern JavaScript applications. Angular 2 is a great framework for this purpose because it takes advantage of all modern web standards, ES6 and has a very compact design that makes writing Angular 2 apps feel like writing vanilla JavaScript. That is, you won’t need to spend a lot of time learning convoluted framework concepts, and will focus instead in developing your JavaScript skills to build a real app killing two birds with one stone (Muahahaha!).
In regards to the size and length of each chapter, aside from the introduction, I have kept every chapter small. The idea being that you can learn little by little, acquire a bit of knowledge that you can apply in your daily work, and get a feel of progress and completion from the very start.
Understanding the Code Samples in This Book
How to Run the Code Samples in This Book
For simplicity, I recommend that you start running the code samples in the browser. That’s the most straightforward way since you won’t need to install anything in your computer. You can either type them as you go in the browser JavaScript console (F12
for Chrome if you are running windows or Opt-CMD-J
in a Mac) or with prototyping tools like JsBin, jsFiddle, CodePen or Plunker. Any of these tools is excellent so you can pick your favorite.
If you don’t feel like typing, all the examples are available in jsFiddle/jsBin JavaScriptmancy library: http://bit.ly/javascriptmancy-samples.
For testing ECMAScript 6 examples I recommend JsBin, jsFiddle or the Babel REPL at https://babeljs.io/repl/. Alternatively there’s a very interesting Chrome plugin that you can use to run both ES5 and ES6 examples called ScratchJS.
If you like, you can download all the code samples from GitHub and run them locally in your computer using node.js.
Also keep an eye out for javascriptmancy.com where I’ll add interactive exercises in a not too distant future.
A Note About Conventions Used in the Code Samples
The book has three types of code samples. Whenever you see a extract of code like the one below, where statements are preceded by a >
, I expect you to type the examples in a REPL.
The code after >
is what you need to type and the expression displayed right afterwards is the expected result:
Some expressions that you often write in a REPL like a variable or a function declaration evaluate to undefined
:
Since I find that this just adds unnecessary noise to the examples I’ll omit these undefined
values and I’ll just write the meaningful result. For instance:
When I have a multiline statement, I will omit the >
so you can more easily copy and paste it in a REPL or prototyping tool (jsBin, CodePen, etc). That way you won’t need to remove the unnecessary >
before running the sample:
I expect the examples within a chapter to be run together, so sometimes examples may reference variables from previous examples within the same section. I will attempt to show smallish bits of code at a time for the sake of simplicity.
For more advanced examples the code will look like a program, there will be no >
to be found and I’ll add a filename for reference. You can either type the content of the files in your favorite editor or download the source directly from GitHub.
A Note About the Exercises
In order to encourage you to experiment with the different things that you will learn in each chapter I wrap every single one of them with exercises.
It is important that you understand that there is almost no wrong solution. I invite you to let your imagination free and try to experiment and be playful with your new found knowledge to your heart’s content. I do offer a solution for each exercise but more as a guidance and example that as the one right solution.
In many of the exercises you’ll see the following pattern:
This is completely equivalent to:
I just use a helper function weaves
to make it look like Moolen, the mighty wizard is casting a spell (in this case teleport
).
A Note About ECMAScript 5 and ECMAScript 6,7 within The Book
Everything in programming has a reason for existing. That hairy piece of code that you wrote seven months ago, that feature that went into an application, that syntax or construct within a language, all were or seemed like good ideas at the time. ES6, ES7 and future versions of JavaScript all try to improve upon the version of JavaScript that we have today. And it helps to understand the pain points they are trying to solve, the context in which they appear and in which they are needed. That’s why this book will show you ES5 in conjunction with ES6 and beyond. For it will be much easier to understand new features when you see them as a natural evolution of the needs and pain points of developers today.
How will this translate into the examples within the book? - you may be wondering. Well I’ll start in the beginning of the book writing ES5 style code, and slowly but surely, as I go showing you ES6 features, we will transform our ES5 code into ES6. By the end of the book, you yourself will have experienced the journey and have mastered both ES5 and ES6.
Additionally, it is going to take some time for us to start using ES6 to the fullest, and there’s surely a ton of web applications that will never be updated to using ES6 features so it will be definitely helpful to know ES5.
A Note About the Use of Generalizations in This Book
Some times in the course of the book I will make generalizations for the sake of simplicity and to provide a better and more continuous learning experience. I will make statements such as:
In JavaScript, unlike in C#, you can augment objects with new properties at any point in time
If you are experienced in C# you may frown at this, cringe, raise your fist to the sky and shout: Why!? oh Why would he say such a thing!? Does he not know C#!?. But bear with me. I will write the above not unaware of the fact that C# has the dynamic
keyword and the ExpandoObject
class that offer that very functionality, but because the predominant use of C# involves the use of strong types and compile-time type checking. The affirmation above provides a much simpler and clearer explanation about JavaScript than writing:
In JavaScript, unlike in C# where you use classes and strong types in 99% of the situations and in a similar way to the use of dynamic and ExpandoObject, you can augment objects with new properties at any point in time
So instead of focusing on being correct 100% of the time and diving into every little detail, I will try to favor simplicity and only go into detail when it is conductive to understanding JavaScript which is the focus of this book. Nonetheless, I will provide footnotes for anyone that is interested in exploring these topics further.
Do You Have Any Feedback? Found Any Error?
If you have any feedback or have found some error in this book that you would like to report, then don’t hesitate to drop me an email at [email protected].
A Final Word From the Author
The goal for this series of books is to be holistic. Holistic enough to give a good overview of the JavaScript language and ecosystem, yet contain enough detail to impart real knowledge about how JavaScript really works. That’s a fine line to tread and sometimes I will probably cover too little or too much. If so don’t hesitate to let me know. The beauty of a lean published book is that I have much more room to include improvements suggested by you.
There is a hidden goal as well, that is to make it as fun and enjoyable as possible. Therefore the fantasy theme of the whole book, the conversational style, the jokes and the weird sense of humor. Anyways, I have put my heart and soul into this book and hope you really enjoy it!
Jaime, 2015
-
“Any sufficiently advanced technology is indistinguishable from magic.” Arthur C. Clarke. Love that quote :) ↩
-
The ECMAScript standard in which JavaScript is based is evolved by the TC39 (Technical Committee 39) composed of several companies with strong interest in JavaScript (all major browser vendors) and distinguished members of the community. You can take a look at their GitHub page for a sneak-peek into how they work and what they are working in ↩