JavaScript Series: Approaching problems

You have probably seen big JavaScript functions written using chained code and wondered how on earth can someone memorise so many methods and ensure the program is going to run correctly. Good thing is that you’re going to learn it as you practice. In the meantime, I can teach you how to use basic tools and techniques in order to speed up your learning process.

TL;DR:

  • Think before doing anything else
  • Start with code examples
  • Use documentation
  • Learn to use JavaScript console
  • Solve one problem at a time
  • Improve, rewrite, experiment

The key is simplicity

Everyone with some basic language understanding can write complex code. The difficult part is writing code that is simple where simple means self explanatory, short, understandable.

Think before doing anything else

The key to writing simple code is to think first what you’re trying to achieve before doing anything else.

Start with code examples

Wait, what? Code examples? But we didn’t write any code yet. Correct! Nothing helps better imagine how your code is going to function like code examples do.

Let me bring an example. Given you’d like to implement a function that sorts a collection, how do you start?

 
  /**
   * Sample Usage:
   *
   *   sortItems([])         // => []
   *   sortItems([1])        // => [1]
   *   sortItems([1,1])      // => [1,1]
   *   sortItems([2,3,1,2]); // => [1,2,2,3]
   */
  function sortItems(collection) {
    // No implementation yet
  }
  

See? It’s not that scary, is it? Totally clear what your intentions are. Once you get comfortable writing these sample usages, you can go even further and learn about test driven development. A simple documentation is enough in the beginning, though.

Get familiar with JavaScript documentation

You should know basic JavaScript syntax already. Are there any methods that could help you with implementation? Maybe the problem is solved already, how to find out?

JavaScript evolves quickly nowadays. New APIs come and go. Documentation is your first place to keep up. I personally use and recommend devdocs.io

osoJeDGa83

Every method is well documented with basic syntax, parameters description, code examples and often browser support.

Console to the rescue

Don’t rush things. Solve one problem at a time and I guarantee you that you’re going to learn a lot more.

Explore your variables, explore what methods they support. Compare following experiences:

yltw0R8w4o

KKU1Kit0D7

Isn’t second experience better? There are huge benefits from approaching things one step at a time. As you can see, JavaScript console offers you autocompletion, why not to try other available methods out?

Problems can be solved in many ways

Remember, you can solve problems in many ways. The only way to learn that is through real experience.

Once you write your first implementation of the method, look at things from distance, look as if someone else analysed your code, check if you could potentially solve it in other way. Did you know that method “X" existed? Could you get rid of the “Y" condition in your code? Now that you have code examples, you know what you’re aiming to do. Everyone else does too. Rewrite your code. Improve it. Also, learn about tests, they help too.

Useful References:

JavaScript Series: Two Online Book Recommendations

If you’re learning JavaScript from the ground up you should know there are some great JavaScript books available online for free. You can order their printed versions as well if you prefer it that way.

Even though there are hundreds of JavaScript books and resources available online, I found these two to be especially well written.

1. Eloquent JavaScript (read online)

b907d484-3993-4373-bd2d-9d519b3b19d4

Picture taken from http://eloquentjavascript.net

Chapter 1. Values, Types, and Operators

You’re going to learn about basic JavaScript types with some great, easy to understand examples.

Chapter 2. Program Structure

Once you learn about basic types, you’re going to learn what a program in JavaScript is. This chapter covers variable assignments, basic functions and conditionals and more.

Chapter 4. Data Structures: Objects and Arrays

You probably understand how to construct a simple program now. If you’re willing to learn in depth about functions, you can read the third chapter but my recommendation is to skip it for now and learn about basic data structures like Objects and Arrays. Remember to try things out in the JavaScript console! This is the best way to learn programming.

Chapter 10. Modules

Often when we learn new programming language, we don’t really know to to structure out programs. Shall we write a hundreds lines of code or should we split it to smaller chunks? What are the recommendations? These questions are addressed in tenth chapter of the book. Namespacing, Decoupling, Using Functions as Namespaces, Objects as Interfaces are a good read for the beginning. The other sections can be skipped until you get confident writing JavaScript programs.

2. Speaking JavaScript: An In-Depth Guide for Programmers (read online)

fe966f9c-3e0e-4543-ad88-3fcd47325131

Picture taken from http://speakingjs.com

Chapter 1. Basic JavaScript

