Any purpose in using Not Not in if statement - javascript

I have seen JS code written using
if(!!a){
//something here
console.log('something');
}
I don't understand what the preference of doing this is compared to:
if(a){
//something else here
console.log('something else here');
}
Do you gain anything by typing !! in the expression with JS?

The if statement checks for the truthiness of the expression passed to it. The !! coerces truthiness into boolean. Therefore doing:
if (!!a) {}
is exactly the same as:
if (a) {}
There is nothing to be gained from using !! in this case
This smells strongly of cargo-cult programming or influence form another language.

It's about truthy and falsy:
Everything in JavaScript has an inherent Boolean value, generally
known as either truthy or falsy.
The following values are always falsy:
false
0
""
null
undefined
NaN
All other values are truthy, including "0" (zero in quotes), "false"
(false in quotes), empty functions, empty arrays, and empty objects.
In your case, I don't think it is useful, since an if already uses the truthy/falsy value of the condition:
if (0) {
// this will never be executed
}
The !! can be used like this:
return !!myObject.length; // returns true if myObject.length > 0, false otherwise

Some samples to understand :
var el = document.getElementById('el');
var log = function(val){
// el.innerHTLM+='<div><pre>' + JSON.stringify(val , null , ' ') +'<\pre></div>';
el.innerHTML+='<div><pre>' + val +'<\pre></div>';
};
var a = 'Helo';
log('a = ' + a);
log('! a = ' + ! a);
log(' !! a = ' + !!a );
log('---');
log('true =' + true);
log('!true =' + !true);
log('!!true =' + !!true);
log('---');
log('false =' + false);
log('!false =' + !false);
log('!!false =' + !!false);
log('---');
log('null =' + null);
log('!null =' + !null);
log('!!null =' + !!null);
log('---')
log('undefined =' + undefined);
log('!undefined =' + !undefined);
log('!!undefined =' + !!undefined);
log('0 =' + 0);
log('!0 =' + !0);
log('!!0 =' + !!0);
log('---');
log('1 =' + 1);
log('!1 =' + !1);
log('!!1 =' + !!1);
log('---');
log('[] =' + []);
log('![] =' + ![]);
log('!![] =' + !![]);
log('---');
log('{} =' + {});
log('!{} =' + !{});
log('!!{} =' + !!{});
<div id='el'>Use case:</div>

Related

Javascript if statement come back false when it should be true

