One Year Later With JavaScript

If you are new to JavaScript or familiar with the facts that JavaScript is the language of www, created in 10 days and is not the same thing as Java. Then continue to read. Else you are expecting a deep dive into the language features with sophisticated algorithms, philosophical abstractions, conceptional design patterns, or why Math.max() is less then Math.min() then you came to the wrong place. Still, please continue reading and enjoy the rest of this article.

Over one year ago I decided to learn JavaScript. With basic knowledge of web development and playing around with languages such as Java, PHP and Ruby. It was now time to get serious and learn the one language that every one talks, uses and argues about. I had used jQuery a couple of times and I knew how to copy paste JavaScript code (which I still know how to do… and do). I never took the time or had the interest to learn the fundamentals behind the language. This was about to change.

I collected tons of notes while learning this outlaw of a language. I think that some of my early gotchas can be valuable for anyone starting out learning JavaScript. I want to share what beginners to JavaScript are exposed to both from the language and from the eco system, what I now think about JavaScript and what the future beholds for JavaScript.

The world of JS is so much bigger then I anticipated and its universe expands for every day.


What I Learned About JavaScript

First thing I learned was the confusing name difference. ECMAScript is the standard for the language e.g. ES6 (ECMAScript 6) is the version name, while JavaScript is based on ECMAScript.

It’s accessible and easy to start out typing JavaScript. Your browser has a JavaScript interpreter, open the browsers console and start playing around. Write 1 + 1 or function add(a,b){return a+b} add(1,1) and you have written your first calculating program. No need for setting up an environment or learn how the compiler works. The sandbox is right there in the browser.

“JavaScript is not a real programming language”

Yep, that’s what they say. I would say that it’s not like any other language. It’s dynamic, untyped and pretty random. However people are creating a lot of awesome stuff like complex UI, web apps, mobile apps, desktop apps, data visualisation, IoT and so on. There is game engines that support JavaScript. There is runtimes for JavaScript to build databases, read and write to the file system, enabling server sided operations or to instruct robots. The ecosystem is huge, it seems like there is a module for everything.

JavaScript is nowadays so called universal. It runs on the client side and can be executed on the server side. Not only can you handle a click event in the browser from a user, but also serve a user content or data over HTTP from your web server written in JavaScript. Frontend → ← Backend with one language. Not bad for a language designed to run on the client side.

Random quirkiness you will run into

The weird parts of JavaScript will be one of the reasons why you will love the language.

For starters you almost don’t need semicolons in JavaScript. I prefer to write without.

No Int(integers) in JavaScript. Numbers are floating numbers. Numbers can be assigned as decimals.

let x = 12
x // 12
let x = 12.00
x // 12
0.1 + 0.2 // 0.30000000000000004
0.1 + 0.2 === 0.3 // false
let x = 9999999999999999
x // 10000000000000000

JavaScript is not alone with this behaviour. Probably not the most suitable language for mathematical operations.

Actually you can do math with strings. Almost.

'2' - '1' // 1
'4' / '2' // 2
'2' * '2' // 4
'1' + '1' // '11' using plus will concatenate your strings

Truthy and Falsy values is a weird thing. Booleans represent a binary digit. JavaScript has boolean data types but also treat all values as either “true” or “false”. An empty object in JavaScript is considered to be Truthy, an empty string or number zero is considered to be Falsy.

isNaN(true) // false
{} // true
!{} // false
0 // false
"" // false

Learning about which values are “true” or “false” in JavaScript is a interesting journey and in some cases important.

Which leads us onto how we compare values and types in JavaScript. Using the equality operators double == or triple ===. Starting out learning JavaScript can be kind of tricky and this is one of the reasons.

0 == "" // true
0 === "" // false
0 == '0' // true
0 === '0' // false
'0' === '0' // true

Comparing zero to an empty string would give “true” because both values are falsy. Comparing zero to an empty string would give “false” because a number and string are not the same data type. Basically == compares values and === compares the type and value of an object.

So now we know which characters are either truthy or falsy and the notation of how to compare values, what can then go wrong?

Boolean() // returns true if the value equates true otherwise false
Boolean([]) // true
Boolean({}) // true
[] == {} // false
[] + {} // "[object Object]"
{} + [] // 0

