Ally
Ally

Reputation: 4942

When can a variable be both null and a function?

While tracking down a bug I came across some strange behavior, why does this happen?

Note: For reference this code is a result of my JavaScript code behing compressed with the closure compiler.

In chrome the debugger is paused on the thrown error. And I've fired some lines into the console (see below).

a
> null
B.Ta.Cd[a]
> "Override this" error is thrown
B.Ta.Cd[null]
> undefined

I don't understand that if a is supposed to be null then why the second two lines do not produce the same thing.

Interestingly I wanted to see how a and null differ.

typeof(a)
> "function"
typeof(null)
> "object"

Now I'm wondering how can a be both a function and null?

This video shows the tests in the console

My fix was to check for typeof(a) == "function" then return. But I don't like adding in fixes for issues I don't understand.

Upvotes: 1

Views: 65

Answers (1)

Ally
Ally

Reputation: 4942

Based along the lines of ScottMermelstein's thinking (thanks for the help) it turns out the valueOf function on the a function had been overridden to return null. Therefore trying to see what a is in the console turns out to be quite misleading.

See this fiddle for an example.

Upvotes: 1

Related Questions