ES2015/ES6 came with the built in datatypes that are really handy. They’re so handy, that they are part of a strong argument for using ES2015 and transpiling, along with Arrow Functions, block scope, destructuring, spread operators, and defaults. ES2015 includes the Number type. This is super handy for dealing with your numbers in a consistent way across different environments and, as you’ll see, even locales.

To review, last time we talked about the JavaScript Number type, we talked about the Number object and it’s handy qualities, properties and methods. We talked about how the constructor worked: what gets when you use new Number(val). We took a deep dive into the methods on the global Number. So we learned about using Number to check values to see if they’re compatible with numerical calculations. Number also exposes some of JavaScript’s number constants as properties, where different operating environments have proven difficult; where one environment may tolerate larger integers, Number.MAX_SAFE_INTEGER provides a standard way to check against a constant.

This time, we’re going to dive deep in to the instances of Number. We’re going to look at the method on Number.prototype. When we instantiate an instance of number by calling new Number(val), JavaScript is going to take the prototype on Number and attach it to our new number instance. We’re also going to discuss Number compatibility with native Math functions.

We’re going to talk about the Number.prototype.toFixed and Number.prototype.toLocale. There’s other methods, but these two are likely why you’d create an instance in the first place.

Using Number.prototype.toFixed

This works the same way as the old toFixed, which lives on (lowercase) numbers.

Essentially, these two snippets do the same thing:

JavaScript

1

2

3

4

5

varn=5

console.log(n.toFixed(2))// 5.00

varm=newNumber(5)

console.log(m.toFixed(2))// 5.00

If we tried to implement a real program, you’d have a bunch of custom coded checking, formating and alternatives. With the Number type, we can easily implement a standardized way to check for values as we saw in the first part of this series.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

functiontoVariableFixed(data,places){

// set values

data=Number.isFinite(data)?data:0;

places=places||0;

n=newNumber(data);

returnn.toFixed(places);

}

toVariableFixed(4)// "4"

toVariableFixed(4,3)// "4.000"

toVariableFixed("A")// "0"

toVariableFixed("A",3)// "0.000"

To do this with a plain number, you’d either have more blocks or have to do some too-clever logical expressions. Either way, readability and maintainability goes down. Here, we have a number, we check it’s ability to be worked on with the object we’re going to instatiate from. It’s consistent, plain and (probably) fairly safe.

Number also allows you to fail gracefully without try/catch blocks.

1

2

3

4

5

varn="A"

n.toFixed(2)// Returns an error: Uncaught TypeError: n.toFixed is not a function

varn=newNumber("A");

n.toFixed(2)// Returns a string: "NaN"

toLocale

If you work with an international audience, you can use Number to handle your localization and currency.

For instance, if you want a string formated for a known locale, you can do this.

1

2

3

4

n=newNumber(5.25)

n.toLocaleString("en-us",{style:'currency',currency:'USD'})// "$5.25"

n.toLocaleString("en-us",{style:'currency',currency:'EUR'})// "€5.25"

n.toLocaleString("en-us",{style:'currency',currency:'JPY'})// "¥5"

In the case of number internationalization, you can also use the NumberFormat object as part of JavaScript’s Internationalization Object, Intl, if that’s appropriate.

This concept is foreign to many of us US based devs (pun intentional), but these skills are very valuable. Your ability to understand and work with localization (and accessibility) is a very marketable skill in some industries. Does everyone need to be a Localization Master? No, but I do recommend learning the basics of internationalization and localization.

Math and Numbers v. math and numbers v. JavaScript and Numbers

One of the points of confusion I’ve encountered while using Number over simple number values is the way the Number instance appears when you inspect it in developer tools. Consider the following:

JavaScript

1

2

3

4

5

6

// in the console.

vara=newNumber(1);

console.log(a);// Number {[[PrimitiveValue]]: 1}

varb=2;

console.log(b);// 2

This concern isn’t an issue outside of the console. When JavaScript expressions are evaluated or native JavaScript functions and methods are executed, the Number PrimitiveValue is automatically retrieved.

Every few weeks, I catch code where the programmer (sometimes me) is bending over backwards to try to solve a problem that ES6 (or sometimes even older versions of JavaScript) already solves. In fact, the interviewers who interviewed me for my current job, ask interviewees for a method on a built-in datatype that’s been in JavaScript for a long time. No one ever uses the built-in method, we all try to write it from scratch. That experience reminds me to always learn and refresh on the basics of your skill set. The Number type is new-ish, but is widely under utilized for some very common functionality. (It’s not the subject of the interview.)

The ES6 Number datatype. Keep in mind the Number and it’s methods are not available in Internet Explorer and mobile browsers (12% or so of users in December 2016) without shimming or transpiling. If you’re not shimming or transpiling for a professional app, you probably should because of browser compatibility and cross-browser inconsistencies; though there are exceptions depending on your audience and performance requirements of course.

