does ""===null? - javascript

when comparing string to see if it is empty, is there any difference between:
if($string==NULL){
//do work
}
and
if($string==""){
/do work
}
Just wondering beacuse I want to know which one is more effective in detecting blank input.

You're kind of asking several vaguely-related questions here. PHP and JavaScript aren't the same language, and you're referencing different operators in the question title and body. In any event:
PHP:
'' == null true
'' === null false
JavaScript:
'' == null false
'' === null false
You might want to consider these tests for general "did I get something in this string variable":
PHP:
if(!empty($string)) {
// do work
}
JavaScript:
if($string) {
// do work
}

Yes, there is a difference. Checking if $string==Null will actually check to see if the variable has been initialized at all, and $string=="" looks to see that the string actually exists, but that it just holds a 0-length string

To test in PHP:
<?php echo var_dump("" === NULL); ?>
To test in JavaScript:
console.log("" === null)
Both produce false, so you can't do that in either language.
Even if it worked, it is not obvious what you mean by comparing with null; this isn't C where it's constantly used for missing values. If you're going to get a string as input, comparing to the empty string is more clear.

I`am using empty() function in PHP. It is not depends on type of the variable. However, when comparing with "==" (not "==="!), NULL becomes empty string ("") when comparing to string.

does “”===null?
No.
Behold the power of testing... for javascript anyway.
alert("" === null);

In JavaScript, the answer is no. An empty string does not equal null, though both are falsey values.

Check the manual, "" is not identical to null because the former is a string and the latter is null, and === checks for equal types as well as equal values.

Take a look at this: http://php.net/manual/en/language.operators.comparison.php

Related

Difference between equality checking inside 'if condition' vs 'console.log' [duplicate]

This question already has answers here:
Empty arrays seem to equal true and false at the same time
(10 answers)
Closed 4 years ago.
I was trying out a code snippet and the results are different for an empty array check inside a console.log statement and in a conditional statement.
Help/Thoughts on why this is different?
Thanks in advance!
//Output: true
if([]) {
console.log(true)
} else{
console.log(false)
}
//Output: false
console.log([] == true)
You seem to be running into a known JavaScript quirk.
"[] is truthy, but not true"
The problem isn't where you are doing the evaluations, but rather that the two evaluations which seem identical are actually different.
See
https://github.com/denysdovhan/wtfjs#-is-truthy-but-not-true
My assumption is that the if/else block, in part of its "truthful" test is checking if something exists (not just if it is true or not) -- wherein the straight console print is comparing the value of the empty array against a boolean (which would be false)
let test = 'apple';
if( test ){
console.log( 'if/else: ' + true );
}else{
console.log( 'if/else: ' + false );
}
console.log( 'log: ' + ( test == true ) );
The two snippets are actually doing different things, hence the different results.
The first, with [] as the condition of the if statement, coerces the array to a Boolean value. (if, naturally enough, only works on Booleans, and JS will happily convert the given value if it isn't already Boolean.) This produces true - all objects in JS are "truthy", which includes all arrays.
For the second snippet, you are using the "loose equality" operator == - for which the JS specification provides a set of rules for how to convert the values into other types, eventually reaching a straightforward comparison between two values of the same type. You might want, or hope, that comparing a non-Boolean to true or false in this situation coerced the non-Boolean to Boolean - but this isn't what happens. What the specification says is that first the Boolean is coerced to number value - resulting in 1 for true (and 0 for false). So it reduces to [] == 1 - which will go through a few more conversions before resulting in a false result.
The key point is that no conversion to Boolean happens in the second case. If you think this is stupid, you're probably right. This is a bit of a gotcha, and one of the reasons many guides tell you never to use == in JS. I don't actually agree with that advice in general (and hate linters telling me to always use === in any circumstances) - but you do have to be aware of some dangers. And using == to compare a value to true or false is something to always avoid.
Luckily, if you want to test if x is truthy or falsy, you have a very short and understandable way to do it - the one you used in the first snippet here: if (x)
[edit] So my original answer was confusing as heck, and there are some incongruencies in the many answers you find on this subject all over the internet; so, let me try this again:
Part 1: Why they are Different
if([]) and if([] == true) are not the same operation. If you see the below example, you will get the same result when doing the same operation.
//Output: false
if([] == true) {
console.log(true);
} else{
console.log(false);
}
//Output: false
console.log([] == true);
Part 2: Why it matters AKA: the confusing bits
In JS, the following is a common expression used to see if an object/variable exists:
var foo = "Hello World";
if (foo) ...
From a design perspective, this test is not important to see if foo is equal to true or false, it is a test to see if the program can find the object or variable foo. If it finds foo, then it executes the results in the "then" condition, otherwise you get the "else" condition. So, in this case, it will convert foo to either false for does not exist, or true for does exist. So in this case the string is reduced to a boolean.
In contrast:
var foo = "Hello World";
if (foo == true) ...
Is typically trying to find out if the value of foo actually equals true. In this case, you are comparing the value of foo "Hello World" to a boolean, so in this case, "Hello World" does not equal true.
Just like foo, [] can be evaluated more than one way. An empty array is still an object; so, in the first case, it coerces to true because it wants to know if [] can be found; however, [] also equals ['']. So now picture this:
if (['bar'] == 'bar') ...
In this case, JS will not look at ['bar'] to see if it is there, but as an object containing a single value which it can convert to the string, 'bar'.
So:
if([]); // is true because it is an object test that evaluates as (1 === 1)
and
if([] == true) // is false because it is a string test that evaluates as ('' == 1) to (0 === 1)

Is it incorrect to use eval() within this function? Can I accomplish the same functionality without it somehow?

I'm trying to write a function I can use to test all for falsy values, keeping it concise since it will be run quite often serverside.
function is_falsy(val){
val = eval(String(val).toLowerCase());
return !!val;
}
I wonder if there's any way it could be done shorter, or what the possible negative implications of using eval() might be. JSBIN tells me it is "evil".
JSBIN
Assuming that val is a string that represents a JavaScript literal then we can take advantage of the fact that the only false-y values in JavaScript are:
0 (+ or -)
NaN
the empty string ('') or ("")
null
undefined
false
Thus, ignoring edge-cases (like 0.0) we could write it like so (a lower case can be performed as in the original code):
function is_falsey_literal (lit) {
if (['""', "''", "null", "undefined", "false", "0", "NaN"].indexOf(lit) >= 0) {
return true;
}
// Ideally there are more checks on numeric literals such as `-0` or `0.0`.
return false;
}
If needing to check a full expression then eval may "work" and is likely more practical when compared to writing a full JavaScript-in-JavaScript parser. For instance, in the above, the input string of (void 0) will be "true" although it evaluates to undefined which is definitely not a truth-y value.
Of course, perhaps the original data can be written/consumed such that there is no need for such a construct at all ..
There should never be any need to treat a string containing false or undefined as falsy. Doing so is inviting false positives (or false negatives) on possibly completely unrelated data.
Imagine what else would be treated as "falsy":
!true
!1
!!true
it's begging for mysterious bugs in your application further down the line.
The program flow should make sure that an undefined value actually arrives at your testing script as a literal undefined, not a string "undefined".
If you only want to test is falsy, then the below is enough.
function is_falsy(val){
return !val;
}
If you want to test whether a string is falsy value like 'false', then
function is_falsy(val){
try {
return !JSON.parse(String(val).toLowerCase());
} catch(e) {
return false;
}
}

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).

jquery check if json var exist

How can I with jquery check to see if a key/value exist in the resulting json after a getJSON?
function myPush(){
$.getJSON("client.php?action=listen",function(d){
d.chat_msg = d.chat_msg.replace(/\\\"/g, "\"");
$('#display').prepend(d.chat_msg+'<br />');
if(d.failed != 'true'){ myPush(); }
});
}
Basically I need a way to see if d.failed exist and if it = 'true' then do not continue looping pushes.
You don't need jQuery for this, just JavaScript. You can do it a few ways:
typeof d.failed- returns the type ('undefined', 'Number', etc)
d.hasOwnProperty('failed')- just in case it's inherited
'failed' in d- check if it was ever set (even to undefined)
You can also do a check on d.failed: if (d.failed), but this will return false if d.failed is undefined, null, false, or zero. To keep it simple, why not do if (d.failed === 'true')? Why check if it exists? If it's true, just return or set some kind of boolean.
Reference:
http://www.nczonline.net/blog/2010/07/27/determining-if-an-object-property-exists/
Found this yesterday. CSS like selectors for JSON
http://jsonselect.org/
You can use a javascript idiom for if-statements like this:
if (d.failed) {
// code in here will execute if not undefined or null
}
Simple as that. In your case it should be:
if (d.failed && d.failed != 'true') {
myPush();
}
Ironically this reads out as "if d.failed exists and is set to 'true'" as the OP wrote in the question.

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.

Categories