Javascript Function Check if a function defines and returns a value

Description

Javascript Function Check if a function defines and returns a value

// A function with an empty return-statement 
// returns undefined 
function function1() { 
         return; 
} 

// A function with no return-statement 
// returns undefined 
function function2() { 
} 

function function3() { 
         return 2 + 2; 
} 
function function4() { 
         return true; 
} 

function function5() { 
         return {}; 
} 

var fn1 = function1(); 
console.log("Function1 returns: " + fn1);         // undefined 

var fn2 = function2(); 
console.log("Function2 returns: " + fn2);         // undefined 

var fn3 = function3(); 
console.log("Function3 returns: " + fn3);         // 4 

var fn4 = function4(); 
console.log("Function4 returns: " + fn4);         // true 

var fn5 = function5(); 
console.log("Function5 returns: " + fn5);         // Object{} 

// Test the return value of function1 
if ( function1() === undefined ) {
   console.log( "Function 1 returns undefined." ); 
} 
else { //w w  w .j  a  v a2  s  .c  o  m
   console.log( "Function 1 returns a value other than undefined." ); 
} 

// Test the return value of function2 
if ( function2() === undefined ) {
   console.log( "Function 2 returns undefined." ); 
} 
else { 
   console.log( "Function 2 returns a value other than undefined." ); 
} 

// Test the return value of function3 
if ( function3() === undefined ) {
   console.log( "Function 3 returns undefined." ); 
} 
else { 
   console.log( "Function 3 returns a value other than undefined." ); 
} 
// Test the return value of function4 
if ( function4() === undefined ) {
   console.log( "Function 4 returns undefined." ); 
} 
else { 
   console.log( "Function 4 returns a value other than undefined." ); 
} 

// Test the return value of function5 
if ( function5() === undefined ) {
   console.log( "Function 5 returns undefined." ); 
} 
else { 
   console.log( "Function 5 returns a value other than undefined." ); 
} 



PreviousNext

Related