I Know, I Know, I Know This Much Is True (…or False)

So today, we’re talking Booleans. Booleans are, as you’re probably aware, one of two states: true or false. This is a beautiful thing… True or false, black or white, left or right, right or wrong, shaken or stirred, scrunch or fold… Sorry… Let’s digress…

 

Now, with Booleans you have the Logical NOT Operator, represented by our friend, the exclamation point, (the !) What the Logical NOT Operator does is take your object and go all truthy-falsy with it. Basically, the Logical NOT Operator is tasked with finding the logical opposite of whatever your object represents.

So based on the rules I mentioned about what is a truthy value and what is a falsy value we get a series of rules to live by. So let’s take a quick look at Boolean types.

  • If x is true, then !x==false
  • If x is false, then !x==true

This is pretty much the essence of it all… The Logical NOT Operator here acts as a “The Opposite Of…” operator. Opposite of true is false and vice versa… Let’s now push this further to numbers:

  • If x is zero, then !x==true
  • If x is non-zero, then !x==false

Okay, so zero, the only falsy value in the JavaScript natural number system is therefore the only number that will yield true when coerced by the Logical NOT Operator. Subsequently, all other numbers being truthy when coerced by a Logical NOT Operator will yield false. You may recall in one of my previous posts that !0 and !1 have occasionally been used as alternatives to true and false respectively. I will probably go a step further and say that if you were happy to push the boundaries of your code if minimizing or code-golfing, you could technically set specific Booleans to 1 and 0 to represent true and false respectively. Bear in mind the following:

While 0==false and 1==true,
!1===false and !0===true

If you’re scratching your heads about the differences between =, == and ===, let me illustrate it with a very simple set of rules that makes it easy to remember:

  • If you are assigning a variable, you only need the one =
  • If you need to compare values only, you need one more to get ==
  • If you want to compare values and object types, you need one more on top of that to get ===

So, let’s use these rules in a practical example which you can perform in the JavaScript console.

x = “5”; // We’ve set x to a string, typically numeric 5 as a string, NOT the actual number.
x == 5; // You’ll get true

This is because x is compared against the numeric version of the string, forcing the string “5” on the left hand side to be coerced into a numeric 5 to compare against the 5 on the right-hand side. As you’re comparing values, the now-numeric 5 on the left is compared to the existing numeric 5 on the right; 5 is equal to 5… As a result, you’ve got a true statement. But if we try this with === we get something quite different…

x === 5; // You’ll get false

Why do we get false this time around? In this case we’re now adding another level of comparison, we’re comparing against not only value, but object type… We’re comparing a string against a number. As a string is not a number (or vice versa), the === comparison operator fails right there and then, returning false.

So, bear that in mind if you’re thinking of taking some shortcuts with true or false.

So where were we? We’ve looked at Booleans, we’ve looked at numbers… Let’s take a look at strings and the effects of Logical NOT Operators on these:

  • If x is an empty string “”, then !x==true
  • If x is non-empty string like “margarita”, then !x==false

Empty strings are falsy values, and so a Logical NOT Operator on a falsy value will yield true. Consequently, a non-empty string, which is a truthy value when coerced by a Logical NOT Operator will naturally yield false.

Now it’s time for arrays:

  • If x is an empty array [], then !x==false
  • If x is non-empty array like [“margarita”], then !x==false

Herein lies the rub; we may be dealing with an empty array, but it is still a defined array. As a result, it still has value, and is thus truthy, thus ![] will yield false.

Bear in mind that an array with a falsy value as its only element (such as [“”] or [0]) is still a non-empty array, and like all non-empty arrays, will yield false when coerced by a Logical NOT Operator.

Now, back to objects… The truthy little buggers that they are. An object is truthy regardless of whether it is empty or non-empty. Case in point:

  • If x is an empty object {}, then !x==false
  • If x is non-empty array like [“pizza”:”supreme”], then !x==false

So, put simply, JavaScript object types don’t really respond well to change when it comes to coercing them to a Boolean with a Logical NOT Operator…

So, what do we do about the other objects – the dates, the functions, the regular expressions? We can test those out too… So, let’s take a quick look at Dates

!(new Date) // returns false

Why has it returned false? Date objects are truthy. And thus a Logical NOT Operator coercing a truthy value will result in false.

How about regular expressions? They’re truthy as well… Put a Logical NOT Operator in front of a truthy value and you will get false:

