parseInt and Radix

Everyone knows that the parseInt function within JavaScript turns your decimal number or string into a rounded integer. parseInt turns 10.937 into 10, 0.2 into 0, and “someValue” into NaN.  If you use parseInt without a radix, however, you’ll receive a warning that no radix has been provided.  In most cases, the radix you want to use is 10:

parseInt(10.83, 10); // 10, no warning
parseInt(.83, 10); // 0, no warning

parseInt(0.8); // 8, unintended result
parseInt(0.8, 10); // 0, intended result

Using a 10 radix means the number is parsed with a base 10 and thus turns the number into the integer you’re expecting, without the annoying warning.  The radix is important if you’re need to guarantee accuracy with variable input (basic number, binary, etc.).

For best results, always use a radix of 10!

Node server with ES6

Today I was wondering how could I write ES6 code and run it on node so I could write my applications using always the same pattern, no matter if I’m writing Node backend code of React Front-end code.

As a matter of fact, it’s quite simple to convert your node applications to full ES6 using Babel. You just have to add some modules and change some configurations.

First of all, you need to install Babel. We’ll install Babel in the development dependencies since we won’t use it in production. You can do that using the command below:

npm i -D @babel/cli @babel/core @babel/node @babel/preset-env @babel/register

I also needed to install another babel related package in the dependencies, this time in the main dependencies:

npm i @babel/polyfill

You also have to create the Babel configuration file:

$ touch .babelrc

And add this configuration to it:

"presets": ["@babel/preset-env"]

To keep everything organized, I moved my app into a folder called src. That way we can have all the source code and final compiled code into separated folders. I also added some scripts to my package.json to run the build and run the server in development mode using nodemon.

There’s one more thing to change. I just could not use the bin/www script to run the server, so I just copied the file to the src folder and renamed it to server.js.

