Why does the function return false? [duplicate] - javascript

This question already has answers here:
How does (A == B == C) comparison work in JavaScript?
(6 answers)
Closed 6 years ago.
I'm trying to shorten out the following code:
var a = 0, b = 0;
function() {
return a === 0 && b === 0; // returns 'true'
}
So, I thought something like the following would do:
var a = 0, b = 0;
function() {
return a === b === 0; // returns 'false'
}
Initially, I thought that such syntax would throw an error, but apparently it returns false. Why does a === b === 0 return false?

The expression a === b === 0 is interpreted as if it were written (a === b) === 0. The result is false because (a === b) gives true, and true is not === to 0.
One can imagine a programming language that would understand a chain of expressions connected by == or === or whatever, meaning that all values should be compared in one big "group equality" comparison. JavaScript is not such a language, however.

This is due to how operators are evaluated. In JavaScript, equality operators are evaluated left-to-right (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence)
This means that this:
a === b === 0
Becomes this after one step:
true === 0
Since the number zero is not equal to the boolean true, your expression returns false.

Related

freeCodeCamp Golf code but with Ternary operators instead of else if [duplicate]

I have a function to check sums in an array :
function checkSum(array, sum) {
// array = [1,4,6,11] sum = 10
var answers = [];
var map = new Map();
for (var x = 0; x < array.length; x++) {
if (map.has(array[x])) {
answers.push([sum - array[x], array[x]])
} else {
map.set(sum - array[x])
}
}
answers.length != 0 ? console.log(answers) : console.log("nada")
}
I originally had the last line just return answers; but let's say I don't want to return an empty array -- instead, I'd rather just log a statement.
why doesn't a return in a ternary conditional work such as this:
answers.length != 0 ? return answers : console.log("nada")
You need to use return answers.length != 0 ? answers : console.log("nada"). The reason it fails is because ternary conditions do not support return in their conditions. Infact, the ternary operator evaluates to an expression and expressions do not contain a return statement.
function checkSum(array, sum) {
// array = [1,4,6,11] sum = 10
var answers = [];
var map = new Map();
for (var x = 0; x < array.length; x++) {
if (map.has(array[x])) {
answers.push([sum - array[x], array[x]])
} else {
map.set(sum - array[x])
}
}
return answers.length != 0 ? answers : console.log("nada")
}
console.log(checkSum([1, 4, 6, 11], 10));
The ternary (conditional) operator expects the "expr1" part (where return answers is) to be an expression - that is, something that can be evaluated to a value, which can be used in other expressions. But a return statement is a statement, one which cannot possibly be interpreted as value, or as an expression; hence, a syntax error is thrown.
Instead of
answers.length != 0 ? console.log(answers) : console.log("nada")
either use a standard if statement:
if (answers.length !== 0) return answers;
console.log('nada');
or, if you just want to log, put the conditional operator inside the console.log instead:
console.log(
answers.length === 0
? 'nada'
: answers
)
I used ternary operators like this a lot in the past. It's fun, and keeps it to one line.
It can certainly be done, as Ankit shows, by putting the return statement out front
return answers.length != 0 ? answers : console.log('nada')
But I would recommend you use a classic if statement for this. Particularly since you're testing whether to return a value or just log one.
if (answers.length != 0) {
return answers;
};
console.log('nada')
I would go even further and recommend that you return the same value type no matter what. This will go a long way for using your function, well - functionally. In this case, that would involve still returning the array (even if it's empty) and logging the nada as well if empty.
if (answers.length == 0) {
console.log('nada');
};
return answers;

typescript/javascript condition: [] != []? [duplicate]

This question already has answers here:
How to compare arrays in JavaScript?
(55 answers)
Closed 5 years ago.
I have a condition set up in typescript which compares 2 variables:
this.CurrentSelection == this.PreviousSelection
Both variables are arrays and can be an empty array ([]). In my app, I have a condition where each of these variables is an empty array (Array(0) in CDT watch). When the comparison happens between these 2 empty arrays, the result is false. It seems like [] == []. Any idea about the underlying reason for this? Do I need an additional "or" clause to check for length==0 for this scenario?
You're comparing references. The result will only be true if both a and b reference the same array:
const a = [];
const b = [];
const c = a;
console.log(a === b);
console.log(a === c);
If you want to check if both arrays contain the same values, you could do something like this:
function arrayEquals(a, b) {
return a.length === b.length && a.every((v, i) => v === b[i]);
}
console.log(
arrayEquals([1,2,3], [1,2,3])
);

Why the boolean is different between if (variable) and if (variable == true)? [duplicate]

This question already has answers here:
why does if("string") evaluate "string" as true but if ("string"==true) does not?
(8 answers)
Closed 8 years ago.
I have a question about the if statement and boolean evaluation in JavaScript.
I create on jsFiddle example of that click, there's four different functions which evaluates the types in array through the loop.
But let's focus only on function b and c.
function b(p) {
return (p == true);
}
function c(p) {
if (p) {
return true;
}
else {
return false;
}
}
As you can see in the console the results are different, for example, -1 and 'Hello' are true to the c, while false in b.
Why that's happens?
Thanks for attention!
-1 != true and Hello != true yet both -1 and Hello are truth-y and evaluate to true when cast to a boolean (which is what the if statement does) which is why
if('Hello') {
return true;
} else {
return false;
}
returns true;

Can you use = and == together in the same script?

Had some problems with a script running, which was mainly built around dropdown menus. Single equals = and exactly equals == were both used in the same function, though not same if statement. Could not see anything else amiss and made all uses ==, which seemed to resolve problem. I'm relatively new to Javascript, so was just wondering if combining different styles of equals makes a difference was all. Didn't think it did.
Your question doesn't really make sense - these are different operators. In javascript:
= is the assignment operator, e.g.
var x = 1;
if (x = 1) // This would not compare x to 1, it would assign the value 1 to x
// and then return the value to the if block which would decide
// whether the value is truthy or not (and in this case
// return true).
== is the comparison operator, e.g.
var x == 1; //This would not make sense (or run)
if (x == 1) {
=== does a comparison and ensures that both operands are the same type:
var x = "1";
if (x == 1) { //Returns true
if (x === 1) //returns false.
= assigns values to variables.
== and === are comparison operators.
Of course your script logic changes quite a bit when you exchange = and == operators.

How do I use a variable with a boolean value as a condition in an IF statement in JavaScript? [duplicate]

This question already has answers here:
Is `if (condition = value)` the correct syntax for comparison?
(5 answers)
Closed 8 years ago.
How do I use a variable with a boolean value as a condition in an IF statement in JavaScript?
patt1 = new RegExp ("time");
var searchResult = (patt1.test("what time is it" )); // search for the word time in the string
// and return true or false
If (searchResult = true) // what is the right syntax for the condition?
{
document.write("Word is in the statement");
document.write("<br />");
}
Simply use the value directly and Javascript will determine if it's truthy or not.
if (searchResult) {
// It's truthy
...
}
The problem in your original sample is you are using searchResult = true. This is not a simple conditional check but is instead an assignment which results in a value which is then checked as a conditional. It's roughly the equivalent of saying the following
searchResult = true;
if (true) {
...
}
In Javascript the = operator can be used in a number of ways
= this is used for assignment
== this is used for equality checking with coercion
=== this is used for strict equality checking
if (searchResult == true) {
...
}
This is a test.
Short version:
if (searchResult) {
...
}
if (searchResult) is the same as if(searchResult == true)
if (!searchResult) is the same as if(searchResult == false)

Categories

Resources