JavaScript isset() function [duplicate] - javascript

This question already has answers here:
JavaScript isset() equivalent
(28 answers)
Closed 6 years ago.
How to check isset in javascript.
I have used in the following way.
var sessionvalue = document.getElementById('sessionvalue').value;
if(Here I have to check if isset the sessionvalue or not){
if(sessionvalue == "" || sessionvalue == null)
{
document.getElementById('sessionvalue').style.borderColor="red";
return false;
}
else
{
document.getElementById('sessionvalue').style.borderColor="#ccc";
}
}

When javascript variables are not declared and you try to call them, they return undefined, so you can do:
if (typeof sessionvalue == "undefined" || sessionvalue == null)

You can just do:
if(sessionvalue)
The above will automatically check for undefined, null (And NaN ,false,"")
You can even make it a global function if you need it like you're used to in php.
function isset(_var){
return !!_var; // converting to boolean.
}

if(typeof(data.length) != 'undefined')
{
// do something
}
if(empty(data))
{
// do something
}
if(typeof(data) == 'undefined' || data === null)
{
//do something
}

you can just do if(sessionvalue) that's it you don't need anything else and remember you can compare apples with cars in javascript, you can check if value is null or undefined with if(sessionvalue) or if(!sessionvalue), your code will be :
document.getElementById('sessionvalue').style.borderColor= sessionvalue ? "red" : "#CCC";

Try Code as below
var sessionvalue=document.getElementById('sessionvalue').value;
if(typeof sessionvalue != 'undefined'){
if(sessionvalue=="" || sessionvalue == null)
{
document.getElementById('sessionvalue').style.borderColor="red";
return false;
}
else
{
document.getElementById('sessionvalue').style.borderColor="#ccc";
}
}

Related

how to check a deeply nested object is undefined? [duplicate]