"scripts": {
"build": "babel src -d dist",
"start": "nodemon src/server.js --exec babel-node",
"test": "echo \"Error: no test specified\" && exit 1"

The build script runs babel and compiles all the files inside of src folder and saves them to dist folder.

The start script runs the server.js file inside src folder passing code thru babel-node to transpile it. This way you can test the code on src folder in real time. Every time you save a file it will recompile and restart the server.

One more thing, if you are using sequelize, it’s best to add another file to the root folder of your application with some sequelize configuration. That’s important because we have moved the source code of the application to the src folder.

Just create a file called .sequelizerc and add the following code to it:

const path = require('path');

module.exports = {
'config': path.resolve('config', 'config.json'),
'models-path': path.resolve('src/models'),
'seeders-path': path.resolve('src/seeders'),
'migrations-path': path.resolve('src/migrations')

Now you just have to convert all of your code to ES6. The conversion is the easy part, you can start by changing all the require calls to import and all the module.exports do export.

If you want to take a look at the boilerplate, check out at github:

What is “use strict” and what does it do?

It’s a common place, when you get into a Js interview, one of the first questions they usually ask is: What is ‘use strict’ and what it does to the application?

I know this is kind of old now, but it still comes up in almost every interview, so let’s talk a little bit about it and really see what it does to the application.

First, let’s take a look at the definition.

JavaScript’s strict mode, introduced in ECMAScript 5, is a way to opt in to a restricted variant of JavaScript, thereby implicitly opting-out of “sloppy mode“. Strict mode isn’t just a subset: it intentionally has different semantics from normal code. Browsers not supporting strict mode will run strict mode code with different behavior from browsers that do, so don’t rely on strict mode without feature-testing for support for the relevant aspects of strict mode. Strict mode code and non-strict mode code can coexist, so scripts can opt into strict mode incrementally.

Strict mode makes several changes to normal JavaScript semantics:

  1. Eliminates some JavaScript silent errors by changing them to throw errors.
  2. Fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that’s not strict mode.
  3. Prohibits some syntax likely to be defined in future versions of ECMAScript.

Now let’s talk about what happens to your code when you enable strict mode.

First, strict mode makes it impossible to accidentally create global variables. In normal JavaScript mistyping a variable in an assignment creates a new property on the global object and continues to “work”. Assignments, which would accidentally create global variables, instead throw an error in strict mode:

test = 'some string'; // create a global variable
console.log(test); // prints 'some string'

Now in Strict Mode

'use strict'
test = 'some string'; // throw an error

As you can see, Strict Mode prevents the application from creating global variables and also prevents you from declaring variables without the keywords let and const.

Strict mode will also prevent global fallback when assigning this to functions. When you call a function without a context, the this of the function will be the global object in normal mode. In Strict mode, this will be undefined. Check out the cobe below:

let test = {
checkThis() {

// calling checkThis with context
test.checkThis(); // prints out { checkThis: [Function: checkThis] }

// calling checkThis without context
let foo = test.checkThis;

foo() // prints out the Global object

Now the same code in Strict Mode:

'use strict';

let test = {
checkThis() {

// calling checkThis with context
test.checkThis(); // prints out { checkThis: [Function: checkThis] }

// calling checkThis without context
let foo = test.checkThis;

foo() // prints out undefined

Another interesting use case showing the behavior above is the following:

(function () {
var a = b = 2

console.log(a); // throws an error saying a in not defined.
console.log(b); // Prints out 2

What happens above is a classic case of a variable been defined in the global scope because it misses the keyword var, let or const. When you write:

(function () {
var a = b = 2

Javascript is actually doing this:

(function () {
var a;
b = 2;
a = b;

If you’re in a clojure like above, the a var will be local and not accessible outside of it, but when you declare b without the keyword var, even inside a clojure, the variable is created as a property of the global object and it is available globally.

Using ‘use strict’ at the top of that code would generate an error saying that you cannot declare a variable without a keyword.

Second, strict mode prohibits with. The code below will throw an error when you run with use strict:

'use strict';
let x = 10;
with (obj) { // error

It also prevent eval from creating variables into the surrounding function or the global scope. In normal mode, variables created inside a eval call leak to the surrounding scope. Check the code below:

eval('var a = 10;');
console.log(a); // prints out 10

Adding ‘use strict’ solves this problem:

'use strict';
eval('var a = 10;');
console.log(a); // variable is undefined

Third, strict mode makes attempts to delete functions, variables or function arguments throw errors where before the attempt would simply have no effect:

var test = '';
delete test;
'use strict';
function foo() {};
delete foo;

Fourth, strict mode prior to Gecko 34 requires that all properties named in an object literal be unique. The normal code may duplicate property names, with the last one determining the property’s value. But since only the last one does anything, the duplication is simply a vector for bugs, if the code is modified to change the property value other than by changing the last instance. Duplicate property names are a syntax error in strict mode:

Fifth, strict mode requires that function parameter names be unique. In normal code the last duplicated argument hides previous identically-named arguments. Those previous arguments remain available through arguments[i], so they’re not completely inaccessible. Still, this hiding makes little sense and is probably undesirable (it might hide a typo, for example), so in strict mode duplicate argument names are a syntax error:

Sixth, a strict mode in ECMAScript 5 forbids octal syntax. The octal syntax isn’t part of ECMAScript 5, but it’s supported in all browsers by prefixing the octal number with a zero: 0644 === 420 and "\045" === "%". In ECMAScript 2015 Octal number is supported by prefixing a number with “0o“. i.e. 

Seventh, strict mode in ECMAScript 2015 forbids setting properties on primitive values. Without strict mode, setting properties is simply ignored (no-op), with strict mode, however, a TypeError is thrown.

Merge Sort Algorithm

The Merge Sort algorithm is one of the most commonly used sorting algorithms in computer science and is also one of the most efficient. It’s based on the principle of Divide and Conquer, and this technique is the basis of efficient algorithms for many problems.

Explaining the concept

A Divide and Conquer algorithm recursively breaks down a problem into two or more sub-problems of the same or related type, until these become simple enough to be solved directly. The solutions to the sub-problems are then combined to give a solution to the original problem.

On a sorting algorithm, the idea is that it’s easier to sort two sorted arrays rather than one unsorted array. Once you have two sorted arrays you can merge them into a single array by comparing their items one by one and adding the smaller item first.

At the end of the sorting we concatenate any left variables at the end of our result list . Since we already sorted the arrays, the last element will always be in the correct position.

The concept is fairly easy to understand but one question still remains. How do we reach a state in which we have two sorted arrays? Well, we can achieve that by splitting the array into halves recursively. We do that until we reach a point in which we compare multiple pairs of single-item arrays.

The code below shows how this works.


[1,9,3,8] [6,5,7,4,2]

[1,9] [3,8] [6,5] [7,4,2]

[1] [9] [3] [8] [6] [5] [7] [4,2]

[1] [9] [3] [8] [6] [5] [7] [4] [2]

You can see how we recursively split the array into smaller arrays until we have only arrays of single items. At that point we start comparing the items one by one and using the above mentioned concatenating method . When the algorithm reaches it’s end, we will have just one sorted array. You can see how the sorting process happens below.

[1]   [9]   [3]   [8]   [6]   [5]   [7]   [4]   [2]

[1]   [9]   [3]   [8]   [6]   [5]   [7]     [2,4]

  [1,9]       [3,8]       [5,6]       [2,4,7]

      [1,3,8,9]              [2,4,5,6,7]


In other words, we split our array to it’s smallest pieces. After that we can assemble them again but in the correct order.

Merge Sort example

Below you’ll see an implementation in JavaScript. It utilizes the built-in slice function in order to get the parts of the array that we need.

const mergeSort = (arr) => {
  if (arr.length <= 1) {
    return arr
  const middle = Math.floor(arr.length / 2)
  return mergeArray(
    mergeSort(arr.slice(0, middle)),

const mergeArray = (left, right) => {
  let result = []

  while (left.length && right.length) {
    if (left[0] < right[0]) {
    } else {

  return [...result, ...left, ...right]

console.log(mergeSort([1,9,3,8,6,5,7,4,2])) // Returns ordered array

As you can see in the code, Merge Sort algorithm implementation is pretty straightforward.

Memoization: Understanding the concept

I’ll go straight to the point here. Memoization is the programmatic practice of making long recursive/iterative functions run much faster.

But how? Well, the speed is achieved by caching function results after its execution so they can be immediately returned the next time the function is called with the same arguments.

Here’s a basic example.

const add = (a, b) => a + b
console.log(add(2,3)) // => returns 5

Every time we call this function, a calculation is going to be performed and a value returned.

Now lets create a simple memoize function that takes another function and modifies it to memoize calls.

const memoize = (fn) => {
  let cache = {};
  return (...args) => {
    let n = JSON.stringify(args);
    if (n in cache) {
      console.log('Fetching from cache', n);
      return cache[n];
    else {
      console.log('Calculating result', n);
      let result = fn(...args);
      cache[n] = result;
      return result;

Now we can easily memoize any pure function, like our add function. Since memoize is a high order function, we have two ways of doing this. One is creating a new memoized function, like below.

const add = (a, b) => a + b;
const memoAdd = memoize(add);
console.log(memoAdd(2,3)); // => Calculating result 5
console.log(memoAdd(2,3)); // => Fetching from cache 5

Or we can change add the function:

const add = memoize((a, b) => a + b);
console.log(add(2,3)); // => Calculating result 5
console.log(add(2,3)); // => Fetching from cache 5

You want to see the performance boost in action? Take a look at this example below.

// recursive fibonacci function
const fibonacci = (n) => {
if (n === 0 || n === 1) {
return n;
return fibonacci(n - 1) + fibonacci(n - 2);

This fibonacci function takes a number, the position number of the Fibonacci sequence, and calculates the corresponding value. Since it’s recursive, it tends to get slower if the position you set gets higher. Lets go nuts here and test it with the 50th element on the sequence, shall we?

console.log(fibonacci(50)); // Call the function and go for a walk!

It took nearly 4 minutes to run the code. The recursive function must be called over 40 billion times (40,730,022,147 times to be specific)! It’s pretty insane.

Now lets memoize it. Since the fibonacci is a recursive function, we can not achieve this by creating a new memoized function, like the code below.

const memoFibonacci = memoize(fibonacci)
console.log(memoFibonacci(50)) // insane amount of time

This happens because we are only memoizing the first call. All subsequent recursive calls to fibonacci are not memoized. The only way to memoize recursive functions is by wrapping the main function with the memoize.

// recursive and memoized fibonacci function
const fibonacci = memoize((n) => {
if (n === 0 || n === 1) {
return n;
return fibonacci(n - 1) + fibonacci(n - 2);

console.log(fibonacci(50)) // runs fast!

Now it runs in less than one second and the results are exactly the same. Amazing! As you can see in the console, a lot os the calls are cached, preventing billions of recursive calls.

Is memoization same as caching?

Yes, kind of. Memoization is actually a specific type of caching. While caching can refer in general to any storing technique for future use, memoizing specifically involves caching the return values of a function.


Keep in mind that memoization does not make sense for all function calls. It does not work well for functions that are not pure, that is functions that have side effects. Memoizing only allows us to cache a result, so any other side effects get lost on successive calls. That said, you can get around this constraint, by returning a function that includes your side effects that you will need to execute after getting the result.

Also, there is a higher memory overhead since we must store our cached results so that we can later recall them as well as an added complexity of using memoization, so it really only makes sense for functions that are computationally expensive.