I don't understand why the temp variable is only returning false. I have tried == just to see if using strict comparison was the issue, but it didn't change. Just to double check, I'm making sure the variables are of the same type by printing their type in console.
Another odd thing that is happening is when I use this line, console.log('temp = ' + temp); to see what is inside of temp, nothing but a blank space will print. But if I use console.log(temp);, it will print what is stored in temp. The console.log('temp = ' + temp); seems to have fixed itself, so nevermind with that issue, but it's still not returning true.
var upFormData = formData.toUpperCase();
console.log('Form Data: ' + upFormData);
degrees[str] = [];
degrees[str][0] = data[0];
for(var i = 1; i < data.length; i++)
{
var temp = data[i][5].toUpperCase();
console.log(temp);
//console.log('temp = ' + temp);
console.log('upFormData = ' + upFormData + ' ' + typeof upFormData + ' ' + typeof temp);
if(upFormData === temp)
{
console.log('MATCH');
}
else
{
console.log('NOT A MATCH');
//console.log(temp);
//console.log('upFormData = ' + upFormData + ' ' + typeof upFormData + ' ' + typeof temp);
}
Results of this script:
Can someone help explain what I'm not doing? And please let me know if you need more information.
EDIT:
Looks like you are want to check if the value entered in form (formData) is in data array.
Use some
var upFormData = formData.trim().toUpperCase();
var hasFormData = data.some( s => s[5].trim().toUpperCase() === upFormData ); //hasFormData will return true if any value matches
If you want to filter out data values which matches forData value, use filter
var matchedData = data.filter( s => s[5].trim().toUpperCase() === upFormData );

Parameter Checks as Null/Undefined Despite Console Showing a Value

I have a function that references things. For the purpose of fixing the bug, I've removed other case statements (they don't change nor fix the problem). I have also removed the return, because that's irrelevant at this stage too.
For some reason, say I pass an element in the DOM: Referencer('id', 'hello'), despite Chrome Console telling me that type = 'id' that if (type === null || "" || "undefined") fires every single time.
Here's a JSBin: https://output.jsbin.com/secuciyeko
function Referencer(type, value) {
// Standard Declaration
"use strict";
// Open Console Group
window.console.groupCollapsed("[Scriptbase.js]/[Referencer] # " + Scriptbase.Time());
// Log Status
window.console.info("[Process Started # " + Scriptbase.Time() + "]");
/* ------- Computation ------- */
// Local Variables
var a = null;
// Log Status
window.console.log("[Success # " + Scriptbase.Time() + "]: Checking for unusable values.");
// Value Validation
if (type === null || "" || "undefined") {
// Log Status
window.console.error("[Failure : " + Scriptbase.Time() + "] : Failure to look up '" + type + "' with the value '" + value + "'.");
// Close Console Group
window.console.groupEnd();
// Exit Method
return;
}
if (value === null || "" || "undefined") {
// Log Status
window.console.error("[Failure : " + Scriptbase.Time() + "] : Failure to look up '" + type + "' with the value '" + value + "'.");
// Close Console Group
window.console.groupEnd();
// Exit Method
return;
}
// Log Status
window.console.log("[Success : " + Scriptbase.Time() + "] : Looking up '" + type.toUpperCase() + "' with the value of '" + value + "'.");
// Look Up Value
switch (type) {
case "id":
// Variable Assignment
a = document.getElementById(value);
// Log Status
window.console.log("[Success : " + Scriptbase.Time() + "]: Found an DOM ID of '" + value + "'.");
// Break Case
break;
}
}
With this
if (type === null || "" || "undefined") {
You are saying:
if type is equal to null
or if empty string is true
or if string 'undefined' is true
You are not actually comparing type to '' or 'undefined'.
You can change to
if (!type) {
Then if it is empty, null or undefined it will go in the condition.
Read about
Truthy
Falsy

Recursive Function not working correctly

I have a recusive function that is supposed to loop through a json object and output the expression. However, my recusion seems to be off because it's outputting field1 != '' AND field3 == '' when it should be outputting field1 != '' AND field2 == '' AND field3 == ''
I've tried a couple different things and the only way I can get it to work is by creating a global variable outstring instead of passing it to the function. Where am I off? When I step through it, i see a correct result but once the stack reverses, it start resetting outstring and then stack it back up again but leaves out the middle (field2).
JSFiddle
function buildString(json, outstring) {
var andor = json.condition;
for (var rule in json.rules) {
if (json.rules[rule].hasOwnProperty("condition")) {
buildString(json.rules[rule], outstring);
} else {
var field = json.rules[rule].id;
var operator = json.rules[rule].operator;
var value = json.rules[rule].value == null ? '' : json.rules[rule].value;
outstring += field + ' ' + operator + ' ' + value;
if (rule < json.rules.length - 1) {
outstring += ' ' + andor + ' ';
}
}
}
return outstring;
}
var jsonObj = {"condition":"AND","rules":[{"id":"field1","operator":"!= ''","value":null},{"condition":"AND","rules":[{"id":"field2","operator":"== ''","value":null}]},{"id":"field3","operator":"== ''","value":null}]};
$('#mydiv').text(buildString(jsonObj, ""));
The function has a return of a string.
When you call the function recursively from within itself, you aren't doing anything with the returned string from that instance, just calling the function which has nowhere to return to
Change:
if (json.rules[rule].hasOwnProperty("condition")) {
buildString(json.rules[rule], outstring);
}
To
if (json.rules[rule].hasOwnProperty("condition")) {
// include the returned value in concatenated string
outstring += buildString(json.rules[rule], outstring);
}
DEMO
Why so complicated?
function buildString(obj) {
return "condition" in obj?
obj.rules.map(buildString).join(" " + obj.condition + " "):
obj.id + " " + obj.operator + " " + string(obj.value);
}
//this problem occurs quite often, write a utility-function.
function string(v){ return v == null? "": String(v) }

Pass JavaScript Function in href

I am working on VS2103 Cordova App. I have created list of items. I want to pass data to another page when i press on item. I've created this list by jQuery.
Here is my code :
for (var i = 0; i < data.length; i++) {
if ((Provider == "Doctors")) {
$("#list").append('<li class="list-message" ><a class="w-clearfix w-inline-block" href="javascript:ProviderDetails(' + data[i].DoctorName + ',' + data[i].DoctorAddress + ',' + data[i].DoctorPhone + ',' + data[i].DoctorPhone2 + ',' + data[i].DoctorPhone3 + ',' + data[i].DocLat + ',' + data[i].DocLong + ',' + data[i].DoctorNotes + ',' + data[i].Category + ');" data-load="1"><div class="w-clearfix column-left"><div class="image-message"><img src="images/Doctors.png"></div></div><div class="column-right"><div class="message-title">' + data[i].DoctorName + '</div><div class="message-text">' + data[i].DoctorAddress + '</div></div></a></li>');
}
}
And here is my function :
function ProviderDetails(Name, Address, Tel, Phone2, Phone3, Lat, Lang, Notes, Category) {
localStorage.setItem("Name", Name);
localStorage.setItem("Address", Address);
localStorage.setItem("Tel", Tel);
localStorage.setItem("Phone2", Phone2);
localStorage.setItem("Phone3", Phone3);
localStorage.setItem("Lat", Lat);
localStorage.setItem("Lang", Lang);
localStorage.setItem("Notes", Notes);
localStorage.setItem("Category", Category);
window.location.href = "../Details.html";
}
It doesn't do any thing when i press any items . Any help ?
Pay attention on how you build the string:
href="javascript:ProviderDetails(' + data[i].DoctorName + ',' ......
you need to add the string delimiters:
href="javascript:ProviderDetails(\'' + "data[i].DoctorName" + '\',\'' .....
Your function is declared as:
function ProviderDetails(Name, Address, Tel, Phone2, Phone3, Lat, Lang, Notes, Category)
{
....
}
Now, because your function expects strings as input you can call your function as:
ProviderDetails('string1', 'string2', .....)
Your javascript loop instead produces:
ProviderDetails(string1, string2, .....)
For javascript now the parameters are considered as variables, i.e., string1 is no more a string but a value contained in the variable string1.
But because you do not have such a variable your function call does not work.
So, the delimiters are important to instruct js to understand the beginning and end of a string.
As a delimiter you can you the symbols: ' or ".
But you need to escape the delimiter itself if you want to use it inside the strings:
var a = 'this isn't a string'; // wrong because the inner delimiter is not escaped.
var a = 'this isn\'t a string'; // OK because the inner delimiter is escaped
Of course if you use inside the string the other delimiter you do not need to escape it.
var a = "this isn't a string"; // this is OK

Can't save id to a variable

I'm having trouble assigning an id field to a variable.
Given this:
var temp;
if(!data.obj.id){
console.log('*************** assigning ' + data.obj.id + ' to temp');
temp = data.obj.id;
console.log('temp is',temp);
}else if(!data.obj._id){
console.log('*************** assigning ' + data.obj._id + ' to temp');
temp = data.obj._id;
console.log('temp is: ',temp);
}
console.log('**************',data.obj._id);
console.log('**************',temp);
Neither of those if statements are ever true, and the console logs return,
************ 538cdd6fca343660389d4d69
************ undefined
EDIT:
I've also tried:
if(data.obj.hasOwnProperty('id')){
console.log('*************** assigning ' + data.obj.id + ' to temp');
temp = data.obj.id;
console.log('temp is',temp);
}else if(data.obj.hasOwnProperty('_id')){
console.log('*************** assigning ' + data.obj._id + ' to temp');
temp = data.obj._id;
console.log('temp is: ',temp);
}
console.log('**************',data.obj._id);
console.log('**************',temp);
And temp is still undefined.
EDIT2:
I've changed my code to this:
var temp;
if(data.obj.hasOwnProperty('id')){
console.log('*************** assigning ' + data.obj.id + ' to temp');
temp = data.obj.id;
console.log('temp is' + temp);
}
if(data.obj.hasOwnProperty('_id')){
console.log('*************** assigning ' + data.obj._id + ' to temp');
temp = data.obj._id;
console.log('temp is' + temp);
}
console.log('**************',data.obj._id);
console.log('**************',data.obj.id);
console.log('**************',temp);
And I get:
************** 538ce08c6ced88c020ecbd07
************** 538ce08c6ced88c020ecbd07
************** undefined
You didn't log the value of data.obj.id, but presumably it is also true, like _id (in the sense that their negation returns false). Therefore, neither the first nor the second if clause are fulfilled in your example, and none of the two branches execute. It seems like you want to remove the negation operators, !, from both your if clauses, but it's hard to tell without context.

Categories