In the first chapter you’re going to learn about the difference between JavaScript and ECMAScript (ES), find syntax reference in one place, find out about expressions and statements in JavaScript, learn about variables and basic types in the language (Numbers, Arrays, Strings, Objects etc.). What’s more, some good recommendations about handling exceptions are also included. Then you’re going to learn about strict mode and most common methods in the standard library.

Chapter 7. JavaScript’s Syntax

This chapter pretty much wraps up what we learned in the first chapter. Basic syntax, strict mode plus some quirks.
You can learn more in depth about Math functions, working with Regular Expressions and Array methods in chapters 18, 19 and 21 but they’re a good addition once you grasp the very basics of the language.

That’s it! The recommendations are short on purpose. I don’t want long books to overwhelm you. Now please launch your Mancy REPL and try things out on your own!

JavaScript Series: Asynchronous Code - Control The Chaos

You learned already how to write asynchronous code and as promised it didn’t get too complicated. We’ve touched the basics but the rules apply to a wider range of APIs. It’s time to learn how to control this chaos.

Promises to the rescue

Promises help you control asynchronous behaviour. They help you streamline things, make things behave and execute the way you tell them to. Let’s start off with a simple example:


  Promise
    .resolve({ firstName: 'Charles', secondName: 'Xavier' })
    .then(function (person) {
      console.log(person);
    });

What happened? We created a Promise that always resolves (succeeds). Once it succeeded, we took data it returned and printed out in the console. Promises can either resolve or reject.

2w9DG4erU

Things don’t always succeed, though. Servers crash, request timeouts occur. What can we do to address potential failures?

  
  Promise
    .reject(new Error('Server crashed'))
    .then(function (person) {
      console.log(person);
    })
    .catch(function (error) {
      console.error(error.message);
    });

The code above catches errors that might have occurred when we requested data. As you can see we expected success but prepared for errors.

2wags0Jq6

This probably makes sense already, what else can we do?

Promises not only let you react to success and failure, they also can act as sort of a pipeline for your data. Thanks to method chaining, you can use tiny functions that morph your data step by step.


  Promise
    .resolve({ firstName: 'Charles', secondName: 'Xavier' })
    .then(function (person) {
      return person.firstName + ' ' + person.secondName;
    })
    .then(function (fullName) {
      console.log(fullName);
    })
    .catch(function (error) {
      console.error(error.message);
    });

Did I mention you can chain callbacks as many times as you want? If your tiny functions throw an error at any point, the catch callback will handle it. Doesn’t it look simple?

pbLogIwuP

It doesn’t look like a real-world example, though, does it?

Promises in the wild

A typical callback based API that retrieves User and then queries his Account Balance by user’s id might look more or less like the following code:


  function findUser(username, callback) {
    setTimeout(function () {
      callback({ userId: 1, username: username, firstName: 'Charles', secondName: 'Xavier' });
    }, 875);
  }

  function getAccountBalance(userId, callback) {
    setTimeout(function () {
      callback({ userId: userId, balance: 1500 });
    }, 1250);
  }

  findUser('professor-x', function (userData) {
    getAccountBalance(userData.userId, function (accountBalanceData) {
      console.log('Account Balance equals = ' + accountBalanceData.balance);
    });
  });

Thanks to setTimeout we are able to simulate network latencies (delays). Works as expected:

We can now express the very same thing with Promises.

  
  function findUser(username) {
    return new Promise(function (resolve, reject) {
      setTimeout(function () {
        resolve({ userId: 1, username: username, firstName: 'Charles', secondName: 'Xavier' });
      }, 875);
    });
  }

  function getAccountBalance(userId) {
    return new Promise(function (resolve, reject) {
      setTimeout(function () {
        resolve({ userId: userId, balance: 1500 });
      }, 1250);
    });
  }

  findUser('professor-x')
    .then(function (userData) {
      return getAccountBalance(userData.userId);
    })
    .then(function (accountBalanceData) {
      console.log('Account Balance equals = ' + accountBalanceData.balance);
    });

Doesn’t it look elegant? The first two functions got rid of the extra “callback" parameter. They might have increased in the number of lines but what really matters is how you can benefit from it. The lines at the bottom read "Find professor-x user and then get account balance by his userID and then print the balance".

IJFrSrYV87

Promises bring a lot of order to the chaos. Learn to use them, experiment, try things out. I omitted error handling on purpose but please remember to always catch potential failures.

Promises can do a lot more than this. As a homework, please have a read about Promise.all and Promise.race

Good luck!

JavaScript Series: Asynchronous Code - Introduction

