Javascript Fundamentals: Number Datatype Part II

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.

You can see all the methods on the Number Instance here.

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:

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.

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.

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.

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:

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.

 

 

 

JavaScript Fundamentals: Number Datatype Part I

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.

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:

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.

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

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

So you can do something like this:

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.

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.

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:

Next time, we’ll look at some of the instance methods on the global Number object.

Should you upgrade to jQuery 3?

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?

  • JQuery 3 aggressively implements newer web standards. This means jQuery code and non-jQuery code(plain JavaScript/DOM/Browser APIs) will be more easily interchangeable. Specifically, on AJAX URLs, DOM manipulation, and Promises.
  • Animation performance will greatly improve.
  • 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.

Upgrading to 2/3 will lose pre-IE9 support, but practically no one uses IE8 and older (.1% of all usage): http://www.w3schools.com/browsers/browsers_explorer.asp

https://jquery.com/upgrade-guide/3.0/

(Note, for you, the Blog Reader, this may be different, depending on what projects you work on).

Most likely areas for changes:

  • AJAX method changes. Drop success/error/complete for then, catch, done, fail, and always.
  • $.removeAttr use when it should be $.prop(attr, false)
  • Use of the $.param method

Installing Maven (2016)

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 Variables
In 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

Gulp/Babel-loader and Webpack in Visual Studio Code

Sample VS Code config files for gulp-babel-loader.

gulpfile.js

These two lines aren’t needed in node gulp apps, but they make errors (cannot resolve module ‘myModule’…) in VS Code.

package.json

tsd.json

jsconfig.json

tasks.json

T-Mobile Data Usage

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.

Has anyone else had this experience?

Are these the simplest`Template Strings` in ES6 (JavaScript)?

Instead of a quote, wrap your string in back-ticks ` (on QWERTY this is just above tab, it shares a key with the tilde ~) to make a template string.

Works on: Chrome 41 or greater, Firefox 34 or greater, not currently in IE. Let me know if this is working in the Spartan preview, I’m the biggest windows fan without Win10 installed.

First, let’s check out the console.

Next, in a web page. Here’s a really simple demonstration of the ES6 template string being implemented in the DOM .

 

ES6/HTML5 Import Demo and Tutorial (Video)

“HTML import” is a well put together way to bring in HTML from other files. It uses minimal JavaScript to make it happen natively, and it’s only a matter of time before someone writes a nice little library on making that happen in a way that appears to be magical for designers.

Mozilla’s not supporting them, but now that I’ve used it, I’m think that this syntax was well thought out and will be easily shimmed. (I know you hate shims, but this is really small and should package nicely.)

First, note that this isn’t going to work serving it locally right from your file system. In other words, you can’t just open your HTML files in the browser from the file explorer. If you don’t know how to set up a server, then this might be a bit too advanced for you anyway. No offense, I still suck at that stuff. (why I work as a front ender!) Continue reading “ES6/HTML5 Import Demo and Tutorial (Video)”

How to Install Firefox Developer Edition on Ubuntu Linux (Debian)

Firefox Developer Edition Logo
Great free dev tool

Firefox developer edition has a lot of cool tools to help web developers, designers, and those who want to build for FirefoxOS.  Of course, on Linux, it’s a little harder to install for those who don’t have a lot of experience in the command line, right now. It’s a really easy install, once you know your way around a bit more. This tutorial is assuming your using default settings in Ubuntu/Lubuntu/Xubuntu.

Go here: https://www.mozilla.org/en-US/firefox/developer/

You’ll be presented with various versions available to run in Linux, if you’re using Ubuntu, you’ll want the Debian flavor in either 32- or 64-bit. 32-bit will run on either, so unless you know you’re on 64- bit get the 32-bit. Continue reading “How to Install Firefox Developer Edition on Ubuntu Linux (Debian)”