This question already has answers here:
How to avoid 'cannot read property of undefined' errors?
(18 answers)
How can I check for "undefined" in JavaScript? [duplicate]
(16 answers)
Closed 2 years ago.
I would like to check whether an object is undefined
this.state.data.value[0].name
I attempted the following
and these will say Type error this.state.data.value is undefined in the console.
if(typeof this.data.value[0].name=== "undefined"){
//do something
}
if(this.data.value[0].name == undefined){
//do something
}
if(!!this.data.value[0].name){
//do something
}
if(!this.data.value[0].name){
//do something
}
if(this.data){
if(this.data.value){ // It says type error, this.state.value is undefined in the console.
}
}
How shall I check the object this.state.value[0].name is undefined?
I attempted this
if (typeof (this.data) !== undefined) {
debugger;
if (typeof (this.data.value) !== undefined) {
debugger;
if (typeof (this.data.value[0].name != undefined)) {//cannot read value [0]
debugger;
}
}
}
My Solution, thanks to pranav-c-balan
if (this.data && this.data.value && this.data.value[0] && this.data.value[0].name) {
return true;
} else {
document.getElementById("myDIV").innerHTML =
"<b>Custom Error Text</b>";
return false;
}
A working Example
let data={};
data.value=[{name:123}];
function checkValue(){
if(data && data.value && data.value[0] && data.value[0].name){
return true;
}else{
return false;
}
}
let correct=checkValue();
if(correct){
console.log("This is valid, data.value[0].name Exist");
}else{
console.log("This is invalid,data.value[0].name do not Exist");
}
function checkValue2(){
if(data && data.value && data.value[0] && data.value[0].names){
return true;
}else{
return false;
}
}
let correct2=checkValue2();
if(correct2){
console.log("This is valid, data.value[0].names Exist");
}else{
console.log("This is invalid,data.value[0].names do not Exist");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.0/react-dom.min.js"></script>
You can check your object by using optional chaining (?.).
This will check every part of your chain. Say if it is undefined the data inside the state then it returns undefined excepts throwing an error.
let state = {
data: {
value: [
{name: 'value'}
]
}
}
console.log(typeof state?.data?.value?.[0]?.name);
console.log(typeof state?.data?.value?.[1]?.name);
console.log(typeof state?.datum?.value?.[0]?.name); // In this case it returns 'undefined' for dutum stage.
Note
Optional chaining has poor browser support until now. So you have to use Babel or any other Javascript compiler for browser support.
Just use the same typeof operator:
if(typeof(this.state) != 'undefined'){
if(typeof(this.state.value) != 'undefined') {
// next source
}
}

Getting strange error when running the following function

I am trying to do something like
HTML('slider1') = someimage;
But my HTML() function is not returning document.getElementById('slider1');
function HTML(id){
if(typeof value !== undefined){
return document.getElementById(id).innerHTML;
}
}
typeof allows the identifier to never have been declared before.
function HTML(id){
if(typeof value == "undefined")
{
//do nothing
}else{
return document.getElementById(id).innerHTML;
}
}
You can also try
if(typeof neverDeclared === typeof undefined) //also no errors and no strings
I think you are trying to assign some image through innerHTML, you may update your function to something like this
function HTML(id){
if(typeof value !== undefined){
return document.getElementById(id);
}
}
HTML('slider1').innerHTML = someimage;
//OR
function HTML(id, htmlChunk){
if(typeof value !== undefined){
document.getElementById(id).innerHTML = htmlChunk;
}
}
HTML('slider1',someimage);

Can I use variable for 'if' query in Javascript?

If I had multiple points in which I needed to use the same if statement, could I use a javascript variable:
var query = ((val!=='CLOSED')||(val!=='OFF')||(val!=='Off'));
if query {
//statement true;
}
Absolutely.
var query = (val!=='CLOSED' || val!=='OFF' || val!=='Off');
if (query) {
//statement true;
}
Note that (val!=='CLOSED' || val!=='OFF' || val!=='Off') doesn't really make a lot of sense. It would evaluate to true for the string 'OFF', for example.
You probably want !(val == 'CLOSED' || val == 'OFF' || val == 'Off').
You can, but your syntax needs to be correct:
var query = ((val!=='CLOSED')||(val!=='OFF')||(val!=='Off'));
if(query) {
//statement true;
}
Notice the parenthesis around query
You can use function for that if variable will change.
function checkVariable(variable) {
return ((variable !== 'CLOSED') || (variable !== 'OFF') || (variable !== 'Off'));
}
if (checkVariable(variable)) {}
If not, then just assign statement value to variable and use it again.
var result = (variable !== 'CLOSED' || variable !== 'OFF' || variable !== 'Off');
if (result) {}
No.
You could store the result of performing the tests and reuse that (the if statement does require the test to be placed in parentheses though):
var result = ((val!=='CLOSED')||(val!=='OFF')||(val!=='Off'));
if (result) {
//statement true;
}
… but that wouldn't re-evaluate the statements if val was to change. So it is not the same as repeating the tests each time.
You could use a function though.
var query = function (val) {
return ((val!=='CLOSED')||(val!=='OFF')||(val!=='Off'));
}
if (query(some_value)) {
//statement true;
}
Yes you can, but it will always contain a value evaluated at the time the query variable was created.

Javascript isset function

I created an isset function to check if a variable is defined and not null.
Here's my code:
isset = function(a) {
if ((typeof (a) === 'undefined') || (a === null))
return false;
else
return true;
};
var a = [];
// Test 1
alert(isset(a['not']); // Alerts FALSE -> works OK
// Test 2
alert(isset(a['not']['existent'])); // Error: Cannot read property 'existent' of undefined
Any suggestion to make my function work for test 2?
Thanks.
You are trying to check property of an undefined object. It doesn't make any sense. You could write like this:
alert(isset(a['not']) && isset(a['not']['existent']));
that won't work, and you can't make it work.
what happens is this:
the js engine tries to evaluate a['not'] and get's "undefined", then it tries to evaluate the property 'existent' of the undefined and you get that error.
all of that happens before the call to your function...
what you can do is something like:
var isset = function(obj, props) {
if ((typeof (obj) === 'undefined') || (obj === null))
return false;
else if (props && props.length > 0)
return isset(obj[props.shift()], props);
else
return true;
};
then you call it like this:
var a = [];
// Test 1
alert(isset(a, ['not']);
// Test 2
alert(isset(a, ['not', 'existent']));
(**this just a pseudo code, you might need to modify it a bit to actually work)
Test 2 will not work because "a['not']['existent']" value resolution precedes "isset" function call, and results in a runtime error.
Well, You can do right this:
1) as we do in php:
$vara = "abc";
$a =0;
while(isset($vara[a]){
a++;
}
2) as I do in javascript:
vara = "abc";
while (vara[a] != null){
a++;
}

javascript if statement question

function valid()
{
begin_checked = false;
end_checked = false;
alert("begin_checked: " +begin_checked);
alert("end_checked: " +end_checked);
if (document.dd.begin.checked.length == undefined || document.dd.end.checked.length == undefined )
{
alert("In undefined");
}
alert("end");
}
When the if statement is false, it never gets to alert("end") ? When it is true, it executes properly. Why?
There is probably a null pointer exception and you do not have errors outputting to your browser.
You need some output to check:
alert(document);
alert(document.dd);
alert(document.dd.begin);
alert(document.dd.begin.checked);
alert(document.dd.end);
alert(document.dd.end.checked);
If you get undefined from any of those, then your code will not execute properly.
Edit: Also, the other answers here all have good information. Read those as well.
Edit2: Alternative - Surround your code in a try/catch block and alert the error:
function valid(){
try{
begin_checked = false;
end_checked = false;
alert("begin_checked: " +begin_checked);
alert("end_checked: " +end_checked);
if (document.dd.begin.checked.length == undefined || document.dd.end.checked.length == undefined ){
alert("In undefined");
}
alert("end");
} catch (e) {
alert(e);
}
}
Are there any errors in your browsers error console? I'm guessing it's because it's trying to evaluate a property that doesn't exist, this causing it to fail (never getting to the == undefined). You can just check that the property exists or use the typeof to check if it's undefined.
if (!document.dd.begin.checked.length || !document.dd.end.checked.length)
{
alert("In undefined");
}
if (typeof document.dd.begin.checked.length == 'undefined' || typeof document.dd.end.checked.length == 'undefined' )
{
alert("In undefined");
}
http://getfirebug.com/

Categories