You’re going to often hear that things in JavaScript happen asynchronously from time to time. You’re also going to hear about callbacks, callback hell, race conditions, promises, generator functions and await/async. Plenty of stuff, huh!

Just to explain what all these terms are about - asynchronous code execution might bring a lot of chaos in your application. As you learn, you start using callbacks to execute code when asynchronous action completes, then you learn too many callbacks are literally hell to manage, things often race between each other and happen in random order. There are some ways to control asynchronous behaviour in a manageable way though and you’re going to learn about it soon.

This note is aiming to teach you turning this:

  • Knock, knock!
  • JavaScript!
  • Who’s there?

into this:

  • Knock, knock!
  • Who’s there?
  • JavaScript!

But first, let’s make something happen asynchronously..


  function asynchronousCodeInside () {
    console.log('Synchronous Code');

    setTimeout(function () {
      console.log('Expect Unexpected!!');
    });

    console.log('Synchronous Code Again');
  }
  

What do you expect to happen? Let me answer this question with a screenshot from Mancy REPL:

2vnqBJYPR

Pretty chaotic, right? In fact, it isn’t. You are going to learn soon how to control asynchronous behaviour. Before you learn that, you probably need to know what to control. Below you can find some of the things that execute asynchronously:

  • XHR (AJAX) / fetch calls
  • setTimeout
  • setInterval
  • setImmediate
  • WebWorkers
  • Promise callbacks

There’s plenty more, like file system calls in Node.js for example but I’m not going to touch those at the moment. Once you learn how to control asynchronous behaviour, you can apply these rules to literally anything that happens in the background.

Callback hell and how to get around it

First, to understand what callback hell is, please check and run the following code in your console:


  function callbackHellInside () {
    console.log('Synchronous Code');

    setTimeout(function () {
      console.log('Expect Unexpected!!');
      
      setTimeout(function () {
        console.log('Expect Unexpected Once Again');
      });
      setTimeout(function () {
        console.log('Wait, what?');
      });
    });

    console.log('Synchronous Code Again');
  }

If you don’t have any idea what is going to happen, it’s totally fine. What’s more, the results may vary when you’re making AJAX calls for example. Sometimes one call might return before the other, the other time it might be the other way around.

p3MSZlHbG

You can find results of executing the code above. Believe me or not, there’s plenty applications out there that rely heavily on such code. But we should strive for simplicity. You want to make sure code you write is understandable for others and I’m going to cover this topic in the next note.

Useful References:

JavaScript Series: Cheatsheet

A typical thing you do when starting out with a new language is that you go and learn from tutorials, grab a book or watch some videos.

They often focus on many details of every type found in a language and cover most of the functions that operate on them. Too many details often mean too big cognitive load. We struggle to get small things done, often procrastinate. We read more than we practice. Even today I find myself often reading more than practicing when things seem to be too difficult. And I try to change this behavior and challenge myself to write more code. So if I could give you an advice it would be to get your hands dirty coding!

A thing I personally found useful when learning programming languages was a language reference. A simple one-page summary of the most common patterns found in a language with short explanations. Not too many details, just the code, good and bad parts.

