javascript if statement question - javascript

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/

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
}
}

Javascript error with setting a default value for function

I have a function:
function modifySpinner(currentIcon, selector, spinType = remove)
{
if (spinType === 'add') {
// something
}
}
But I am receiving this error in my console:
Uncaught SyntaxError: Unexpected token =
This wasn't causing issues in firefox? But in chrome its not working.
Try this instead:
function modifySpinner(currentIcon, selector, spinType)
{
var spinType = spinType || "remove"
if (spinType === 'add') {
// something
}
}
So why this works: if the spinType doesn't have a value it equates to undefined. With var spinType = spinType || "remove" you are saying "hey evaulate spinType and if it's false, then use remove." undefined and null both evaluate to false in this conditional statement so, it's shorthand for saying if this value is undefined, use this other value instead.
Truthy and Falsy in Javascript
You can't use this syntax for a default value.
function modifySpinner(currentIcon, selector, spinType )
{
spinType = spinType || "remove";
if (spinType === 'add') {
// something
}
}
Like this, if it's undefined, null, ... The value will be remove
Javascript doesn't have default parameters (it's been introduced in Ecmascript 6), you have to do the check yourself:
function modifySpinner(currentIcon, selector, spinType)
{
spinType = typeof spinType !== 'undefined' ? spinType : 'remove';
if (spinType === 'add') {
// something
}
}

JavaScript isset() function [duplicate]

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";
}
}

Finding undefined variable name string in ReferenceError

My question is simple, but Javascript VM dependent.
When catching a ReferenceError (in my case when doing eval(...)), how do I get back the actual identifier token from the error object?
Matching for "known" error messages and parsing them seems way too hackish for me, but is the only available option to me right now.
edit: For the moment I'm only "matching" V8 and Firefox by doing this:
catch(e){
if (e.name === "ReferenceError"){
var varname = e.toString().replace("ReferenceError: ","")
.replace(" is not defined","").trim();
foobar(varname);
}
}
You should be able to do this using e.message and matching the text up until the first space.
The following code works in IE7/IE8/IE9/IE10/Chrome and Firefox.
try {
alert(tesssst);
} catch(e){
if (e.name === "ReferenceError" || e.name === "TypeError") { //IE7 uses TypeError instead
var variableName = e.message.substr(0, e.message.indexOf(" "));
//IE7 and IE8 fix (it adds ' around the variable name)
if (variableName.substr(0, 1) == "'" && variableName.substr(variableName.length - 1) == "'") {
variableName = variableName.substr(1, variableName.length - 2);
}
console.log(variableName); //tesssst
}
}
Edit:
Added IE7/IE8 fixes
Edit 2:
With a little regex magic you can change this to the following:
try {
alert(tesssst);
} catch(e){
if (e.name === "ReferenceError" || e.name === "TypeError") { //IE7 uses TypeError instead
var variableName = e.message.match(/^'?(.*?)'? /)[1];
console.log(variableName);
}
}

How to check if object literal is not in page?

I'm trying to check for if my object literal is not in my page.
var today = {
okay : true
}
If this snippet is not in my page I want to check for null or undefined but it kills silently...
if (today.okay == null)
if (today.okay == undefined)
What to do?
The reason it fails (it shouldn't be failing silently, it should be throwing an exception) is that you're trying to retrieve a value from a symbol (today) that may not be defined.
Try this:
if (typeof today == 'object' && today.okay) {
// It's there
}
else {
// It's not there
}
Alternately, of course, you can just handle the exception:
try {
if (today.okay) {
// 'today' is defined and 'okay' is truthy
}
else {
// 'today' is defined, but 'okay' is not truthy
}
}
catch (e) {
// 'today' is undefined
}
My impression is that most JavaScript engines are very fast when it comes to throwing exceptions (this is not true of all environments), but if you anticipate this condition being not unusual (not exceptional), then I would handle it with inline logic, not an exception. Exceptions are for exceptional conditions.
Assuming you require the "okay" to be boolean, the expression you're looking for is:
('object' == typeof today && today.okay === true)​​​

Categories