Check if a variable is undefined or null

From CodeCodex

Contents

Implementations

The following code examples show how to determine if a variable or object is null.

FreeMarker

<#if variable_to_test??>not null!<#else>null!</#if>

You can also use a ternary-like syntax: <#assign Threshold = 10/>

       <#if "11" > "10">

${"AM greater than"} <#else> ${"AM less than"} </#if> This code will print n/a if x is not defined.

Java

Checking if a variable is null in Java is very easy.

if (variable_to_test==null) {
  System.out.println("variable_to_test is null!");
} else {
  System.out.println("variable_to_test is not null!");
}

JavaScript

Undefined

To check if a variable is undefined use this code:

 
if(typeof(variable_to_test)=="undefined"){ 
  document.write("undefined"); 
}else{ 
  document.write("defined"); 
} 

Or, more simply, you can use:

 
if(!variable_to_test){ 
  document.write("undefined"); 
}else{ 
  document.write("defined"); 
} 

Null

To check if a variable is null, use this code:

 
if(variable_to_test == null){ 
  document.write("null"); 
}else{ 
  document.write("not null"); 
} 

Ruby

The value of the variable confirms nil in the following way.

if variable_to_test.nil?
  puts "variable_to_test is nil!"
else
  puts "variable_to_test is not nil!"
end

The variable judges definition finish with keyword "defined?". ( The kind returns if defined or nil returns ).

class Klass
  attr_accessor :instance_var
  def test
    local_var = []
    p defined? local_var
    p defined? @instance_var
    p defined? @@class_var
    p defined? $gloval_var
    p defined? Const
  end
end

x = Klass.new
x.test

puts
x.instance_var = ""
@@class_var = 0
$gloval_var = nil
Const = "test"
x.test

Output:

"local-variable"
nil
nil
nil
nil

"local-variable"
"instance-variable"
"class variable"
"global-variable"
"constant"