!/tic|tac|toe/ // returns false

Lastly, functions… Functions when coerced by a Logical NOT Operator act similarly to how functions behave when coerced by a unary or negation operator, the end result is basically what you get after the operator has acted on the return value of the function. If a function’s return value is truthy, the Logical Not Operator acting upon the function will result in false; whereas if a function’s return value is falsy, the Logical Not Operator acting upon the function will result in true.

Case in point: x = function(y) { return y + 1;}

  • !x == false
    x
    is defined, therefore truthy, thus !x is false.
  • !x(-1) == true
    x(-1) == 0, therefore falsy, thus !x(-1) is true.
  • !x(0) == false
    x(0) == 1, therefore truthy, thus !x(0) is false.

Let’s try a function with no return value: y = function(z) { var x = 17;}

  • !y == false
    y
    is still defined, therefore truthy, thus !y is false.
  • !y(27) == true
    There is no return value for the function, as y(27) returns undefined. Undefined is a falsy value, as a result, !y(27) is true.

So there’s the Logical NOT Operator and how Booleans can be coerced from other objects using it. The final operator of focus is the concatenation operator, which funnily enough is also represented by the + character. I’ll address the concatenation operator in my next post. Stay tuned!

Unary and Negation Operators Part 4 – Dates, Functions and Regular Expressions

I can only promise this post will be quick and painless… Kinda like ripping off a Band-Aid…

There were three final object types in JavaScript that hadn’t been taken into account with regards to Unary and Negation Operators; they are dates, functions and regular expressions… Let’s kick it off with dates…

Thing is with the Date object… One needs to declare a new instance before anything can really be done with it.

+Date // result is NaN

+(new Date) // result at time of running was 1438551674445.000000

Running the latter statement as +new Date works just as well, but for two less characters (see my upcoming post on code golf). But the result is basically the number of milliseconds since Epoch (January 1, 1970 00:00:00) began. So in essence you have a very large number, + and basically make it positive and negative. And that’s all there is with Unary and Negation Operators and date objects.

Next, I’m skipping to regular expressions as functions basically are capable of returning anything, including other functions… But we won’t be going into that… Regular expressions… these are the lovely things that look a bit like this:

/at|gn|mp|sc|-|’|((zi?|t)o|[hts]e|[lrd]ia)$/g

This was part of my entry for distinguishing regions of Italy against American states. Regular expressions are great for matching against certain sets of words, like in the example I’ve linked above. What they can’t do however, is translate well to numbers… Actually, they suck at it… Big time… Take our lovely example from the paragraph or so before…

x = /at|gn|mp|sc|-|’|((zi?|t)o|[hts]e|[lrd]ia)$/g; // x stores the RegExp
+x // result is NaN
-x // result is also NaN

Hmmm… what if, like strings, they were completely numeric? Still doesn’t work, told you before, regular expressions suck at this… they’re great for what they can do, but being coerced into numbers is not one of them:

x = /3456/; // Stored the regular expression of /3456/ to x
+x // NaN… still nothing…
-x // NaN… also nothing…

So, regular expressions are therefore pretty useless when it comes to coercing them into numbers. They’re great for other things, but just not for converting into numbers. So let’s put that to rest…

Finally, functions… Now I will assume that if you’ve been programming for some time that you know how a function works…

x = function (y) { return y*2; }

Simple function, number goes in, double the number goes out.

Now, as you’re dealing with something that provides a return value in this particular instance, +x(5) or -x(17) will provide a response that is basically the Unary or Negation Operator working on the return value. In the case of +x(5), this will return +(10) which will then become 10. -x(17) will return -(34) which will then become -34. If the return value of a function was a string, the Unary or Negation Operator would interact with that to provide the final result, and so on.

So general rule is, if a Unary or Negation Operator is coercing a function, the final product from this coercion is the result of the Unary or Negation Operator acting on the function’s return value.

What if there’s no return value? Let’s test it out with an example:

y = function() { var x = “42”;}

Even expecting a return value on this function is unheard of, and the JavaScript console responds in kind with undefined. Well, when you think about it, that makes a lot of sense. We haven’t defined a return value on y() and therefore the undefined is definitely appropriate!

So bearing this in mind, using a Unary or Negation Operator on a function that has no return value is the same as trying to coerce undefined with a Unary or Negation Operator; and as a result in either case, the result is our lovely friend NaN.

