Why does JavaScript even have null?

JavaScript has its quirks and difficulties. One of them is null & undefined. If there’s undefined, why does JavaScript even have null?

Equality

Let’s start exploring null and undefined by having a look at the following comparisons:

null >= 0; //true
null <= 0; //true 
null == 0; //false 
null > 0;  //false
null < 0;  //false

How can null be bigger or equal to zero, less or equal to zero, but not be equal to zero?!

To understand this we have to know how JavaScript handles these comparisons. There are two different kinds of operators used in the example above: _Equality Operators_  (==, ===, != and !===) and Relational Operators (>, <, >= and <=).  And both work differently.

Equality operators compare at an object level. If both _operands, _the things left and right of the operator, are of different types a strict comparison (=== or !==) is used. Because null is an object and 0 is a number they are not equal.

In the case of Relational Operators, both operands are converted to the same type. In the example to a number. Under the hood, JavaScript is doing the following:

Number(null) >= 0; //true

Which makes much more sense. Number(null) return the value 0 and 0 is equal to 0.

Let’s try the same examples with undefined:

undefined >= 0;//false 
undefined <= 0;//false 
undefined == 0;//false 
undefined < 0;//false
undefined > 0;//false

First thought would be that this should result in the same outcome. Although JavaScript is doing the same, the result is different. Again, JavaScript is converting undefined to a number, but Number(undefined) is not 0 but NaN. The JavaScript spec says that every comparison with NaN results in false, even a comparison with NaN.

There’s even a little bit more to the _comparison algorithm _than this, but this explains the idea.

Why null?

Does JavaScript need a null value? Though it would be possible to write an entire application without using null, and often it does, there is a place for null. The difference in usage is intention. A null value is intenionally abcent, where an undefined value is often unintentional and just the default value.

For example in a function retrieving a piece of data. When that data isn’t there, this function returns null. Otherwise, it returns the data. This way one can tell if the value is returned by the function and is set to null or if the variable that should contain the result isn’t set at all.

In other words: null !== undefined

 

 

Keep your password safe!

I’m currently working on a short course on web security. In this course, I’m going to show a couple of common mistakes in websites that create gaping holes. I’d like to give you a small tip in advance, just to make you more aware of what you are doing when you hit that ‘remember my password’ button in your browser.

Although I’m pretty sure your browser itself keeps the password safe, it has to place it in the password field of the login form to be able to submit it. With this small trick you, (and anyone else that might sit behind your pc), can read it again…

When the username is selected and the browser has filled in the ‘ * ‘ in the password box, right click the password box and hit inspect.

In the inspector go to the console and type: $0.value

Et Voila, your password is exposed.

The ‘$0’ refers to the selected element in the inspector. ‘value’ just writes the value property on that to the console. In this case, the password is in there.

 

 

 

Progressive Enhancement

Since last December I’ve been giving talks about Progressive Web apps. A couple of them where lightning talks of 10 minutes. One of the things I had to remove to fit the slides and the demo into those 10 minutes was the explanation of Progressive Enhancement, although it’s in the definition of a PWA. So, let me explain…

Progressive Enhancement

Start with a strong base and enhance from that. You want to deliver the best possible experience for the widest possible audience. That’s your base. If the browser of your visitor supports more, great! Than his/her experience will be even better.

Here’s an example taken from my demo code:

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js').then(function (registr) {
    console.log('successful with scope: ', registr.scope);
  }).catch(function (err) {
    console.log('ServiceWorker registration failed: ', err);
  });
}

In this case a feature detection is used to check if a _ServiceWorker _exists on the navigator object. If there isn’t, no hard feelings and the site will work as expected. If the service worker object is available then just register one. From that point on the user gets an even better experience, like offline support for example.

Update

I posted the samplecode to my GitHub.

Styling console.log output

I recently learned about a very cool console.log feature. You can use CSS formatting to style the output of console.log. And it’s very easy. All you have to do is use the ‘ %c ‘ formatting tag in your message. Here’s a simple example:

console.log('%cThis is a %cfun%c console message',
            'font: 24px serif; font-weight:100; color: #228;',
            'font: 30px sans-serif; font-weight:800; color: #F44;',
            'font: 24px serif; font-weight:100; color: #228;'
        );

When you look in the console of the browser, you should see something like this:

fun-console-message

Unfortunately this features is not supported in all browsers, which may result in a whole bunch of CSS being written to the console. You should check the browser in your code before using this feature. As far as I know only Chrome and Firefox support this feature.

Quick note on WinJS templates and controls

Today I was working streaming (https://livecoding.tv/sorskoot) building my new JavaScript Audio Workstation. I wanted to use a template in a custom WinJS control but found it wasn’t in the samples.  Also, the MSDN documentation contained an error which made it even harder to get it to work.

Here’s an example:
(function () {
  WinJS.Namespace.define('jsaw.ui', { 
    menuBar: WinJS.Class.define(
      function (element, options) {
        this.element = element || document.createElement('div');
        this.element.winControl = this;
        this.options = options;
        this.createControl();
    }, {
      createControl: function () {
        WinJS.UI.Fragments.render('./app/templates/menubar.html',
                                  this.element)
                          .done(
                                /* Your success and error handlers */
                          );
      }
    })
  });
  WinJS.Class.mix(jsaw.ui.menuBar, WinJS.Utilities.eventMixin);
})();
In this example I create a WinJS class in the jsaw.ui namespace. This class has a constructor function (line 4) that calls the createControl function. In that function (line 10), a fragment is rendered. This fragment serves as a template for the control. All HTML in that control will be rendered and it will be cached as well. Note, that the Fragments object is in the UI namespace.