JavaScript Patterns [Ch.1: Introduction]

JavaScript Patterns [Ch.1: Introduction]

Build Better Applications with Coding and Design Patterns

Featured on Hashnode

So a couple of weeks ago I come across a very interesting book titled
JavaScript Patterns by @Stoyan Stefanov which has a very good reputation, the book discusses a number of different design, coding, and anti-patterns related to JavaScript which intended to increase your code quality, scalability, and maintainability

A couple of days ago one of my colleagues at @Instabug mentioned it again in one of our talks, So I said that it's a good time to start reading it!

I started reading and then I decided that it would be better to write a form of summaries or personal notes so to speak based on the book, So without further ado, Let's Get it Started


Patterns

📔 Patterns definition

In software development, we define a pattern as "a solution to a common problem" which is not necessarily to be a code solution but more of a best practice, a useful abstraction, and a template for solving categories of problems

🎯 Importance of patterns

  • They provide a level of abstraction
  • They help us write better code using proven practices
  • They improve communication between developers, Putting a label on coding technique makes it easier to make sure we’re talking about the same thing

🏷 Types of patterns

In the book we will be discussing the following types of patterns in details:

🧩 Design patterns

Design patterns are general repeatable solutions to commonly occurring problems in software design

Examples of design patterns are singleton, factory, decorator, observer, and so on

The thing about design patterns in relation to JavaScript is that, although language-independent, the design patterns were mostly studied from the perspective of strongly typed languages, such as C++ and Java which sometimes it doesn’t make sense to apply them in a dynamic language such as JavaScript

👨‍💻 Coding patterns

The coding patterns are much more interesting; they are JavaScript-specific patterns and good practices related to the unique features of the language

👻 Anti patterns

Antipatterns have a bit of negative or even insulting sound to their name that needn't be the case, so it's better to define anti-pattern as:

Common approach that causes more problems than it solves


JavaScript: Concepts

In this section, we will not really have that much new information but we will get a good recap of the main concepts in JavaScript before we go into more detailed discussions

🐶 Object-Oriented

JavaScript is an object-oriented language, Almost anything you look at in a piece of JavaScript code has a good chance of being an object

Only five primitive types are not objects: number, string, boolean, null, and undefined, and the first three have corresponding object representation in the form of primitive wrappers

✍ What's an object?

  • an object is just a collection of named properties, a list of key-value pairs
  • an object can have methods, simply when a value of a property is a function
  • an object can be modified (almost) anytime, its properties can be added, removed, and updated
var person = {
  firstName: "John",
  lastName : "Doe",
  id       : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};

🏷 Types of objects

There are two main types of objects:

  1. Native: Described in the ECMAScript standard
  2. Host: Defined by the host environment (for example, the browser environment)
// native objects
// can further be categorized as built-in or user-defined
var person = {};
var d = new Date();
var cars = new Array("Saab", "Volvo", "BMW");

// host objects
history
window
location
document
XMLHttpRequest
setTimeout

🐾 Prototypes

👨‍👦 Inheritance in JavaScript

Before ES5, JavaScript does not support inheritance natively, although this was just one way to reuse code, Inheritance can be accomplished in various ways, which usually make use of prototypes

Component 61.png

🧱 Prototype definition

A prototype is an object and every function you create automatically gets
a prototype
property that points to a new blank object

This object is almost identical to an object created with an object literal or Object() constructor, except that its constructor property points to the function you create and not to the built-in Object()

We’ll discuss inheritance in detail, but for now, just keep in mind that the prototype is an object and every function has a prototype property

🌋 Environment

JavaScript programs need an environment to run where the browser is the most common one but don't worry most of the patterns we will discuss are environment-agnostic

Environments can provide their own host objects, which are not defined in the ECMAScript standard which might have unexpected behavior

🗞 ECMAScript 5

The core JavaScript is based on the ES (ECMAScript standard), ES5 adds many new built-in objects, methods, and properties to the language:

The most important one is *strict* mode which actually removes features from the language, making the programs simpler and less error-prone

👮‍♂️ Strict mode

The following code in the function is executed in the strict subset of the language.
For older browsers, this is just a string not assigned to any variable, so it’s not used, and yet it’s not an error

function my() {
    "use strict";
    // rest of the function...
}

EXAMPLE:

function sum(a, a, c) { // !!! syntax error
    'use strict';
    return a + a + c; // wrong if this code ran
}

Starting from ES6, all modules are always in the strict mode so you don't need to add 'use strict' explicitly

📏 JSLint/JSHint

JavaScript is an interpreted language with no static compile-time checks, This is where JSLint helps

JSLint is a JavaScript static code analysis tool used to ensure the quality of your code that inspects your code and warns about potential problems also note that all the code in the current/following articles successfully passes JSLint’s check

Having no JSLint error in your code also helps you be more confident in the code

🚦 Console

The console is not part of the language but part of the environment and is present in all current browsers, console object has many methods you can check them from here

image.png

console.log("Hello world!");

console.info("Hello world!");

console.warn("This is a warning!");