JavaScript - (window.addEventListener) - javascript

all
In the if statement fragment "if (window.addEventListener)" what does
the window.addEventListener resolve to. I believe it is a boolean but when is it "true" and when is it "false". I have been researching for a week but to no avail.
I am learning JavaScript by doing self-study, so bear with me.

Any if expression like that — that is, one without an explicit comparison — implicitly converts the expression value to a boolean. The rules in JavaScript are that anything other than null, undefined, 0, "", NaN, or false is considered true.
Thus, testing window.addEventListener like that is a way to check whether that property exists (is not undefined) on the window object.

window.addEventListener in all modern browsers refers to a function. In JavaScript, any value can be coerced to boolean. The result is either false (for 0, "", NaN, null, undefined, and of course, false — the "falsy" values) or true (for all other values — the "truthy" values). So if addEventListener exists on window and has a truthy value (a function reference is truthy), the code branches into the body of the if. If not (obsolete versions of Internet Explorer didn't have it, they had the Microsoft precursor to it called attachEvent), looking up the property will result in undefined, which is falsy.

Just for refer, javascript uses 'Falsy' values that is a value that translates to false when evaluated in a Boolean context.
Reference Falsy

Related

Not condition in javascript for number

I came across a condition which made me strange. I am working on React in that I have given a condition on a render method like this:
if (!this.props.allYearData || !this.props.Growth)
return <Loading />;
However, my page always shows the loading symbol. I console data what I have given in if condition and both data was in define state, but my Growth was showing 0 value., so I commented out this.props.Growth and my page loaded. So I am just wondering why JavasSript didn't consider 0 as a defined value? I always has impression that ! means undefined. Can someone explain this?
0 is falsy. ! is a negation operator. Thus !0 is going to be "not falsy" or truthy. Truthy values in an if statement condition result in the if block will be evaluated.
Details
See MDN for more information on Truthy/Falsy.
Here are a few examples:
true // truthy
false // falsy
!true // falsy (negation operator, it says "opposite of")
!false // truthy
0 // falsy (this is because booleans are represented as 0 and 1 in binary,
// 0 being false)
!0 // truthy
undefined // falsy
!undefined // truthy
Your impression of the ! operator is fairly off in JS (and most other languages). It doesn't mean undefined, it generally always means "not", so:
if (!condition)
means "if condition is not true"
false, undefined, null, 0 and an empty string like '' will all return "falsey" in javascript if used in a conditional operator like if, while everything else will return "truthy". This is a fairly standard practice in most loosely typed languages, you find similar behavior in python, though one important difference is that in JS, an empty array is NOT falsey, whereas in python it is.
If you ONLY want to know if the value is not undefined, it's simple:
if (this.props.allYearData !== undefined || this.props.Growth !== undefined)

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 if(a) exactly check in 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.

Why 'NaN' and 'Undefined' are not reserved keywords in JavaScript?

We can do:
NaN = 'foo'
as well as
undefined = 'foo'
Why are they not reserved keywords?
I think it should be implemented in order to be sure that when we are looking for a number, it is a number :)
If we should use IsNaN() or typeof, why are NaN or undefined needed?
I cannot tell you why, but undefined and NaN are actually properties of the global object:
15.1.1 Value Properties of the Global Object
15.1.1.1 NaN
The value of NaN is NaN (see 8.5). This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.
(...)
15.1.1.3 undefined
The value of undefined is undefined (see 8.1). This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.
There is a difference between the value undefined (NaN) and the corresponding property.
You might notice the [[Writable]]: false. I'm not sure whether this new in ES5 (and might not be adapted by all browsers), but in newer browsers (tested in Firefox 6), assigning a new value to undefined has no effect:
[12:28:15.090] < undefined = "foo"
[12:28:15.093] > "foo"
[12:28:19.882] < undefined
[12:28:19.883] > undefined
So although it seems you can assign a new value, you actually cannot.
Why they are not reserved keywords?
Not sure if there was a specific reason to not make them reserved keywords, but it was decided against it. The language still works. You cannot override these values, so it's fine.
The only way to test whether a number is NaN, is to use isNaN() anyway.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/NaN
NaN is a property of the global object.
The initial value of NaN is Not-A-Number — the same as the value of
Number.NaN. In modern browsers, NaN is a non-configurable,
non-writable property. Even when this is not the case, avoid
overriding it.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined
undefined is a property of the global object, i.e. it is a variable in global scope.
The initial value of undefined is the primitive value undefined.
I'm speculating now, but the reason why I think NaN and undefined are not keywords is because you generally don't assign these values to variables.
var x = undefined; // doesn't make sense, use null!
var y = NaN; // You can't do much with this variable!
undefined basically means uninitialized, and if you want to make it clear that the value is unknown you use null. So undefined usually means not-initialized or the result of JavaScript code gone wrong.
NaN Is rarely assigned manually, simply because you can't do much with this value. It is usually the result of a calculation gone wrong. The makers of JavaScript probably didn't want to give this value the visibility of primitive values.
Also, NaN is also present in other languages and it isn't used as a keyword there either. For example: In C# NaN is represented by Double.NaN, since you don't make a distinction between floating point and integer values in JavaScript, I'm guessing that's why they put NaN with the Global Identifiers!
I hope this clears things up!
Both NaN and undefined are values in JavaScript.
NaN is of number type. (it denotes "not a valid number").
undefined is of undefined type. (when there is nothing assigned to a variable, JavaScript assigned undefined particular in var declaration).
And also both are read-only values(property) of global window object.
So that's why JavaScript cannot make values as a reserved word.
NaN is not a keyword, but it is rather a built-in property of the global object, and as such may be replaced (like undefined, but unlike the keyword this or the literals true, false, and null).
You can test if a value is NaN with the isNaN() function. Moreover NaN is defined to be unequal to everything, including itself.
Or in a nutshell you can say that:
NaN is the value returned when you try to treat something that is not a number as a number. For instance, the results of 7 times "abc" is not a number. The old form of it is Number.NaN. You can test for not-a-number values with the isNaN() function.
One reason is that it is possible to use those words as object keys:
messages = {
NaN: 'that was not a number',
undefined: 'that was not initialized',
default: 'that was something' // not in the original question but is valid syntax
};
console.log (messages.NaN);
While it would be possible to use { 'NaN': 'that was not a number' } and console.log(messages['NaN']), leaving as many words as possible unreserved could make your code easier to read.

Categories

Resources