what does if(a) exactly check in javascript - javascript

What does if(a) exactly check in javascript? Can it check undefined? Can it check null? Can it check an empty string?
When do we need to use typeof a == 'undefined' or it could be covered by if(a)?

if evaluates a in a boolean context and uses the result to determine which code branch to execute. undefined, null and the empty string all evaluate to false in a boolean context.
typeof a === "undefined" is useful to check if the name a is defined (e.g. if a variable with that name exists in the current scope). Without this construct, accessing a directly would throw an exception if it is not defined.

Taken from the ECMAscript language specification, the if-Statement works as the following:
12.5 The if Statement
The production IfStatement : if ( Expression ) Statement is evaluated as follows:
Let exprRef be the result of evaluating Expression.
If ToBoolean(GetValue(exprRef)) is false, return (normal, empty, empty).
Return the result of evaluating Statement.
Means, in such cases, it would try a toBoolean conversion which acts like this:
Table 11 - ToBoolean Conversions
Undefined: false
Null: false
Boolean: The result equals the input argument (no conversion).
Number: The result is false if the argument is +0, -0, or NaN; otherwise the result is true.
String: The result is false if the argument is the empty String (its length is zero);
otherwise the result is true.
Object: true

It checks for a value not being false-ish, i. e. false, 0, undefined and null or an empty string. typeof a == 'undefined' is useful when you are curious if a value is undefined or not, since if (a) can't make the distinction between the false-ish values.

The conditional statement will only check for 'true' or 'false'.
in case of undefined the condition is not satisfied and control does not go into the loop.
typeof returns the type of operand. for details you may want to see this link

following values are considered as false in javascript conditions: false, null, undefined,'', 0, NaN

