homepage Welcome to WebmasterWorld Guest from 54.198.140.182
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Visit PubCon.com
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

    
if (var) vs. if (var != )
Rain_Lover




msg:4644144
 9:55 am on Feb 11, 2014 (gmt 0)

Sample:

<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title>Check Text Field Value</title>
<style>
</style>
</head>

<body>
<textarea rows="5" cols="35" id="field" oninput="indicate();"></textarea>
<div id="indicator"></div>
<script>
function indicate() {
var field = document.getElementById('field');
var indicator = document.getElementById('indicator');
if (field.value) {
indicator.innerHTML = 'Some content';
} else {
indicator.innerHTML = 'No content';
}
}
indicate();
</script>
</body>

</html>


Demo: [jsfiddle.net ]

I want to check if the text field is empty or not. I've seen many questions and answers some using if (textarea.value) and some using if (textarea.value != ""). Or the following pair:
if (!textarea.value) vs. if (textarea.value == "").

I wonder what's the difference between them.

 

birdbrain




msg:4644171
 11:56 am on Feb 11, 2014 (gmt 0)

Hi there Rain Lover,
does this help...


<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title>Check Text Field Value</title>

<script>
(function() {
'use strict';

var field,indicator;

function init() {
field=document.getElementById('field');
indicator=document.getElementById('indicator');
field.oninput=function() {
indicate();
}
indicate();
}

function indicate() {
if(field.value.replace(/\s/g,'').length==0) {
indicator.innerHTML='No content';
}
else {
indicator.innerHTML='Some content';
}
}
window.addEventListener?
window.addEventListener('load',init,false):
window.attachEvent('onload',init);
})();
</script>

</head>
<body>

<textarea id="field" rows="5" cols="35"></textarea>
<div id="indicator"></div>

</body>

</html>



birdbrain

Fotiman




msg:4644237
 3:20 pm on Feb 11, 2014 (gmt 0)

Essentially, this comes down to understanding which values are "falsy" in JavaScript. Boolean data types have an explicit true or false value, but everything in JavaScript can be treated as a boolean value, with an implied "truthy" or "falsy" value. The following values are falsy:
* false
* 0 (zero)
* "" (empty string)
* null
* undefined
* NaN (a special Number value meaning Not-a-Number!)

All other values are truthy.
source: [sitepoint.com...]

In your test, you are getting the value property (which is of type DOMString) of a textarea element, which JavaScript will treat as a string. Therefore, with no text entered, field.value is equal to "", which you can see (from the list above) is a falsy value. If you were to enter the value false into the textarea, then field.value would be equal to "false", which is a truthy value.

Basically, field.value will evaluate to false unless 1 or more characters has been entered.

if (textarea.value)
if (textarea.value != "")

The latter one might be more explicitly clear as to what it's checking, while the former is shorter. The latter is using an explicit comparison operator (!=) which could result in one of the values being converted if they were not the same type (for example, if you compared a number against a string). In this case, you will always be comparing string values (because the value attribute returns a DOMString).

if (!textarea.value)
if (textarea.value == "")

Again, this is a case of taking a truthy/falsy value, or performing a comparison.

There's no right or wrong answer. Some would argue that the more explicit comparison makes it more obvious what is actually being tested, while others would argue that the more concise version saves bytes and gives the same result. There may also be some performance difference in the 2 methods, though unless you're looping through massive data (and in this example you're clearly not), the difference is negligible.

Hope that helps.

Rain_Lover




msg:4644240
 3:28 pm on Feb 11, 2014 (gmt 0)

Many thanks, Fotiman!
Perfect -- as always! :)

lucy24




msg:4644321
 8:50 pm on Feb 11, 2014 (gmt 0)

There's no right or wrong answer.

How do you distinguish between these two questions (in English):
has variable abc been defined?
does variable abc have a non-zero (non-"false" etc) value?

Suppose you want to check whether a variable has been defined, but its value might happen to be zero. Can it be done? If it's a toggle, is there a difference between
== false
and
!= true
?

Fotiman




msg:4644328
 9:16 pm on Feb 11, 2014 (gmt 0)

Not sure I understand exactly what you're asking, but I'll take a stab. :)

has variable abc been defined?

if (typeof(abc) != 'undefined')

For example:

var abc; // declared but not defined
if (typeof(abc) != 'undefined') {
// it's safe to do something with abc
}
else {
// oops, someone forgot to initialize abc
}



does variable abc have a non-zero (non-"false" etc) value?

I guess it depends on what you mean here. Are you looking to see if abc has a non-zero value, OR are you looking to see if abc has a non-"false" (aka, truthy) value?

// check that abc is non-zero
if (abc != 0) {}
// check that abc is truthy
if (abc) {}



Suppose you want to check whether a variable has been defined, but its value might happen to be zero. Can it be done?

if (typeof(abc) != 'undefined')

Is that what you were asking?

Fotiman




msg:4644330
 9:22 pm on Feb 11, 2014 (gmt 0)

Or perhaps you're looking for a combination like "is abc defined AND is it truthy?"

if (typeof(abc) != 'undefined' && abc)


is there a difference between
== false
and
!= true

There's no functional difference. In boolean terms, there are only 2 options, truthy and falsy. If something is not one, it must be the other, therefore:
abc == false
is functionally the same as
abc != true

lucy24




msg:4644380
 3:22 am on Feb 12, 2014 (gmt 0)

if (typeof(abc) != 'undefined')

Yes, thanks, it's the word "typeof" that was new to me.

There's no functional difference.

I strongly suspect-- but obviously can't prove retroactively-- that every time I've had a function that worked with "non-false" but not with "true" (or vice versa), it was really because I said "=true" in place of "==true". File under: Been there. Done that.

:: now back to trying to understand why my computer-- in any browser-- refuses to recognize ".clearRect" unless it has been preceded by an alert() within the same function ::

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved