Checking for null objects in javascript - javascript

I have the following code snippet that defines the property values in my form.
function retrieve(){
setSelectedIndex(document.producerSetForm.GA1,"<%=ssnGA1%>");
setSelectedIndex(document.producerSetForm.GA2,"<%=ssnGA2%>");
setSelectedIndex(document.producerSetForm.GA3,"<%=ssnGA3%>");
setSelectedIndex(document.producerSetForm.GA4,"<%=ssnGA4%>");
setSelectedIndex(document.producerSetForm.GA5,"<%=ssnGA5%>");
}
where these ssnGA1,ssnGA2 etc may or may not be having a value. I need to check whether whether they have a value to do some more processing. I tried
var len=<%=ssnGA1.toString().length()%>;
if(len !=0)
but it works only if the value is present. else it giving javascript error. Please help. THANKS

You have to check if your string is not undefined/null first, on example:
if ( ssnGA1 && ssnGA1.toString().length ) {
// do something
}
Also, length is a property, not a function, see MDN for details.

Related

Can someone please explain in plain english what is going on in a particular part of my code for objects?

although it is a very simple code, I would like to get a full understanding of what is happening in my condition:
let getFreqOn = function(string){
//set a variable for object
let object = {}
for (let key = 0; key < string.length; key++){
// if (object.hasOwnProperty(string[key])) {
// if (object[string[key]]) {
// if (object[string[key]] !== undefined) {
if (string[key] in object) {
object[string[key]]++
}
else{
object[string[key]] = 1
}
}
return object
}
My main concern would be the first condition, I understand what it is they do but I cant put in to plain English how it is working. For example if (string[key] in object) is basically telling my that if a specific property is in the empty object I defined, then I will set then it will be set as the property and incremented. But what I'm trying to wrap my head around is that the object is empty, so how can the property be in the object?
Hoping someone can enlighten me on the conditions that I commented out as well. Sorry for the noob question.
First, the in operator returns a boolean result. It checks whether the string on the left is present as a property name in the object on the right.
Thus
if (string[key] in object)
asks whether that single character of the string is in use as a property name in the object. As you observed, the very first time through the loop that cannot possibly be true, because the object starts off empty.
Thus the if test is false, so the else part runs. There, the code still refers to object[string[key]], but it's a simple assignment. An assignment to an object property works whether or not the property name is already there; when it isn't, a new object property is implicitly created.
The key difference is right there in the two different statements from the two parts of the if - else:
object[string[key]]++; // only works when property exists
object[string[key]] = 1; // works always

I have a button function in my program. Mostly works, but when I click, it doesn't execute the if. Code included

var rectbutton = function(x,y,width,height,bevel,label,basecolor,textcolor,hovercolor,changevar,changevarvalue){
textAlign(CENTER,CENTER);
textSize(height);
fill(basecolor);
rect(x-width/2,y-height/2,width,height,bevel);
fill(textcolor);
text(label,x,y+5);
if(mouseX>=x-width/2 && mouseX<=x+width/2 && mouseY>=y-height/2 && mouseY<=y+height/2){
fill(hovercolor);
rect(x-width/2,y-height/2,width,height,bevel);
fill(textcolor);
text(label,x,y+5);
if(mouseIsPressed){
var changevar=changevarvalue;
}
}
};
Use:
rectbutton(200,250,250,50,5,"PLAY",color(255,255,255),color(0,0,0),color(255,0,0),playerState,1);
Everything works until I click. Doesn't set changevar to changevarvalue. Did try changevar=changevarvalue; instead of var changevar=changevarvalue;
In your code snipped there is no mouseIsPressed defined anywhere, is it missing? You might need to provide us a more complete code example.
Also try to look at your console if any javascript errors occure.
In js objects are passed by reference and primitives are passed by value. If you want to update your changevar variable, you would have to pass an object in changevar parameter while calling the rectbutton function and not some primitive value. I'm assuming playerState contains some primitive and not an object as a value.

outputting content based on whether variable object equals "true"