the answer by h2co3 is actually almost correct, you can not check for undefined variables in an if without typeof as this will cause a script error.
if you do this:
<script>
if (a) alert('hello');
</script>
you will get a script error and the if will not be evaluated (the result is the same in the sense that alert is not shown, but that's because the thread execution ended due to the script error.)
if you want to make sure a is defined you need to use the typeof test.

Related

Javascript !undefined gives true?

When I try to alert a negation of variable having undefined value , I get the output as true?
alert(undefined);
alert(!undefined);
The first alert gives undefined and second alert gives true.
Is this the expected behavior. If so then why ?Am I missing some concept/theory about undefined in Javascript?
Is this the expected behavior.
Yes.
If so then why ?Am I missing some concept/theory about undefined in Javascript?
JavaScript has the concept of implicit conversion of values (aka coercing values). When you use the negation ("NOT") operator (!), the thing you're negating has to be a boolean, so it converts its argument to boolean if it's not boolean already. The rules for doing that are defined by the specification: Basically, if the value is undefined, null, "", 0, 0n, or NaN (also document.all on browsers¹), it coerces to false; otherwise, it coerces to true.
So !undefined is true because undefined implicitly converts to false, and then ! negates it.
Collectively, those values (and false) are called falsy values. Anything else¹ is called a truthy value. This concept comes into play a lot, not just with !, but with tests in ifs and loops and the handling of the return value of callbacks for certain built-in functions like Array.prototype.filter, etc.
¹ document.all on browsers is falsy, even though it's an object, and all (other) objects are truthy. If you're interested in the...interesting...history around that, check out Chapter 17 of my recent book JavaScript: The New Toys. Basically, it's to avoid sites unnecessarily using non-standard, out of date features.
Yes, it is the expected behavior.
Negation of the following values gives true in javaScript:
false
undefined
null
0 (number zero)
""(empty string)
eg: !undefined = true
Note: The following checks return true when you == compare it with false, but their negations will return false.
" "(space only).
[ ](empty array),
eg: [ ] == false gives true, but ![ ] gives false
Yes, that's right. undefined is a falsy value.
https://developer.mozilla.org/ru/docs/Glossary/Falsy
https://developer.mozilla.org/ru/docs/Glossary/Truthy
If you need strict checks, you should avoid the non-strict operators:
$ node -p 'undefined == null'
true
and use the strict operators instead:
$ node -p 'undefined === null'
false
Unfortunately a strict negation does not exist.
But you can negate everything twice to get a true boolean equivalent:
$ node -p '!!undefined'
false

What is the difference between truthy and falsy with true and false in JavaScript?

I have a question concerning some concepts in JavaScript such as (truthy, true) and (falsy, false).
I know the type of 1 is not true but the question is: why 1 == true?
What was the main reason of ECMAScript to consider 1 or "ghsagh" as true?
I also cannot understand the meaning of truthy and falsy.
What was the benefit of this consideration?!
JavaScript likes to convert values to other types implicitly whenever possible. Because of that, when comparing booleans to other types of variables, JavaScript uses the same logic as older programming languages. A value that represents empty, null, or zero (such as 0, or "") evaluates to false, and any other value (such as 1, 5, -19, "ghsfsah", or other meaningful content) evaluates to true.
Why does it do this? Well for one it allows developers a small shortcut when checking to see if a variable has content. For example, if a user doesn't give input in a text field, we can easily check to see if a field is empty and prompt the user.
if ( !textfield.value ) {
alert( "Please enter something in the text box" );
}
If you need to see if something is actually true or false, you can use ===.
JavaScript is very flexible about the types of values it requires. If JavaScript wants a boolean, it will convert whatever value you give it to a boolean.
Some values (“truthy” values) convert to true and others (“falsy” values) convert to false.
The following values convert to, and therefore work like, false:
undefined
null
0
-0
NaN
"" // the empty string
All other values, including all objects (and arrays) convert to, and work like, true.
As an example, suppose that the variable o either holds an object or the value null. You can test explicitly to see if o is non-null with an if statement like this:
if (o !== null){
....
}
The strict not-equal operator !== compares o to null and evaluates to either true or false. But you can omit the comparison and instead rely on the fact that null is falsy and objects are truthy:
if (o){
....
}
In the first case, the body of the if will be executed only if o is not null. So the code block will execute even if o is set to undefined.
The second case is less strict: it will execute the body of the if only if o is not false or any falsy value (such as null or undefined). Which if statement is appropriate for your program really depends on what values you expect to be assigned to o. If you need to distinguish null from 0 and "", then you should use an explicit comparison.

What does this javascript code snippet mean?

Here is the code snippet:
var prjId = navObj.itemId || navObj
Does this mean that prjId is either equal to navObj.itemId or navObj? What does it then mean that a variable is equal to navigation object?
Thank you in advance for answers!
This is equivalent to the following:
var prjId;
if(navObj.itemId)
prjId = navObj.itemId;
else
prjId = navObj;
If navObj.itemId is set to false or has not been defined at all,
prjId = navObj;
otherwise:
prjId = navObj.itemId;.
No. The || operator first tries to convert navObj.itemId to a Boolean value.
It will be converted to true if it is already the Boolean value, true, a number other than 0 or NaN, a non-empty string, or an object that is not null or undefined. These are known as "truthy" values.
It will be converted to false if it is already the Boolean value false, 0, NaN, an empty string, null or undefined. These are known as "falsey" values.
If navObj.itemId is "truthy", navObj.itemId is assigned to prjId, otherwise navObj is assigned to prjId.
Further Reading
Logical Operators
It simply means that if the left operand of the logical or operator (||) is a truthy value then return it otherwise return the right operand.
The following values are always falsy:
false
0
empty string
null
undefined
NAN (not a number)
So if navObj.itemId doesn't evaluate to anything of the above, then it will be assigned to the prjId variable.
This is widely used when we have optional parameters in a function, for example. It is a way of specifying the default value for an optional parameter. But of course that's not the only use of it.
It sets prjId to the property of itemId on navObj, if it exists (evaluates to 'truthy'), if it doesn't exist (or it evaluates to 'falsy'), prjId gets set to navObj.

What does an exclamation mark before a variable mean in JavaScript

I'm trying to learn JavaScript by going through some code in an application and I keep seeing !variable in if conditions. For example:
if (!variable.onsubmit || (variable.onsubmit() != false)) {
What is it? Some kind of test if the variable is empty?
! is the logical not operator in JavaScript.
Formally
!expression is read as:
Take expression and evaluate it. In your case that's variable.onsubmit
Case the result of that evaluation and convert it to a boolean. In your case since onsubmit is likely a function, it means - if the function is null or undefined - return false, otherwise return true.
If that evaluation is true, return false. Otherwise return true.
In your case
In your case !variable.onsubmit means return true if there isn't a function defined (and thus is falsy), otherwise return false (since there is a function defined).
Simply put - !variable means take the truth value of variable and negate it.
Thus, if (!variable) { will enter the if clause if variable is false (or coerces to false)
In total
if (!variable.onsubmit || (variable.onsubmit() != false)) {
Means - check if variable.onsubmit is defined and truthy (thus true), then it checks if calling onsubmit returns a result that coerces to true. In a short line it checks if there is no onsubmit or it returns true.
Next time, how do I find this myself?
MDN has a list of operators here.
The language specification specifies such operators, though being the official specification it does contain some jargon which might be hard to understand.
It is a negation operator used for truth tests on a variable.
var myVariable = 1;
if ( ! myVariable )
{
// myVariable evaluates as false
}
if ( myVariable )
{
// myVariable evaluates as true
}
The selected answer already answers the question. One thing to add in this is that ! operator can be used in a rather interesting fashion.
obj = {}
if (!!obj) {console.log('works')} // !!obj = true
obj = undefined
if (!!obj) {console.log('does not work')} // !!obj = false
So double !! will change any expression to a boolean value with no exceptions.
This has a very peculiar use case in some cases.
Lets say there is a function that returns either true or false and nothing else. In that case one could just change return returnValue to return !!returnValue for extra caution (although not need in most of the cases)
Conversely, if a function only accepts true or false and nothing else, one could just call the function as functionA(!!parameter) instead of functionA(parameter), which again is not needed in most of the cases, but could ensure extra security
! is a logic reversal operator, if something was true it will change it to false, if something is false, it will change to true.
example, we know that empty string or 0 in boolean is false.
let a = Boolean("")
console.log(a) // shows false, because empty string in boolean is false
console.log(!a) // shows true, because logic is reversed
easier example:
let a = 5
let b = 1
let c = a > b
console.log(c) // shows true, since a,5 is bigger than b,1
console.log(!c) // shows false, since logic is now reversed

Javascript - If statements check both expression and definition declaration? This is confusing

var boolTrue = true;
var randomObject;
if (boolTrue)
// this will fire
if (randomObject)
// this will fire, because the object is defined
if (!objectNotDefined)
// this will fire, because there is no defined object named 'objectNotDefined'
Coming from a C++ and C# background, I am very familiar with the basic if(expression) syntax. However, I think it is not very readable to have both expressions (true/false) and have object existence also being a expression. Because now if I see a function like below, i don't know if the data coming in is an object (existence/undefined check) or a boolean.
function(data) {
if (data)
// is this checking if the object is true/false or if the object is in existence?
}
Is this just the way it is? I mean, is there anyway to easily read this? Also, where is this documented anywhere in the JS spec (curious)?
In Javascript everything is "true" (or "truthy" to be more precise using Javascript parlance) except false, 0, undefined, null, NaN and empty string.
To avoid confusion use:
if (data === true) // Is it really true?
and
if (typeof data === 'undefined') // Is the variable undefined?
You can check for (non-)existence separately:
if ( typeof variable == 'undefined' ) {
// other code
}
However, the syntax you show is commonly used as a much shorter form and is sufficient in most usecases.
The following values are equivalent to false in conditional statements:
false
null
undefined
The empty string ”
The number 0
The number NaN
It checks whether it is truthy.
In JavaScript, everything is truthy except false, 0, "", undefined, null and NaN.
So, true will pass, as well as any object (also empty objects/arrays/etc).
Note that your third comment is true if you mean "declared but not defined" - a variable that has never been declared throws a ReferenceError on access. A declared, non-defined variable (var something;) is undefined (so, not truthy) so it will indeed pass the condition if you negate it.

Categories

Resources