The Number Object goes well with HTML5’s number. There’s not a lot of use of this input because it’s ugly and confusing, but it’s something to keep in mind.

Otherwise, if you’re not sure the value is a number or not, you can use the Number constructor to explicitly and predictably cast it as an instance of Number.

The Constructor of the Number Object

In this example, we convert data from an unpredictable source like a text input or AJAX response.

JavaScript

1

numberObject=newNumber(data);

These result of using this will be mathematically consistent, but the convenience of using the Number datatype is most valuable to prevent the developer from having to think about math. So here’s some common uses:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

newNumber(1)// Number {[[PrimitiveValue]]: 1}

newNumber(1.1)// Number {[[PrimitiveValue]]: 1.1}

newNumber('11')// Number {[[PrimitiveValue]]: 11}

newNumber('11.1')// Number {[[PrimitiveValue]]: 11.1}

newNumber(true)// Number {[[PrimitiveValue]]: 1}

newNumber(false)// Number {[[PrimitiveValue]]: 0}

newNumber(null)// Number {[[PrimitiveValue]]: 0}

newNumber('a')// Number {[[PrimitiveValue]]: NaN}

newNumber('11,1')// Number {[[PrimitiveValue]]: NaN}

newNumber(undefined)// Number {[[PrimitiveValue]]: NaN}

newNumber(void0)// Number {[[PrimitiveValue]]: NaN}

// notice these three throw developers off from time to time.

newNumber(true)// Number {[[PrimitiveValue]]: 1}

newNumber(false)// Number {[[PrimitiveValue]]: 0}

newNumber(null)// Number {[[PrimitiveValue]]: 0}

// but thankfully, there's only one level of implicit conversion.

newNumber('true')// Number {[[PrimitiveValue]]: NaN}

newNumber('false')// Number {[[PrimitiveValue]]: NaN}

newNumber('null')// Number {[[PrimitiveValue]]: NaN}

This is great, it’s predictable: you’re going to get a Number Object and it’s either going to have a value of a number or “not a number.”

Numbers you can use

When you want to see if a value passed as an argument to a function is a usable number? Before ES6 you had the global isFinite function. You can still use it, but it’s hard to remember all of the built in globals, they’re more likely to get written over, but perfectly acceptable. I prefer using the new ones built on the Number object. I like code to be intentional and explicit. Further, there’s potential for JavaScript runtimes to lack the window methods; for instance, NodeJS doesn’t have the window object, if you’re using window[method] notation, your code wouldn’t be reusable unless you account for global[method]. Native run times may eliminate global methods altogether, since they’re not as chained to the Browser API.

JavaScript

1

2

3

4

5

6

// Check to see if a value is safe to use.

if(Number.isFinite(value))...

// is the same as

if(isFinite(value))...

Here’s some examples of what you get using Number.isFinite(value):

JavaScript

1

2

3

4

5

6

7

8

9

10

Number.isFinite(1)// true

Number.isFinite(1.1)// true

Number.isFinite(NaN)// false

Number.isFinite("a")// false

Number.isFinite(Infinity)// false

Number.isFinite(-Infinity)// false

Number.isFinite(undefined)// false

Number.isFinite(1/0)// false

Number.isFinite(null)// false

The first thing you can do is use the Number constructor to explicitly recast strings consisting only of a number to a Number type.

JavaScript

1

2

3

// if you want to accept strings consisting only of a number,

// you can get that by using the Number constructor like this.

value=newNumber(value);

So you can do something like this:

JavaScript

1

2

3

4

5

6

7

8

function(arg){

// if you want to accept strings consisting only of a number...

numberObject=newNumber(arg);

if(!Number.isFinite(numberObject)){

// throw, reject, return, etc.

}

// the rest of your code.

}

Using the number

If you want to work with that number like you would a number literal, you can get the value back by using the “valueOf” method.

JavaScript

1

value=numberObject.valueOf();

You can use the “value” just as you would any number literal or trusted variable. Otherwise, you can use the “numberObject” (the instance of Number holding our value) and all of the methods that live on the instance (covered in future posts).

Other Global Number methods

Number also includes methods for checking a number to see if it is an integer and safe integer.

1

2

3

4

5

6

7

8

9

10

11

Number.isInteger(100)//true

Number.isInteger(-100)//true

Number.isInteger(.1)// false

Number.isInteger(1000000000000000000000)//may be true, may not. I got true.

Number.isSafeInteger(100)// true

Number.isSafeInteger(1000000000000000000000)// false

Number.isSafeInteger(1.1)// false

Number.isInteger(Infinity)// false