Surprise!

There is a lot of reserved keywords in JavaScript, you might think that undefined is one of them but it’s not. All tough modern browsers don’t let you reassign undefined.

Null and Undefined. A declared variable that has not been assigned any value is undefined. Variables assigned to a non value is null. Makes sense. But it’s not that easy:

let foo
typeof foo // "undefined"
foo === undefined // true
let bar = null
typeof bar // "object"
bar === null // true

Everything is an object in JavaScript, at least everything appears to be an object. Confusing. Regex is an object, types like string, number, boolean will be wrapped in an object and treated as an object, so we can call methods on them like:

'some string'.toUpperCase() // "SOME STRING"
new String('some string').toUpperCase() // "SOME STRING"

Refer to a variable or call a function before its declaration is fine in JavaScript due to a behaviour called Hoisting. Seems spooky at first.

// Function invocation
foo('bar')
// Function declaration
function foo(p) {return p}
-> "bar"

Self invoking functions are a thing. More semantically correct called IIFE (Immediately Invoked Function Expression). It’s an anonymous function that invokes itself. It’s encapsulated and will there for not pollute the global name space. You will find IIFE’s in some of the popular design patterns. ES6 introduced the let keyword for block-scoped variables which could replace IIFE in some cases.

(function() { return 'Hello' }()) // Hello
// You can also pass an argument
(function(a) { return `Hello ${a}` }('World')) // Hello World

Variables in functions are local scoped and variables outside of functions are global scoped. It’s almost that simple. Learning how scopes and the context of the keyword this works is essential.

var x = 'Hello from global'
function foo() { return this.x }
foo() // "Hello from global"
const obj = {}
obj.x = 'Hello from local'
obj.foo = foo
obj.foo() // "Hello from local"

I wrote a couple of lines on how scope and context works and behaves, read here.

There is a garbage collector in JavaScript. That’s a friendly fella that cleans up your unused references from the memory. Still watch out for memory leaks.

“Don’t block the event loop”

JavaScript runs on a single thread and does not allow for parallel executions. Callbacks is a technique used to achieve concurrent code. Callbacks allows our program to run asynchronously and prevents blocking the event loop. The event loop queues up calls so that the program can continue to run and gets notified when a call has been executed and finished its operations. Some interesting patterns that are making use of callbacks are generators, promises and observables.

If the word callback still makes no sense to you, check out this article where I show how to create a callback function.

There is a library for creating a background thread in the browser to run JavaScript on called Web Workers.

There is a lot more hidden gems in this language. Let me know in comments below what you have encountered.

How to store values

JavaScript is dynamically typed which means that x with out specifying its type can be assigned to a number, object, string, array, function or what have you. You don’t need type annotations for your data structures or functions.

flow is a type checker for JavaScript if you are missing static typing.

“Arrays can’t be bothered”

It’s easy to get started assigning variables and just as easy minded are arrays. Arrays in JavaScript are collections of values, arrays can be multi dimensional which means that an array can store an array inside of an array, arrays also don’t care if they store a string, number, boolean, object or all four together in the same array. Lazy guys!

[1,['a'],false,[[{ a: 'b' }]],undefined] instanceof Array // true

The data format JSON and JavaScript objects shares almost the same literal notation. JSON has been adapted as a standard format for data transmission and stands for JavaScript Object Notation and is a record that consists of key-value pairs just like objects in JavaScript.

let obj = {}
obj.hello = 'world'
obj // Object {hello: "world"}
JSON.stringify(obj) // "{"hello":"world"}"

There is a couple of NoSQL databases MongoDB being the most popular document oriented databases that are using the JSON format. If you don’t want to set up your own backend and configure a database then I would recommend firebase, it provides a realtime database and infrastructure for rapid prototyping.

“JavaScript is a mutant”

Data structures are mutable in JavaScript while primitives are immutable. For example:

const obj = {state: 'on'}
obj.state = 'off'
obj // Object {state: "off"}
obj is mutated
var z = 'Hello'
z[1] = 'l' // "Hlllo"
z // "Hello"
z has not been mutated

immutable is a library that provides persistent immutable data structures.