So there’s Unary and Negation Operators sorted. In my next post I’ll move onto other operators, and hopefully provide a quicker run-down on how these other operators affect JavaScript object types.

Until then!

Unary and Negation Operators Part 3 – Arrays and Objects

Are you sitting comfortably? Great! Let’s pick up where we left off!

We talked about the affect of UNOs (Unary and Negation Operators) on Booleans and numbers in my last post. I’ll now talk about arrays and objects and how UNOs affect them.  We’ll be dealing with truthy and falsy values as I did in that last post because now that you know about them, you’ll be able to spot these a lot sooner.

Now, I mentioned that falsy values yield false when coerced to a Boolean, and truthy values yield true when coerced to a Boolean.

When it comes to objects and arrays, a UNO will coerce these “differently” . Let’s take a look:

Empty Objects and Arrays

  • +[] == 0
  • -[] == 0

An empty array is a straight-out falsy value. It will coerce straight to 0 regardless of which UNO you use.

  • +{} == NaN
  • -{} == NaN

Whereas the empty object suffers a crueler fate by not even being able to cast to a number! Even though an empty object’s nature, being truthy, it still becomes coerced to Not a Number. It weird and it sucks, I know, but this is how JavaScript rolls…

“Not-So-Empty ” Objects and Arrays

So let’s see what happens when we put different content in these and then true coerce them with a UNO. The correct way with regards to objects is a key and value pair like {x:y}. Anything other than this or an empty object and we wind up with syntax errors.

+{x:27} == NaN

-{x:27} == NaN

+{x:”eggs”} == NaN

-{x:”eggs”} == NaN

We’re off to a great start here… This doesn’t help us one bit… Objects just simply coerce to NaN with a UNO. The empty object version +{} may help us in the long run (to which I will explain later) but the other instances are simply useless.

Let’s try an array with one element:

+[27] == 27

+[“27”] == 27

+[“eggs”] == NaN

So… Here’s what we’ve learned. Not much either… It’s kinda cool that an array with a number or its equivalent string will both coerce to the said number with a UNO, but trying to do this with any other string in an array – pointless, another NaN. I can see +[] will come in useful later but I will also talk about that and +{} in a future post.

Beyond this, we will conclude by saying that objects of any size or arrays of any size greater than one without a number in numeric or string form will coerce out as NaN. I honestly thought I had more to give on this particular post… Let’s see what we have left… Functions, Regular Expressions and Dates… Let’s hit those in my next post…

Until then!

Unary and Negation Operators Part 2 – Numbers and Booleans

Hi again! Now, last I spoke (er… wrote) I had been going ad nauseum regarding the affects of unary and negation operators on strings. Today, I’ll be focusing my efforts with regards to these same operators but on a few of the remaining objects on the list: booleans and numbers… The others I’ll handle in future posts.

So, Unary and Negation Operators (which I’ll call UNOs for short) yield interesting results when combined with other JavaScript object types. We dealt with strings and the effects of UNOs on them in my last post; so as numbers will be relatively simple I’ll just blitz through this part…

+5 == 5
-5 == -5
-(-5) == 5

Well… Surprise, surprise… The plus and minus do the exact expected thing one would expect in standard mathematics…

The only exception to this is --5. --5 actually won’t evaluate as the -- operator is reserved for pre-decrement and post-decrement of variables, and not numbers… For the negation of a negative number parentheses need to be used, as per my last example.

And that’s UNOs with numbers… I told you it’d be quick…

Now we get to the interesting parts. Let’s start with booleans…

+false == 0
+true == 1


Okay, to understand why coercing false to a number results in zero, and why true is coerced to 1, I need to get into truthy and falsy values… Truthy and falsy values have the following traits:

  • Truthy values will coerce to true when converted to a Boolean. Examples of truthy values are all natural numbers both positive and negative (excluding zero), and non-empty strings, and all empty and non-empty arrays and objects. Basically any value that has definition, is not null, or zero, or empty qualifies as a truthy value (…and empty objects and arrays, I wish someone can explain this to me… That’s just plain weird). True as well counts as a truthy value.
  • Falsy values will coerce to false when converted to a Boolean. Examples of falsy values are zero, empty strings; null, NaN (Not a Number) and undefined. Naturally, false also counts as a falsy value.

So how do you test whether a value is truthy or falsy? You know how they say “two wrongs don’t make a right”? JavaScript have taken this concept and twisted it on its head. JavaScript’s Logical NOT operator (!) converts true to false and vice versa… So combining two of them you have a falsy/truthy operator which is capable of taking any value and determining if it is truthy or falsy. !! spits out true for truthy values and false for falsy values. It really is that easy.

So where am I leading with this? If you’ve been programming for a while, you’ll have come across similar examples of truthy and falsy values at work, probably without you realizing it:

var x=10;
while(x){
   f(); x--;
}

The while loop and the for loop are notorious for abusing the concepts of truthy and falsy values. See that solitary x in our example here? As you will know while loops work off a condition being satisfied to continue running. When the condition is no longer met, the while loop terminates and the code moves on. With each iteration the value of x decreases until it reaches zero. Once it does, the while loop finally converts zero to false and terminates. Similarly, you may have seen the following:

while(true) 

or

while(1)

Both statements mean the same thing… So, it would make sense that true and 1 are considered equivalent to one another logically. In fact, if you were to evaluate !!1 you would naturally get true, and evaluating +true will give you 1. Similarly, because zero is a falsy value you could conclude that !!0 would give you false, and therefore +false would give you 0.

And you’d be right…

Because 0 and 1 are falsy and truthy respectively they can technically be used as shortcuts for false and true respectively. While technically any number or truthy value could be used as a substitute for true, 1 is the simplest and quickest way. This little trick of using 0 and 1 as substitutes for false and true is often used in code golf (which I will cover in a later post) to conserve character usage. Basically, you’re saving 4 and 3 characters respectively.

So as a result:

+false == 0

and

+true == 1

In my next post, I will be addressing arrays and objects and how they react with UNOs. Stay tuned.

Unary and Negation Operators Part 1 – Strings

In my most recent post, I mentioned the various objects that exist in JavaScript, and the operators most commonly responsible for coercing one object type into another.

In this post, I’ll be focusing on the Unary Operator (+) and the Negation Operator ()

+"5" == +(5) == 5

In the above example we see the unary operator acting upon the “5” string resulting in said string being coerced into a number, naturally, the number 5.

Let’s take a look at the process as it happens:

  1. The unary operator upon first encountering the string, checks the nature of the string. In this case, it’s a string which is numeric by nature.
  2. Next, the unary operator coerces the string into its respective number. Note in this case, I’ve placed the 5 in parentheses to show that the 5 has still yet to be further acted upon. This will come into importance in later examples.
  3. Finally the unary operator acts upon the numeric 5 and coerces further with its secondary function, acting as a positive on the numeric 5 we have already coerced from the string. The final result is an unsigned (and thus naturally positive) 5.

Let’s go a step further, now this time with the Negation Operator, the sign.

-"5" == -(5) == -5

In this example we see the negation operator acting upon the “5” string resulting in said string being coerced into a number, in this case, the number -5.

So let’s see what happens this time around:

  1. The negation operator upon first encountering the string, checks the nature of the string. As with the previous example, it’s a string which is numeric by nature.
  2. Next, the negation operator coerces the string into its respective number. Note as with the previous example, I’ve also placed the 5 in parentheses to show that the 5 has still yet to be further acted upon.
  3. Finally the negation operator acts upon the numeric 5 and coerces further with its secondary function, acting as a negator on the numeric 5 we have already coerced from the string. The final result is -5.

If we were to have used the string “-5” instead in these two examples we would get -5 and 5 respectively. Why? Let’s take a quick look.

+"-5" == +(-5) == -5

-“-5” == -(-5) == +5 == 5

So, once the -5 is “cast out” (the supposed technical term for the conversion of one object type into another) from the string, the unary or negation operator performs the respective mathematical operation on the -5 to convert it to -5 or 5 respectively.

So, where does that leave us? Sure, we can cast out numbers until we’re blue in the face. But what about other kinds of strings, what about arrays, objects, dates, booleans? Could we cast out a number from a function?

The answer is yestechnically. What if we had a string that had a combination of letters and numbers, or starting with a number, or numbers at the end, or no numbers at all? Would an empty string cast out?

I’ve taken the liberty of doing these for you. I’ve shown the result after the “//” in each example. Let’s start with strings:

+"7 monkeys" // NaN

NaN means “Not a Number”, even though typeof(+”7 monkeys”) yields “number”, so apparently “Not a Number” is still a number…? Generally +x should for all intensive purposes yield “number”, but because “7 monkeys” or any similar string cannot be completely coerced into a number, Not a Number results. Strangely though, parseInt(“7 monkeys”) and parseFloat(“7 monkeys”) both yield 7. I will talk about these functions in a later post.

-"7 Monkeys" // also yields NaN
+"3+3" // NaN

The above example threw me at first, after all, with +”3+3″ one would think the unary operator would evaluate the string and return 6… Not so. Unary and Negation operators DO NOT evaluate the contents of a string, in fact they don’t evaluate anything. Unary and Negation operators will only do the following:

  • A unary or negation operator will first coerce the object used against the operator to a number based on the content of the object.
  • If the unary operator is used, the system will then work out the resulting number based on standard mathematical rules based on placing a positive sign in front of it.
  • If the negation operator is used, the system will then work out the resulting number based on standard mathematical rules based on placing a negative sign in front of it.
  • Unary and Negation operators will work only on strings that are formatted as recognized numbers within JavaScript.

Note that last point… For a string to be correctly coerced to a number, the initial string has to be formatted like a JavaScript number.

Generally a JavaScript number is formatted in one of three ways:

  • ±A (where A represents a series of integers (containing 1 or more digits)
  • ±A.B (where A and B represent two series of integers (containing 1 or more digits) on either side of the decimal point
  • ±A.Be±C (where A, B and C represent three series of integers (containing 1 or more digits), and e (or E) represents the 10C exponential function. Technically this will be the same as ±A.B × 10±C. So, for example, 7.56e3 = 7.56 × 103 = 7.56 × 1000 = 7560, and 4.2e-2 = 4.2 × 10-2 = 4.2 × 0.01 = 0.042.

One exception to the rule is that a number in JavaScript can be represented with a decimal point but nothing following it. So, +”7.” will coerce into 7, and +”7.e2″ will coerce to 700. but +”7.e2.3″ will render out as a Syntax Error due to the fact that the exponential needs to be an integer, and not in this case, 2.3.

+”foo” // NaN

In the conversion of a string to a number, if the number does not match the conventional JavaScript number formats I mentioned earlier, the only other alternative is for it to render out as Not a Number (NaN).

I will provide further insight into these operators and their interactions with other JavaScript object types in my next post.

Are You My (JavaScript Object) Type?

So there are several object types available in JavaScript as many of you would be aware. For those playing at home, the list is as follows:

  • Array;
  • Boolean;
  • Date;
  • Function;
  • Number;
  • Object (how meta!);
  • RegExp; and
  • String

Each of these objects has a different coercion with one another, and the order that such interactions occurs can also affect the result.

Such coercions are done with JavaScript’s operators, in the form of:

 <OBJECT_A><OPERATOR><OBJECT_B>

The operators commonly used when coercing objects are:

  • The unary operator (+), commonly used for coercing an object to a number;
  • The negation operator (-), not as commonly used as the unary operator, but can also be used to coerce an object to a number;
  • The concatenation operator (also represented by +), used to join strings; and
  • The Logical NOT operator (!), used to coerce an object to a Boolean value.

Now, while these are a small sample of the available operators in JavaScript, these are the ones generally used for coercing an object type into another object type.

I’ll be talking about each of these operators in upcoming posts.

As always, more later!

alert(“Hello World!”);

Hi quirky coders abound!

This blog has been created for the sole purpose of bringing a little JavaScript enlightenment to your lives. My intent for this blog is to provide some insight into the crazy coding quirks of JavaScript, namely in the way of code golf and coercion quirks and how these can be used and abused in your every day code.

I’ll be showing some crazy stuff with every passing post, and I may also get you involved in a little project or two along the way. So, with that little morsel of what this blog is about, I’ll also give you a little intro about myself.

My name is Eliseo D’Annunzio, I’ve been in the IT industry for the past 20 years, and have a love for coding… I love quirky things, and JavaScript happens to fall within that category. I’ve recently been working on a number of projects which involve JavaScript, and I’ll hopefully be releasing a few of these soon. I’ve also been experimenting with the extent that I can code with non-alphanumeric JavaScript, and I’ll be making strong mention of this throughout this blog.

I hope I can educate and entertain you with my own findings and little words of wisdom. Feel free to make the occasional comment or ask a question if you like, and I’ll see to responding to them when I can.

More later!