The Reasons behind WAT in JavaScript: Explanation and Solutions

WAT Javascript has known because of the talk shows that represents serious opinion with regard to software.

If you have some experience in the JavaScript community, you may have encountered Gary Bernhardt’s famous “Wat” A lightning talk.

If you’re a bit confused and you haven’t seen the video. I’ll give you an overview.

Overview of the video

At CodeMash 2012, A lightning talk, Gary Bernhardt discusses the unexpected behavior found in Ruby and JavaScript.

Around two minutes into his presentation, he humorously criticizes JavaScript using sarcasm to make his point.

Let’s take a look at what he’s trying to illustrate, and also he gives illogical operations:

  1. What is the return value of Array + Array?
[] + [] = ''
Array + Array = Empty string

  1. What is the return value of Array + Object?
[] + {} = '[object Object]'
Array + Object =   '[object Object]'

  1. What is the return value Object + Array?
{} + [] = 0
Object + Array = 0

  1. What is the return value of Object + Object?
{} + {} = NaN
Object + Object =  NaN (not a number) 

  1. What is the return value of the following expression?
Array (16)
,,,,,,,,,,,,,,,
 
Array(16).join(wat)
watwatwatwatwatwatwatwatwatwatwatwatwatwatwat

Array(16).join("wat" + 1)
wat1wat1wat1wat1wat1wat1wat1wat1wat1wat1wat1wat1wat1wat1wat1

Array(16).join('wat' - 1) + ' Batman' = 'NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN Batman'

He added a few words before the video ends he says WATMAN! And, everyone laugh.

Honestly, in my own opinion, the way JavaScript’s addition operator works can lead to some unusual outcomes in specific cases.

I hadn’t considered looking into this behavior before and I was quite surprised to find out that not only were all three of my answers incorrect, but the correct answers themselves were quite unexpected.

Now, let us understand in a deeper way the WAT in JavaScript.

Understanding JavaScript WAT

JavaScript approaches it differently, but that doesn’t necessarily mean it’s incorrect.

Let’s start with the basics. In JavaScript (JS), there are five different types of values that you can immediately declare. These are the building blocks for storing information:

1. Numbers

These can be whole numbers (like 1 and 2), decimal numbers (like 3.14), or special values like NaN (which stands for “not a number”) and Infinity.

2. Strings

These are sequences of characters enclosed in either single quotes (‘abc’) or double quotes (“abc”). They are commonly used to represent text.

3. Booleans

There are only two values here: true and false. Booleans are useful for expressing conditions or binary choices.

4. Objects

These are collections of key-value pairs, enclosed in curly braces “{}.”

Objects allows you to store related information together, such as a website’s name and what it offers: {website: “Itsourcecode”, Offers: ‘Free sourcecode and tutorials}.

5. Arrays

These are ordered lists of values, enclosed in square brackets “[].”

Arrays can contain various types of values, such as numbers, strings, or even other arrays: [1, 2, 3, 4, 5 “Hi, Welcome to Itsourcecode!”].

Among these types, booleans, numbers, and strings are considered as fundamental values.

Additionally, there are two special primitive values: undefined, which signifies the absence of a value, and null, which represents the intentional absence of any object value.

Here are the solutions from the example of JavaScript WAT in Bernhardt’s talk.

Array + Array = Empty string

const array1 = [];
const array2 = [];
const result = array1.toString() + array2.toString();

console.log(result);

In the example code, we declare two empty arrays, array1, and array2.

We then convert both arrays to strings using the toString() method and concatenate them together using the + operator.

Finally, we log the result, which will be an empty string.

Output:

Empty  string 

Array + Object = ‘[object Object]’

const array = [];
const object = {};

const result = array.toString() + object.toString();

console.log(result);

In the example code, we have an empty array and an empty object object.

We call the toString() method on both the array and the object, and then concatenate them using the + operator.

Since an empty array is represented as an empty string (”) and an empty object is represented as [object Object], the concatenation of ” + ‘[object Object]’ results in [object Object].

Output:

[object Object]

Object + Object = NaN (not a number)

const object1 = {};
const object2 = {};

const result = Number(object1) + Number(object2);

console.log(result);

We convert both object1 and object2 to numbers using the Number() function.

Since objects cannot be directly converted to numbers, the result of both conversions will be NaN.

By adding these two NaN values together using the + operator, we obtain the output NaN.

Output:

NaN

Object + Array = 0

let result = +Number([].toString());
console.log(result);

In the example code, a variable named “result” is defined.

Its value is obtained by converting an empty array into a string using the toString method and then converting that string into a number using the Number function.

When an empty string is converted to a number, it becomes 0. So, the final value assigned to “result” is 0.

Output:

0

Two Empty array are the not the same

When we compare two empty arrays in JavaScript, they are not considered equal because they are separate objects.

However, something interesting happens in the next line of code that catches our attention.

It seems that JavaScript allows for a peculiar scenario where the variable “a” and its negation, “not a”, can be equivalent to each other.

This might seem implausible, right?

[] == [] // false 
[] == ![] // true

Deeper explanation:

In JavaScript, an empty array is treated as true or “truthy.” So, when we evaluate the expression “![]” (which means “not an empty array”), it surprisingly results in false.

Now, using the loose equality operator, JavaScript attempts to compare the empty array with false, but treats them as if they were numbers, even though neither of them actually is.

During this comparison, the empty array is coerced into an empty string, which is then further coerced into zero. Similarly, false is also coerced into zero.

Since both resulting zero values are identical, the comparison ultimately yields true. This behavior can be unexpected and might bring a confusion.

Array plus (+) Object

When you use the expression [] + {} in JavaScript, it produces the string “[object Object].”

However, it’s essential to understand that this result is not an actual object itself.

It is merely a string with the specific value of “[object Object].”

To demonstrate this point, here’s the example:

var myVariable = [] + {};
 
myVariable.name = "Itsourcecode";
myVariable.visits = 30000000;
 
typeof myVariable; 
console.dir(myVariable);

Output:

'[object Object]'

Double equal sign (==) and triple equal sign (===)

The rules governing type conversion can be intricate, difficult to remember, and sometimes even incorrect, as you’ll soon find out.

That’s why it’s generally advised against using the “==” operator. Instead, it’s better to use “===” (triple equal sign) operator.

The “===” operator adheres to a more reliable approach known as ECMAScript’s Abstract Equality Comparison Algorithm, which helps avoid the pitfalls of type coercion.

While some people may not favor the “===” operator because it appears 50% sillier than “==” and twice as silly as the simple “=” (equal sign) operator, it remains the correct and safer choice for performing equality comparisons in JavaScript.

Conclusion

In conclusion, this article explores the WAT in JavaScript, as discussed by Gary Bernhardt in his lightning talk.

It explains the surprising behavior of JavaScript’s addition operator and provides clear explanations for the unexpected outcomes.

The article also discusses the fundamental data types in JavaScript and emphasizes that JavaScript’s approach may differ from other languages but isn’t necessarily wrong.

Overall, it encourages readers to understand these quirks to write better JavaScript code.

We are hoping that this article provides you with enough information that helps you understand the JavaScript WAT

You can also check out the following article:

Thank you for reading itsourcecoders 😊.

Leave a Comment