I tried to wrap most common constructs below:


 // 1. Numbers

  1
  -1
  1.15
  -1.15
  Infinity

  // Not A Number - often occurs
  // when trying to parse something
  // that does not really look like a number, e.g. parseInt(null)
  NaN


  /*** Simple operations ***/
  (1 * 2) + (1 / 2) - 1


  /*** Detecting if of a number **/

  // NaN and Infinity included
  typeof myNumber === 'number'

  // NaN and Infinity not included
  Number.isFinite(myNumber)


  /*** Trying to cast to a number ***/
  parseInt('1')    // 1
  parseInt('1.12') // 1

  parseFloat('1')    // 1
  parseFloat('1.12') // 1.12

  parseInt('word');   // NaN
  parseFloat('word'); // NaN

  parseInt('Infinity')   // Infinity
  parseFloat('Infinity') // Infinity

  +'1.12'     // 1.12
  +'Infinity' // Infinity

  
  // 2. Strings

  "A String"
  'A String'

  // ES6 Syntax, can be multiline,
  // not supported widely across browsers
  `A String`
             

  /*** Detecting if a string ***/
  typeof myString === 'string'

  
  /*** Simple operations ***/
  'John' + ' ' + 'Smith'
  `${name} ${surname}` // Given variables name=John and surname=Smith
                       // will output 'John Smith'

  
  /*** Trying to cast to a string ***/
  String(null)      // 'null'
  String(undefined) // 'undefined'
  String(true)      // 'true'
  String(1)         // '1'
  String(1.12)      // '1.12'

  '' + 1.12         // '1.12'
  '' + true         // 'true'

  
  // 3. Booleans

  true
  false

  
  /*** Detecting if a boolean ***/
  typeof myBoolean === 'boolean'


  /*** Simple operations ***/
  false && true  // AND: false
  false || true  // OR: true
  !true          // NOT: false
  !false         // NOT: true
  !!true         // NOT(NOT): true

  
  /*** Trying to cast to a boolean ***/
  Boolean(1);        // true
  Boolean(0);        // false
  Boolean('word');   // true
  Boolean('');       // false
  Boolean(null)      // false
  Boolean(undefined) // false
  !!'word'           // true

  
  // 4. Arrays

  []
  [1,2,3]
  ['an', 'array', 'of', 'strings']
  ['an', 'array', 'of', 6, 'mixed', 'values']
  new Array(1,2,3) // [1,2,3]
  Array(3);        // [undefined,undefined,undefined]


  /*** Detecting if an array ***/
  Array.isArray(myArray)
  // For older browsers try
  Object.prototype.toString.call(myArray) === '[object Array]'


  /*** Simple operations ***/
  [6,5,4][0] // take first element:  6
  [6,5,4][1] // take second element: 5
  [3,2].length // 2
  [6,5,4].indexof(6); // 0
  [6,5,4].indexof(7); // -1
  [6,5,4].includes(4); // true
  [3,2,1].sort() // [1,2,3]
  [1,2].concat([3,4], [5,6], 7) // [1,2,3,4,5,6,7]


  /*** Trying to cast to an array ***/
  [].concat(1);        // [1]
  [].concat('word')    // ['word']
  [].concat(true)      // [true]
  [].concat([1])       // [1]
  [].concat(undefined) // [undefined]
  [].concat(null)      // [null]

 
  // 5. Objects

  {}
  { name: 'John', surname: 'Smith', age: 30 }
  {
    username: 'johnny',
    details: {
      age: 30,
      interests: ['music', 'yoga']
    }
  }
  new Object({ username: 'johnny' })
  Object.create(Object.prototype, { username: { value: 'johnny' } })

  // Important: To evaluate object literals in console
  // you often need to wrap them with parantheses, e.g.:
  ({})
  ({ username: 'johny' })


  /*** Detecting if an object ***/
  typeof myObject === 'object' && !('length' in myObject)


  /*** Simple operations ***/

  // Extends an EXISTING object with a new property
  Object.assign(myObject, { city: 'NY' })

  // Copies an object and extends a COPY rather than original value
  Object.assign({}, myObject, { city: 'NY' })

  // Removes a property from the existing object
  delete myObject.city


  // Trying to cast to an object
  // Not really available, use Object.assign
  // to extend existing objects if needed


  // 6. Functions

  // Function Declaration
  function add(x, y) {
    return x + y;
  }

  // Function Expression - Anonymous (nameless) function gets assigned to a variable
  var add = function (x, y) {
    return x + y;
  }

  // Functions don't need to take parameters
  function () {
    return 1;   // returns a value
  }

  // Functions don't need to return
  function () {
    doSomething(); // does something but does not return
                   // returning value is `undefined`
  }

  // ES6 Arrow functions
  var add = (x, y) => {
    return x + y;
  }

  // ES6 Short Arrow functions
  // Use when you want to only return in the function
  var add = (x, y) => x + y;

  // IIFE (Immediately Invoked Function Expression)
  var result = (function () {
    return 1 + 2
  }()) // 3


  /*** Binding context - `this` ***/
  function age() {
    return this.age;
  }

  // Returns a FUNCTION that can be then called
  age.bind({ age: 30 })
  // Calls the function, returns 30
  age.call({ age: 30 })
  // Calls the function, returns 30
  age.apply({ age: 30 })

  // Important: You CANNOT bind `this` context to an arrow function.
  // Returning value will be `undefined`
  (() => { return this.age }).call({ age: 30 });


  // 7. Other (undefined, null)

  undefined
  null

  // Simple operations
  undefined == null  // true
  undefined === null // false

Just to make it clear - most of the sophisticated operations with these types are not covered in this cheatsheet on purpose. Learn simple things first, then broaden your knowledge. Once you get the basics, we can move on to more advanced language constructs.