Number.isInteger(-Infinity)// false

Number also has methods for the globals isNaN, parseInt, and parseFloat.

Number’s you can’t lose: Constants

My audience is unlikely to use these Constant properties, but here they are:

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

Number.MAX_SAFE_INTEGER// Largest integer guaranteed by all JavaScript runtimes.

Number.MAX_VALUE// Largest number guaranteed by all JavaScript runtimes.

I recently sent out this suggestion to some of my clients. From my client’s perspectives, investing in upgrading libraries can sometimes be a hard sale. It cost money to have people go through and change working code and it opens up the opportunity for new bugs.

Should we upgrade to jQuery 3?

Compatibility with future code. It will be much faster and cheaper to change the website in the future because 3.0 is more standards compliant and is easier to debug. Why is it better?

Method signature and return values changes are sensible and help write more concise code and are easier to debug. Specifically, the $.post/$.get methods now accept options, and that DOM ctor now returns an empty array instead of a null value.

Real Promise support means interoperability with Promise debugging now and Async Functions in the future.

It seems that the Maven installation instructions around the web are convoluted or out of date. (I kept getting: “Error: ACould not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher”) Here’s how I did it with v.3.3.9 on Windows 10, I see no reason why this wouldn’t be the same on Linux or Mac with the relevant parts changed.

1. Download the -bin.zip (the full zip is missing stuff.)(If you’re on linux, use the gunzip file.)

2. Set the JAVA_HOME environmental variable. The dependency on JavaSDK must explicitly be referred to with the environmental variable JAVA_HOME = C:\Program Files\Java\jdk1.x.x_xx (in my case: C:\Program Files\Java\jdk1.8.0_91) or wherever you keep your Java SDK.

3. Unzip Maven, I put my portable executables in C:\tools\ so mine was extracted to C:\tools\maven.

4. Add Maven bin to PATH, in my case C:\tools\maven\bin
(see below this article, if you need instructions on that).

5. Test it out in the command prompt, by typing: mvn -v

And your done!

Errors to Avoid:
1) Older versions required setting M2_HOME, M3_HOME, and/or MAVEN_OPTS. The should be blank and not exist. 2) Tutorials often tell you to install the full file, just download the bin. If you need the rest of Maven, you’ll know you need it and you probably won’t be reading this tutorial.

2) “Error: ACould not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher” is popping up because you’re missing packages, if you install the “full” version, it’s missing this. If you install the -bin version suggested above, it is not missing.

3) Setting/Editing Environmental VariablesIn Windows, it’s easiest to access from the start menu. Open Start and search for (or just start typing) Environmental Variables… and you’ll see suggesstions from Windows to the right place by the time you get to “Envi.” Click one that says something like, “Edit the system environmental variables” or “Edit the environmental variables for your account.”

I like to use the account level, not the system level variables. To change a variable, you click on it and select edit. This will give you a prompt with the variable name and the value. For path, pre-Windows 10 mid-2015, you needed to manually add in the path by editing the PATH variable. c:\existing\paths;c:\existing\paths;c:\path\to\maven\which\you\added

Make a copy and save the existing path if you’re doing it this way. You don’t need to accidentally ruin your PATH variable. No it’s not the worst thing to recover from, but just save a copy first. Make gramps over here happy.

Notice the semicolon before your new one.

Windows 10 makes it even easier. When you edit PATH you get a cool interface that makes it easy to do and hard to mess up.

Command line? Don’t, but if you insist: set PATH=%PATH%;C:\path\to\maven\bin (this adds it to the beginning, this is like doing “path = new + path;” in other languages).Linux/Bash? PATH=/data/to/maven/bin:$PATH

These are some very minimal changes to the standard express.js generated app.js file. It looks nice, “=>” syntax is getting easier to read the more I use and get used to it. Note: I took out a lot of unrelated code to isolate the topic of the blog. This example is for getting a development, learning environment ready to use Babel.js with Express on the back and front ends.

How’d I do it?

Using Babel’s “babel-node” cli tool, its compiling in real time in the development env. For production, do not use babel-node, you’ll want to compile with Babel.js then run with node. Just use “npm install -g babel-cli” and babel-node is already there and built in.

I also included eslint for good measure. Make sure to “npm install –save-dev babel-eslint” and set the parser to “babel-eslint.”

What else do you suggest that can I do to the app.js to take advantage ES6 features, without straying too far from the default?

I hate having to set up complicated environments. I like JavaScript/Front End Development environments to be:

Easy to understand and follow along for everyone on the team.

Quick to get running and make changes.

Free of having to learn new domain specific or pseudo languages for simple building.