Functional

I wont talk in Lambda terms here. However, I want you to understand that JavaScript has functional aspects built into its core. JavaScript has been a great starting point for me to learn about the functional world. To have the ability to approach code from a functional perspective is one of the reasons why I enjoy working with the language.

JavaScript treats functions as first class citizens to allow functions to be passed around or assigned like any other object.

// Function returning a unix timestamp
function time() {
return new Date().getTime()
}
let assigned = time
assigned() // 1472589264363
assigned() // 1472589272867

Functions are higher order functions in JavaScript, meaning that a function can take another function as its parameter which enables us to do function composition.

const firstChar = param => param.charAt(0)
const toUpperCase = param => param.toUpperCase()
toUpperCase(firstChar('composition')) // "C"

Unlike other functional programming languages JavaScript is not a pure functional language. Meaning that JavaScript allows your functions to have side effects.

Some functions behaves more pure then others when working with the API surface. A little bit of knowledge and discipline helps you to avoid side effects.

Here is what I mean

let x = []
x.push('a')
x // ["a"]
x.length // 1
x.concat('b') // [“a”,”b”]
x // ["a"]
x.length // 1

concat would return a copy of the variable with new values. push would go straight away and mutate the state of the variable.

Another example using the map function

const arr = [1,2,3]
arr.map(i => i*i) // [1, 4, 9]
arr.map(i => i+i) // [2, 4, 6]
arr // [1,2,3]

map will return a new transformed collection of the elements every time it’s executed. If you are like me and curious about how things works under the hood. Here is the magic behind map

Speaking about loops. JavaScript has an imperative side that allows you to write for loops but don’t write your own loops. We don’t have to instruct the computer on how to loop over elements, instead use the benefits of JavaScript being a multi paradigm language, we have access to apply different styles of writing operations. Learning how to apply built in helper functions such as map or forEach speeded up my development and taught me how to write more declarative code.

JavaScript like many other functional programming languages supports a concept called Closures. A closure is a function that is stored and remember its outer environment. Allows you to curry your functions. I wrote a short introduction to closures in JavaScript that you should check out if you are unfamiliar with the concept. Check it out here.

Object Oriented

JavaScript as a multi paradigm language works well for both object orientated programming and functional programming. Objects are prototypal inherited and not classical inherited, if you are coming from a class-based background JavaScript will be a new adventure. We can create objects in JavaScript without classes and objects defines their own behaviour, actually with ES6 syntactical sugar was added to constructor functions to look like classes, but your instances still deals with prototypes under the hood.

You could for example create an constructor, assign a function to its prototype, create an instance and then call the function from the instance via the prototype chain. Our instance would have no internal methods on its own neither its constructor.