I thought this would be straight forward after reading through w3c tutorials etc! But I appear to have something incorrect as the code doesn't output anything!
The variable is set based on whether the user is logged in or not:
var theJSON={"LOGGEDIN":false};
var theJSON={"LOGGEDIN":true};
I am then trying to show on the front end whether the user is logged in or not:
$(document).ready(function() {
if (typeof(theJSON[LOGGEDIN]) == true ) {
document.write ("Logged in")
} else {
document.write ("Not logged in");
}
i must be missing/mistyping something so simple?
There a couple of things wrong in your code:
When you try to access the LOGGEDIN property of the object, you are missing quotation marks. The expression theJSON[LOGGEDIN] will first try to get the value of the variable LOGGEDIN to use its value as property name. If such a variable does not exist (like it is in your example), the code will throw an error.
Now, The value of theJSON['LOGGEDIN'] is true and the type of the value is a boolean. typeof(theJSON['LOGGEDIN']) == true will never be true, because the typeof operator returns a string with the name of the data type, i.e. typeof(theJSON['LOGGEDIN]') will return "boolean".
If you just want to test whether the value is true, do:
if (theJSON['LOGGEDIN'])
w3schools is really not the best site to start learning about JavaScript, have a look at http://eloquentjavascript.net/ and the MDN JavaScript Guide instead.
if (typeof(theJSON["LOGGEDIN]") == true )
or
if (typeof(theJSON.LOGGEDIN) == true )
BTW, better use === instead of ==
if the value is number 1 it will still pass the condition.
Firstly, your theJSON is an actual object as given, not a JSON string. If it was you'd need to parse it as suggested.
The expression theJSON[LOGGEDIN] is incorrect syntax, you can either say theJSON.LOGGEDIN or theJSON["LOGGEDIN"]. And as this is a boolean, typeof(theJSON.LOGGEDIN) == "boolean".
The expression is a boolean, but it's value is true, so you can just write if (theJSON.LOGGEDIN).

Not Equal To notation in Javascript to use in jQuery

Is this the notation to use for Not Equal To in JS, in jquery code
!== OR !=
None of them work
Here is the code I am using
var val = $('#xxx').val();
if (val!='') {
alert("jello");
}
Thanks
Jean
Equality testing in JQuery works no different from "standard" JavaScript.
!= means "not equal to", but !== makes sure that both values have the same type as well. As an example, 1 == '1' is true but not 1 === '1', because the LHS value is a number and the RHS value is a string.
Given your example, we cannot really tell you a lot about what is going on. We need a real example.
.val() is used to retrieve or set values from input in forms mostly, is that what you want to do? If not maybe you mean using .text() or .html().
If that is indeed what you want to do maybe you have your selector wrong and its returning null to you, and null does not equal '', or maybe you actually have data there, like whitespaces. :)
May be you have whitespace in your #xxx node, that why both !== and != failing, you could try following to test non whitespace characters
var val = $('#xxx').val();
if (/\S/.test(val)){
alert('jello');
}
Note: I assume jQuery's .val() won't return null because of this line in jQuery source
return (elem.value || "").replace(/\r/g, "");
If not, you need to do like this
if (val && /\S/.test(val)){
alert('jello');
}
It's both, but the latter is strict on type, see here:
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Comparison_Operators
It is working with jquery and normal java script.
You should check (alert/debug) your val variable for its value and null.
You should also check $('#xxx').length whether you are getting elements or not otherwise you will get, hence your if condition will be false.

A question about "undefined" in Javascript

Today one of my friends said:
if (typeof isoft == "undefined") var isoft = new Object();
is such kind of code is writted by a freshman and writes
if(!isoft) var isoft = new Object();
I originally consider there must be some difference. But I can't find the difference. Is
there any? Or are the two examples the same?
Thanks.
See the question Javascript, check to see if a variable is an object but note that the accepted answer by Tom Ritter appears to be incomplete, check the comment on his answer. See also the community answer by Rob.
In the example involving regular objects that you provided there is little difference. However, another typical pattern can be:
var radioButtons = document.forms['formName'].elements['radioButtonName'];
if ('undefined' === typeof radioButtons.length) {
radioButtons = [ radioButtons ];
}
for (var i = 0; i < radioButtons.length; i++) {
// ...
}
If you used if (!radioButtons.length) it would evaluate true when no radio buttons were found (radioButtons.length is 0) and create an array of a single (non-existent) radio button. The same problem can arise if you choose to handle the radio buttons using:
if ('undefined' === typeof radioButtons.length) {
// there is only one
} else {
// there are many or none
}
There are other examples involving empty strings where if (!variable) is probably not recommended and it is better to test against typeof undefined or explicitly test against null.
If isoft should hold a reference to an object, both do the same. A !isoft is true for all false values, but a object can't be a false value.
In your particular example there's no significant difference, since you're evaluating Object instance, and objects are converted to Boolean true when cast to Boolean, while undefined and null are evaluated as Boolean false.
But take this for an example:
function alertSomething(something) {
//say you wanna show alert only if something is defined.
//but you do not know if something is going to be an object or
//a string or a number, so you cannot just do
//if (!something) return;
//you have to check if something is defined
if (typeof something=='undefined') return;
alert(something);
}
I like to take shortcuts and save typing wherever I can, sure, but you have to know when to take a shortcuts, and when not to ;)

Categories