Other platforms, Java or .NET, benefit from IDEs because they follow a predefined path and have a set of best practices defined into the language. The ugliness of JavaScript is why it’s powerful. But it can also lead to a lot of unnecessary reinventing the wheel.

Using NPM to use simpleton and replaceable tools keeps my projects fitting those three points above.

NPM is amazing and powerful. I’ve built three major projects now without Grunt or Gulp, using only NPM and locally installed modules.

NPM run.

Shell

1

npm run[command][--<args>]

The run command lets you run a locally installed module from the command line.

sample script in package.json

JavaScript

1

2

3

4

5

6

7

8

9

...

"scripts":{

"test":"mocha test.js"

},

...

"devDependencies":{

"mocha":"*"

}

...

npm run command

Shell

1

npm run test

This runs “mocha test.js”

Scripts can also call one another.

JavaScript

1

2

3

4

5

6

7

...

"scripts":{

"test":"mocha test.js",

"lint":"eslint app.js",

"check":"npm run lint && npm run test"

},

...

In this previous example, “npm run check” will execute lint and test.

You can also use other NPM modules to run and watch the app.

For instance, in the following example, I use babel to convert and bundle the files after the lint and test. Then I run nodemon, which I have executing a custom script. Nodemon is also told to ignore the public directory where babel places the bundle. (I learned the fun way that this creates an infinite loop, if you don’t ignore it!)

Now when I run “npm run auto-start” it won’t just run the lint and tests and launch the app, nodemon will also watch for changes, linting, testing and restarting each time a change is detected.

Building from NPM is incredibly powerful. When I need to change the files or directories, I can do it inside the string. If I want to change the linter, I can change the dependency, and the script for “lint’s” value. Run “npm install” to update the dependencies. Then all the existing “npm run lint” calls will call the new linter. There’s only a tiny amount of configuration and no coding, just a JSON file describing what I want to happen.

Multiple calls to the same NPM module are possible, while using a different command to have different options.

1

2

3

4

5

6

...

"scripts":{

"lint1":"eslint app.js",

"lint2":"eslint **/*.js"

},

...

Finally, the best part about building with NPM way: All that someone on the team needs to do to include this automation or build this app on another machine is clone the files and run “npm install” to get it up and running (if they have Node installed).

When won’t automated building with NPM work? Well, sometimes I have more complex builds, where one area of code might use one set of tools and another area uses some other tools. Some operations are easier to do asynchronously, rather than through piping stdout. What I’ve found myself doing more, is using NPM for my smaller personal modules and I’m still using grunt for my large projects.

Thanks for reading, if you have any ideas, concerns, or complaints please let me know on twitter @StevenLacks or in the comments.

Promises are cool. The best source for Promise API basics is still the API documentation on MDN. Well here’s some news. Promises are awesome and really easy to work with. That article will teach you all about the built in methods, like “all” and “resolve”, we’re going to go over some useful techniques that are not built into the Promise object.

First, let’s do a simple promise.

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

// Create a function to pass the new Promise instance.

// Resolve and reject are how the promise figures out what to do when it's done.

//

// This is a simple time out.

varpromisable0=function(resolve,reject){

setTimeout(function(){

resolve('Hello');

},2000);

};

//Set up the promise, by creating a new instance of Promise passing in our promisable function.

varbasicPromise=newPromise(promisable0);

// Create a function we want to execute when that is done.

// The parameter is the thing you resolved.

functionmyFirstThen(result){

console.log(result);

}

// Now let's use it!

basicPromise.then(myFirstThen);

What if we want to do something sequentially? Promise.all() waits for all of the promised functions, Promise.race waits for one… but a lot of times, we want to run sequences without losing the benefits of asynchronous code.

Chaining thenables in promises

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

varcount=0;

// This example's promisable is the same (with just a different string)

varpromisable=function(resolve,reject){

setTimeout(function(){

resolve('Working');

},2000);

};

varfirstPromise=newPromise(promisable);

// A more complex thenable, returns another promise, each then method makes

You can have very powerful sequences, with non-blocking IO. This is great for real world applications using ES2015/ES6. You could easily replace our timeouts in these examples with AJAX calls, queries to a datastore, complex DOM interactions, or anything else you might want to ensure is done before executing another set of instructions.

Update: Guatom makes a good point (in the comments below), we’re all more familiar with ES2015 concepts, you can avoid using “bind” by using arrow functions, which keep the context of where the function was called. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Previously, I was on the T-Mobile 1GB plan. Towards the end of the month, I’d always hit 1GB, sometimes a day or two early. I realized that the day or two of lost productivity would be worth upgrading to 3GB… so I did… Now, a day or two before the new month, I’m getting the same warnings and I’m hitting 3GB.

Now, my usage probably has increased a bit, but I doubt by 2GB more… and I’m still on wifi most of the time.