class JediAcedemy {
constructor(name) {
this.name = name
}
JediAcedemy.prototype.sayName = function() {
return `Hey, I'm ${this.name}`
}
let luke = new JediAcedemy('Luke Skywalker')
luke instanceof JediAcedemy // true
luke.hasOwnProperty('sayName') // false
luke.sayName() // "Hey, I'm Luke Skywalker"

Objects are linked via the prototype chain and you can reassign the prototype of your objects. It was a new concept for me and it’s important to know how it works to understand how to use the language, specially to get most out of JavaScript. Prototypes makes JavaScript a flexible language that is fun to use. I wrote a short introduction with some examples of how prototypes works, check it out here.

I learned from the scene that there is a debate on how you should create your objects using factory functions vs constructor functions. I recommend you to do some research on the topic and learn about both ways and its constraints. A constructor functions will feel more like home if you are used to classes while factory functions seems to be quite of a JS way of creating objects.

function factory() {
const language = 'JavaScript'
return {
learning() {
console.log(`I'm learning ${language}`)
}
}
}
luke = factory()
typeof luke // "object"
luke.learning() // "I'm learning JavaScript"

As you can see we don’t need the new or this keyword. We are simply assigning a function call to a variable and using the benefits of closures. Really fun and dynamic way of creating objects.

JavaScript like many other object oriented languages supports method chaining. Allowing us to execute a sequence of methods on a specific object. Before we learned how to return the first character of a string upper cased by composing functions. Same result can be achieved from composing methods.

'chain'.charAt(0).toUpperCase() // "C"

Silent Fails

If you are a ninja who writes bug free code then this section is not for you. Big parts of learning a new programming language is to figure out how to debug the language. Specially in JavaScript where your program can break in runtime and throws Uncaught TypeError: undefined is not a function.

“log out all the things”

Log out all the things to the rescue. Sure is there handy debugging tools available, your favourite browser probably has one and you should learn how to use it. Still I use the one and only console.log() (depending on environment) function for logging out what my code is doing, in which context and with which values. Another handy console method that I find neat is console.count(), which allows you to log the number of times count() has been called.

Lets say we have function that compares the value of items

function compareItems(a,b) {
console.count('values compared')
if (a !== b) return 'items value not equal, render item to screen'
}
compare('itemX','item')  // items compared: 1
compare('itemY','itemX') // items compared: 2
compare('itemZ','itemY') // items compared: 3
// ...You get the point

What I think about JavaScript

I find JavaScript to be a really fun language to learn and use. Due to its flexibility, large range of use cases and its lively community. JavaScript feels like a rebel in comparison to many other languages. There is no strict rules or restrictions and lets you focus on being creative productive. I enjoy working with the language but because of its flexibility there is a lot of room for debates. Some strong opinions from the community on best practices will confuse you, but at the end of the day do whatever you want. JavaScript will not complain. Learn its flexibility and start to see its power.

Many people are coming into JavaScript with the mindset of trying to use the language to favour how they are used to program. Instead of adapting the language for what it is and has to offer.

“JavaScript fatigue”

The JS community is very active. Every week you hear about new frameworks, libraries, starter kit, build tools, package managers and services of all kinds. The industry is changing rapidly and it feels overwhelming trying to catch up on all the features. From its large eco system of tools and all the buzz words the term “JavaScript fatigue” was born. I admit that it can be annoying setting up a new project and trying to find and match all the pieces but In my opinion it’s a good sign. It’s a good sign that people are interested in building, sharing, shaping, and pushing innovations forward. There is so much valuable stuff out there for free, ready to be used.

I’m able to share this knowledge and hopefully educate some of you, because I got the knowledge from the community. For free. I encourage everyone to share their knowledge and make programming the best craft in the world!

Enough with all the fun facts, can I make a living as a JavaScript developer? at the time of writing this article. Yes, you most defiantly can. There is a huge need of developers on the market today. It’s a good time for JavaScript. It’s the most popular language, especially for web and soon to be mobile development.

Check out these articles written by Quincy Larson about JavaScripts popularity and job opportunities:
Based on stackoverflow 2016 survey, read here
Based on JavaScript being the most used language on GitHub, read here


What does the future behold for JavaScript

Well, it’s the language of the web after all so it’s here to stay for a while. I hope that mobile development with JavaScript will become much more popular and common. I’m currently very excited to learn and use React Native for building native mobile apps.

A language without a community is a dead language. The JavaScript community as I described before is active and supportive.

Every year from now on ECMAScript will have a new version released. Like it or not we will need to expand our tool box and get used to transforming the new generation of JavaScript to an older one, so the browsers can run our applications. I don’t think that we can count on browsers to keep up the support. There is some interesting ideas of brining macros to JavaScript, you could then create a macro and then load your syntax as a library. At the time of writing this article babeljs is the most popular transpiler. If you are a developer that have not already started to write next generation JS then I don’t know what you are waiting for.

It will become more popular to compile down to JavaScript, There is already ridicules many languages that you could use if you are interested in another style or principles. If you are scared of learning haskell then Elm is a cool kid that compiles to JavaScript, Elm approaches web development from a functional perspective.

JavaScript runs on a single thread and our cpu’s are not getting less cores. Concurrency will become an important topic in the future and a potential issue for the language.

In summary I think JavaScript has a bright future and I’m excited to see how it evolves and to be part of it.

I hope you enjoyed my bias views and that you are now convinced to learn JavaScript. If you have any questions or enlightenments please feel free to drop a comment below or hit me up on twitter.

Lets explore JavaScript for another year, share our knowledge and contribute to the community. And most important, enjoy!