I think the answer is no, most languages do not consider "undefined" to be the same as false. Of course it's important to know the particulars of a language to understand how it handles true
, false
, NULL
(or nil
), etc.
You tagged this with Ruby, so here are some Ruby examples:
>> x # raises NameError: undefined local variable
>> x = nil # initializes x and assigns the value nil
>> x == true # false
>> x == false # false (in Ruby nil is not false, but see below)
>> x.nil? # true
>> x ? true : false # false -- Ruby treats nil values as false in conditions
>> x = 1 # now x has a value
>> x.nil? # false
>> x ? true : false # true
As to "why evaluate undefined as false", it can be handy when you need to know a variable is defined before you use it. For example in Ruby you often see this:
if x && x == "some interesting value"
do_important_thing
end
If x
is undefined, the first part of the condition returns false and the statement short-circuits. Which is much cleaner than:
if x.nil?
if x == "some interesting value"
do_important_thing
end
end