Meaning of == "" in javascript - javascript

Short questioion, I'm trying to understand this tutorial:
http://superdit.com/2011/02/09/jquery-memory-game/
Being new to Javascript I can't seem to find what the statement '== ""' means... I understand "==", but not the empty double quotes.

val == "" is a non-strict comparison to emtpy string. It will evaluate to true if val is empty, 0, false or [] (empty array):
var val = "";
console.log( val == "" ); // true
val = 0;
console.log( val == "" ); // true
val = false;
console.log( val == "" ); // true
val = [];
console.log( val == "" ); // true
You can use === to use strict comparison, fex:
val = 0;
console.log( val === "" ); // false

The ' == "" ' is a check for an empty string. It will be true when the string is empty, and false whenever there are some characters inside it.

A quick scan of the code (ctrl-F is your friend) quickly teaches you that the only time such a statement occurs in the code is here: if (imgopened == ""), another search taught me that imgopened is an evil (global) variable that is initialized to "" at the very top of the script, and every time some action/function is done with whatever value it was assigned.
I suspect it's a sort of card game, where two identical imgs need to be clicked, in which case this var will reference the image currently turned. If it's empty, then all imgs are facing down, and this var is empty: "".In other words:
if (imgopened == "")//=== if no card is turned
{
//do X, most likely: turn card
}
else
{
//do Y
}
This could've been written as
if (!imgopened)
//or
if (imgopened == false)//falsy, but somewhat confusing
//or
if (imgopened == 0)//!confusing, don't use
//or, my personal favorite
if (imgopened === '')

Related

Ajax check value of data

I'm getting data as JSON response and each time one of my fields is empty and one has value so I need to make if statement to check which one has value and print that one.
So far I tried:
if(data.longtext_dec != ''){
var ress = data.longtext_dec;
} else {
var ress = data.text_dec;
}
and
if($.trim(data.longtext_dec) === '')
{
var ress = data.longtext_dec;
} else {
var ress = data.text_dec;
}
each time the code keeps printing longtext_dec or show both as null.
So I need help to get this right, the result of this ress I want to append it in my view (either this or that).
How can I fix this code?
UPDATE
network response tab:
product_id 15
specification_id 5
text_dec ddd
longtext_dec null
id 69
payload
{"product_id":"15","specification_id":"5","text_dec":"ddd","longtext_dec":null,"id":69}
Just use if (data.longtext_desc) it's a way to check if data variable evaluates to true. undefined, null, false, 0, an empty string evaluates to false.
var ress; // undefined
if (data.longtext_desc) {
ress = data.longtext_desc;
} else {
ress = data.text_dec;
}
Optionally use a ternary operator:
var ress = data.longtext_desc ? data.longtext_desc : data.text_dec;
There is a difference between empty string, null, undefined and boolean true/false. As shown in the JSON you want to check if the value from the response object is null. So just check
if( data.longtext_dec !== null )
Here is very well explained:
https://stackoverflow.com/a/27550756/3868104
Optional you can check for whatever you want for example:
if( data.longtext_dec !== "" )
and so on.
you can leverage javascript || operator as below
var res = data.longtext_dec || data.text_dec;
Try this :
var data = {"product_id":"15","specification_id":"5","text_dec":"ddd","longtext_dec":null,"id":69};
var ress;
(data.longtext_dec !== null) ? ress = data.longtext_dec : ress = data.text_dec;
console.log(ress);

checking values before submitting form

Before I submit a form I want to check the values in the input.
Here I'm checking if a value is NOt equal to .5 or 1. or not a empty string.
form.onsubmit = function(e) {
var ftimes = document.getElementsByClassName("add_timebox");
var fflag = 0;
for(i=0;i< ftimes.length;i++) {
var value1 = ftimes[i].value;
console.log(value1);
if ( value1 !==.5 ||value1 !== 1 || (!IsStringEmpty(value1)) ){
fflag = 1;
console.log('inside');
}
}
if(fflag==1) {
alert('enter again' );
return false;
}
I have made many changes to the IF statement to try to get it correct.
But it is still going in the loop even when I know if shouldn't.
For example when i submit the form and i have one input value equal .22
then it should only give me 1 'inside' but in keeps repeating:
inside
.22
(empty string)
inside
....
You do not show how you are implementing your IsStringEmpty method, but if you are using something like this, then any number is also a non-empty string, so your if statement will always run.
function IsStringEmpty(str) {
return (!str || 0 === str.length);
}
So you need to change your ORs with ANDs, or it will never check the number conditions.
You can check if the value is not an empty string and is different from 0.5 and 1. Then your condition should be like this.
if (!IsStringEmpty(value1) && value1 !== 0.5 && value1 !== 1)
But, you are getting the value from a form, so it will be a string. Therefore, you are comparing strings and you need this.
if (!IsStringEmpty(value1) && value1 !== ".5" && value1 !== "1")
Although you will probably want to compare floats, in which case you need this.
if (!IsStringEmpty(value1) && parseFloat(value1) !== .5 && parseFloat(value1) !== 1))
So basically, when you enter 1, .5 or and empty string in all of the form fields, you skip the inside block. But if you have any other value in any of the fields, then the flag will be set to 1. If that is not what you meant, please update your question to be more specific.
Please check Plunker here.
Hope this helps.
you have to add a break; statment in your if condition once the if condition is satisfied.
if ( value1 !==.5 ||value1 !== 1 || (!IsStringEmpty(value1)) ){
fflag = 1;
console.log('inside');
break;
}

