JQuery - write conditional when object property is blank - javascript

I'm trying to write a conditional for when an object property's value is blank, but it is not triggering. This is my code. Any idea how I should write this?
console.log(vid);
if (vid.video == undefined){
//DO STUFF HERE - Doesn't work
}
The "object" in the screenshot is referenced in the code above as variable vid. I also tried undefined in the conditional.

I see some misunderstading here:
You say when an object property's value is blank but your coded if (vid.video != ""){.
I think you need if (!vid.video) {

use this:
vid.video == undefined
Also what Andrew said. If you want to DO STUFF when the attribute is empty, you should Use "==", and not "!="

if(vid.video != "")
Are you looking to only execute code when video doesn't equal "" but if you want to execute code when it is equal to "" you need
if(vid.video == "")
However if you want to check to see if its undefined you'll need to do
if(vid.video === undefined){
vid.video is not defined here
}
or
if(vid.video){
vid.video is defined here
}

Related

Check for array in JS

I'm trying to check a value in JS that on page load is returned as a single-element array and after an ajax function returns as a string. I don't know why it's doing this but I'm trying to role with it.
So, using console.log(value) I get array ['Scranton'] on page load, and the ajax even returns string "Scranton"
When trying to check this variable, this does not work as I intended:
if ( value === 'Scranton' || value === ['Scranton']){
...
}
Any help is appreciated!
This would probably work but I would try and fix the underlying issue instead of working around it.
if ( value === 'Scranton' || value[0] === 'Scranton'){
...
}
You can use indexOf for both an array and a string, so value.indexOf("Scranton") !== -1 will work (just tested this on the console).
However you must first check for null/false/undefined or it will error.
if (value && value.indexOf("Scranton") !== -1) {}
EDIT: As Felix said, this will also be true for any string containing "Scranton". If this is a problem, then you can check for indexOf == 0 instead, which will be true for any string starting with "Scranton". It really depends on your concrete problem if this solution fits you. Use with care.
if (Object.prototype.toString.call(value) === '[object Array]') {
if (value.indexOf('Scranton') != -1) {
/* */
}
} else {
if (value === 'Scranton') {
/* */
}
}
Edit 1:
First, you need to check if "value" is an array. If it's an array and contains the string "Scranton", you can find it using value.indexOf().
And if "value" is not an array, you can directly compare it with the string 'Scranton'.
What does "after an ajax function" mean? The page loads with a default variable that has been assigned an array value, and then an Ajax request is made, which changes this default variable, and instead of an array being assigned, it assigns a string? Assuming this "ajax function" changes the default variable to the response text from the server, there is your problem: Ajax--like any other request--is text-based, so it is a string. If you are responding to the Ajax request with a JSON string, built on the server, it needs to be parsed in the browser, so it can be reinterpreted as an array. See the JSON.parse method.

Weird Javascript If Statement

I'm not sure whats wrong with my if statement. I'm trying to use my model inside my javascript.
if (#Model !== null)
{
if (#Model.Level !== null)
{
//use #Model.Level
}
}
else
{
//use default
}
The Model is null, but it still steps into the first if statement (and breaks on the second one obviously). I've tried #Model, !#Model and != but it still always steps in.
What am I doing wrong? (It's also got squiggly red lines under both !== saying there is a syntax error)
Triple equations work without type castings in JavaScript. In your case you are might get an undefined object which isn't a null value.
For example:
undefined === null //Do not cast when comparing, increased performance.
false
undefined == null //Do cast when comparing, decreased performance.
true
In addition, if #Model value is null then you won't see a null value on client side. It gives you an empty value like this:
if( == null)
{
}
This will cause an error on your javascript side. Null check should be done at server side. For that reason you have to put # value in front of your code to make it server side:
<script>
#if (Model != null) //Server side code.
{
if (Model.Level != null) //still server side code.
{
<text>
alert("your javascript here"); //write javascript on your screen.
</text>
}
}
</script>
In order to check if something is null or undefined in javascript, use if (#model) rather than if ( #model !== null)
http://appendto.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-2/
The reason why it steps into the if statement is because it evaluates to true, no weirdness to be found here. Your browser is not temperamental. For a list comparisons check out this http://dorey.github.io/JavaScript-Equality-Table/
Also note that there is a difference between double and triple =. Triple will type cast
This code looks a LOT like a Razor then Javascript, though you may be trying to mix the two of them together.
Your choices:
1) Convert Model to a JavaScript object using something like this:
Turn C# object into a JSON string in .NET 4
2) Use the Razor if statement and write out your final JavaScript with it.
<script>
// Code assume this is an numeric value
var useThisVariable;
</script>
if (#Model !== null)
{
if (#Model.Level !== null)
{
<script>
useThisVariable = #Model.Level;
</script>
}
}
else
{
<script>
useThisVariable = -1;
</script>
}

Checking if undefined in jQuery/Javascript

I have the following:
var currentQuestion = $(this).closest(".question")
I have tried everything suggested in this, this and this question:
if(currentQuestion !== undefined)
if(currentQuestion !== "undefined")
if(typeof currentQuestion !== undefined)
if(typeof currentQuestion !== "undefined")
if(currentQuestion !== null)
if(currentQuestion != undefined)
if(currentQuestion != "undefined")
if(currentQuestion.data("index") !== null)
if(currentQuestion.data("index") !== undefined)
if(typeof currentQuestion.data("index") !== undefined)
But it keeps going inside the if statement...
I have this inside the if:
console.log("nextQ: " + currentQuestion.data("index"));
and nextQ: undefined is getting print out
any other ideas?
EDIT:
currentQuestion.data("index") != null
worked out. If you check all the options I tried before, the one similar to this one had this comparison element: !== and not !=. That change made the difference. If someone can explain why, I'll grant him/her the correct answer.
The result will never be undefined, it's always a jQuery object. If the operation didn't find any elements, the jQuery object will be empty, so you check how many element there are in it to see if found anything:
if (currentQuestion.length > 0)
After you have checked that there is actually any element in the jQuery object, you can check if there is any data associated to the element.
If no data is associated with an element, the data method will return undefined when you try to read the value. So, to check if there is no data, you should check the type of the value that the data method returns:
if (typeof currentQuestion.data("index") != "undefined")
If you want to check any elements exist, then check the length.
var currentQuestion = $(this).closest(".question");
if (currentQuestion.length > 0) {
console.log("nextQ: " + currentQuestion.data("index"));
}
if (currentQuestion.length) {
Should work fine. If it goes in there, it found something. And instead of looking at the if statement you need to look at your html and see what it found.
What you want is currentQuestion.length.
jQuery selectors return an array of elements matching the selector. To test for values in an array, you should use length:
Boolean([].length); //false
Because 0 evaluates to false, you can just use if (currentQuestion.length).
If you're trying to check for it when it is false, use !:
if (!currentQuestion.length)
For your question of why != worked but not !==, I would suggest this question: Difference between == and === in JavaScript
Basically, currentQuestion.data('index') is not strictly equal to null, but it could evaluate to null: same as [] == 0 evaluates to true, but [] === 0 evaluates to false.
It is probably not the most elegant solution. But somehow
currentQuestion.data("index") != null
worked out. If you check all the options I tried before, the most similar to this one had this comparison element: !== and not !=. That change made the difference. If someone can explain why, I'll grant him/her the correct answer.

javascript undefined not null, not empty issue

Is the statement:
if(attachmentId!=null && attachmentId.length>0&& attachmentId !='undefined'){
//do something
}
equivalent to:
if (attchmentId) {
//do something
}
thanks for the help
Writing :
if (attchmentId)
is the equivalent of:
if(
attchmentId != undefined &&//NO QUOTE
attchmentId != '' &&
attchmentId != null &&
attchmentId != false &&
attchmentId != 0
)
They're not equivalent but the third test attachmentId !='undefined' was probably an error (did you want attachmentId !=undefined ?).
Another example of difference is that 0 doesn't pass the first test but pass the second one.
You must decide what's important to you before you try to write the test. If you know you start with a string and you want to test if it's defined and not empty, then you may use the second test.
It can be reduced to this:
if (attachmentId && attachmentId.length > 0) {
//do something
}
This will do for arrays and more complex objects that happen to have a length property. If attachmentId is supposed to be a string the code above will work the same, but the second part will basically be a noop, so you can just go with:
if (attachmentId) {
//do something
}
I am assuming the comparison against 'undefined' was a mistake - do that and you're not checking if something is actually undefined. You're checking it it is different from a literal string that says "undefined".
Also you check the variable first due to the short circuit rule. It it's either null or not defined you don't care about the rest. Otherwise, if you tried evaluating the length before checking if it's undefined or null you could throw an error there.

If statement throwing error for nonexistent object

The answer to this question seems like it would be obvious, but I'm always looking to improve my semantics, so bear with me.
I have an array structure with individual items containing X,Y coordinates
var example = new Array();
example.push({x:0,y:0});
In my code I have a set interval that updates my canvas and checks for certain conditions. Including one similar to this
if(example[0].x == other.x && example[0].y == other.y)
{
//do something
}
The issue is that the array is very dynamic, and when the code is first executed the example array is empty. Hence, Chrome throws errors along the lines of "Cannot get property x". To shut up the console, I added a dummy item to the array {x:"~", y:"~"} but it seems really unintuitive. Have I implemented an undesirable data structure? What's a simple way to handle if statements for objects that... don't exist?
Why don't you just check whether the array has elements?
if (example.length && ...)
Or whether the first element is true:
if (example[0] && ...)
if (0 in example
&& example[0].x == other.x && example[0].y == other.y) {
// do something
}
(This works for arbitrary index, not just 0; if you just want to check if the array is non-empty, example.length as shown by melpomene is good.)
You should be able to check on the first-level element (i.e. 'example') - JavaScript usually throws errors like this when you try to access a property of an element that is null or undefined. Like some others have already shown:
if(example[0] && example[0].x === other.x)
The point is though that JavaScript will let you have example[0] and return as you like, but once you try to access that property, you're out of luck:
var example = [];
//undefined
example
//[]
example[0]
//undefined <--- this is a falsy value, will evaluate false in a check
example[0].x
//TypeError: Cannot read property 'x' of undefined

Categories

Resources