JSFiddle - React, Tailwind, and code Playground

by vgulati28

HTML

<div id="error">

</div>

JavaScript

var fname="Vinay";
var lname;
var error;

//Method 1 - Basic way
if (fname == null){
    error = "Method 1 - Please enter the First Name<br>";
} else if (lname == null){
 		error = "Method 1 - Please enter the Last Name<br>";
}

// Method 2 - Check if the variable has value or not
if(!fname){
		error += "Method 2 - Please enter the First Name<br>";
} else if (!lname){
 		error += "Method 2 - Please enter the Last Name<br>";
}

// Method 3 - This will work for any variable that is either undeclared or declared and explicitly set to null or undefined. 
if( typeof fname === 'undefined' || fname === null ){
    error += "Method 3 - Please enter the First Name<br>";
} else if( typeof lname === 'undefined' || lname === null ){
    error += "Method 3 - Please enter the Last Name<br>";
}

// Method 4 - Check if the value is undefined
if(fname === undefined){
		error += "Method 4 - Please enter the First Name<br>";
} else if (lname === undefined){
 		error += "Method 4 - Please enter the Last Name<br>";
}

document.getElementById("error").innerHTML+=error;