string objects comparison always returning false

Here is the code that I am executing:
filterIssues: function(objectKey, text){
var view = this;
var keys = objectKey.split(".");
var attributeKey = keys[0];
var attributeName;
if (keys.length > 1){
attributeName = keys[1];
}
view.issues.each(function(issue){
var value = issue.get(attributeKey);
console.log(text);
if (value === undefined || value === null){
issue.trigger("hide");
return;
}
if (attributeName !== undefined){
value = value[attributeName];
}
if(value !== undefined){
var matchedText = value.substring(0, text.length - 1);
if ( matchedText === text){
issue.trigger("show");
console.log(value);
return;
}
}
issue.trigger("hide");
});
}
The matchedText == text always returns false.
This is what I get when I play around with the console:
> matchedText
"sande"
> text
"sande"
> typeof(text)
"string"
> typeof(matchedText)
"string"
> matchedText === text
false
> matchedText == text
false
I do realize that and === will always check if both the objects are the same and I have read
JavaScript equal operations anomalies and Javascript string equality.
Is there something wrong in the code that I am overlooking?
I think you are misusing the subString() method. If you use subString(), use the length without -1.
Well I eventually found out what was the problem. Thanks for your responses and I believe you might not have come across the answer for the lack of information.
The problem lied in the text value that I was passing to the function. The text contained a "" at the end and that's why comparison just did not work.

Is there any way of determining which or statement is true in javascript?

So say I have an if statement:
if(a=='' || b==''){
//which is true?
}
Is it possible to determine which statement satisfied the if statement without doing a switch statement or another if statement to check?
You can define a token to store what condition was true:
var token = null;
if ((a == '' && (token = 'a')) || (b == '' && (token = 'b'))) {
// Here token has an 'a' or a 'b'. You can use numbers instead of letters
}
I think it's the simplest way to do what you want.
As others have said, you have to test the conditions separately, but you can kind of mix worlds.
var test1 = 1 == 1; // true
var test2 = 2 == 1; // false
if (test1 || test2) {
// If either conditions is true, we end up here.
// Do the common stuff
if (test1) {
// Handle test1 true
}
if (test2) {
// Handle test2 true
}
}
No, you have asked explicitly if one or both are true. There's no way to work out which of those sub-expressions is true without another conditional of some sort.
If you're interested in different behaviour based on which is true, you should probably separate them with a possibly-common bit, something like
either = false;
if (a == ' ') {
doActionsForA();
either = true;
}
if (b == ' ') {
doActionsForB();
either = true;
}
if (either) {
doActionsForAorB();
}
If you care about which of the two conditions is true the only way to find out is to test them separately, e.g.
if(a==''){
// ...
}
else if(b=='') {
// ...
}
Sometimes, especially in more complicated conditionals, it helps if you store the result of each condition and reuse it later on:
var isFoo = a == '';
var isBar = b == '';
// You can now use isFoo and isBar whenever it's convenient
the simple solution:
if ((ia=(a=='')) || (b=='')) {
// ia indicate whether the boolean expression a have been true.
// ia -> a has been true, b may have, !ia -> b has been true, a has not
}
there is no ib in the simple solution as it won't be always be set due to shortcut evaluation.
to cater for shortcut evaluation try:
if (((ia=(a=='') || (ib=(b=='')) && ((ib=(b=='')) || (ia=(a==''))) {
// ia, ib indicate whether the corresponding boolean expressions have been true
}
if(a=='' || b==''){
var x= a || b;
//if a is ''(falsy) x will be b, else a
}
var phone="";
var email="something";
if(phone=='' || email==''){
var x= (phone) ? 'phone':'email';
console.log(x); //email
}

jquery check variable values

In jQuery I have the following 4 variables.
var add
var city
var state
var zip
I need to check to see that any one of the above have a value.
If none have a value that is OK. If all of them have a value that is OK.
Just need to check that at least one of them do not have a value.
Not sure what is the most efficient way of doing this.
var check = [ add, city, state, zip ].every( function ( v ) { return !!v } )
Just for the sake of showing off.
Explaination: the every method loops through all the array and returns false if one of the conditions returns false and stops immediately the loop. If all the loops return true, true is returned.
PS: v is for "variable".
var check = (function(a, b, c, d) {
return !!a && !!b && !!c && !!d;
}(add, city, state, zip));
console.log(check);
another method... lets learn some new techniques today!
this will actually check to see if the value is not false. anything else is ok (strings, numerics, TRUE).
Simply
if (yourVar)
{
// if yourVar has value then true other wise false.
}
Hope thats what you required..
to check i a variable has a value assign it to it you can do:
var myVar
....
if (typeof myVar === 'undefined'){
// here goes your code if the variable doesn't have a value
}
if(!add || !city || !state || !zip) {
console.log('exists var with no value');
}
if( add.length == 0 || zip.length == 0 || city.length == 0 || state.length == 0) {
alert("at least one of the variables has no value");
}; else if (add.length == 0 & zip.length == 0 & city.length == 0 & state.length == 0) {
alert("all of the variables are empty");
}; else { alert("okay"); }

Categories

Resources