This question already has answers here:
Javascript compare 3 values
(7 answers)
Closed 2 years ago.
I am working on studying for an entry test, and being self learned I have been working a lot of functions problems. this one has stumped me,
I a to write a function testing to see if 3 values are equal. The code i have tired is:
Function equal(a,b,c){
return a==b==c;
}
as well as:
function equal(a,b,c){
let newEqual=a==b;
return newEqual===c
}
I feel like I am missing something rather simple but have not been able to put my finger on it.
thank you in advance for any insight
a == b == c will be evaluated as :
a == b then checks the result ( true ) and compares it with c => true == c which is false :
const a = 5;
const b = 5;
const c = 5;
const result = a == b == c ;
console.log(result); // false
const a1 = 5;
const b1 = 5;
const c1 = true;
const result1 = a1 == b1 == c1 ;
console.log(result1); // true
You should compare them separately :
const a = 5;
const b = 5;
const c = 5;
const result = a == b && b == c ;
console.log(result);
To check whether all three variables are equal or not, use && operator to add on queries.
&& returns true if all conditions are true.
function equal(a,b,c){
return a == b && b == c;
}
As mentioned by #mplungjan, for strict comparison use === instead of ==.
Try this.
function equal(a,b,c){
return a==b && b==c;
}
You can check it by doing the following:
function equal(a,b,c){
return (a==b) && (b==c)
}
That way you are checking if a == b is true, and b == c is true then all three are equal. In other words, true && true = true
Related
Currently, the only way I know of to do what the title states is by writing the following:
var a = 3, b = 5, c = 3;
if (a === b && a === c) {
// code
}
Or by using the ternary operator:
(a === b && a === c) ? /* code */ : /* else */
Is there a way to check a against both b and c? Something like this perhaps:
if (a === (b && c)) {
// code
}
Obviously this doesn't work as intended, which is why I'm asking the question. Any help is appreciated.
This is not a duplicate of the other 2 - those two are using the OR operator. I'm asking about the AND operator.
For a simple case like this? Definitely not. There are some handy little tricks you can use if you build an array, however. For example:
var my_array = [3, 5, 3];
if(my_array.every(function(el) {return el == my_array[0];})) {
// code
}
Unfortunately no. That's what you have. Unless you convert it to an Array and test with a loop.
if a,b and c are all numbers then you can do simple maths to check for parity of b and c against a.
Simply add b and c, divide by 2 to get the average number and use that to compare against a.
var a = 3, b = 5, c = 3;
a === (b + c)/2
? console.log('yes')
: console.log('no')
// console gives "no"
var a = 3, b = 3, c = 3;
a === (b + c)/2
? console.log('yes')
: console.log('no')
// console gives "yes"
var a = 3, b = 4, c = 2;
a === (b + c)/2
? console.log('yes')
: console.log('no')
// console gives "yes"
This question already has answers here:
Javascript if statement with multiple permissible conditions [duplicate]
(4 answers)
Closed 5 years ago.
Why doesn't this work:
if (x != (a || b || c)) {
doStuff();
}
It's meant to check whether x is NOT equal to a OR b OR c.
EDIT: How would I achieve a check for whether x is NOT equal to a OR b OR c?
EDIT: Ok, it's a duplicate. What do I do now, take minus points even after realizing my mistake? :P
To use multiples values like you wanna just:
var x = 'x';
var a = 'a';
var b = 'b';
var c = 'c';
function doStuff() {
console.log(1)
}
// exemple 1
if(x == a || x == b || x == c) {
doStuff();
}
function isSameValue(element, index, array) {
return element === x;
}
// exemple 2
if([a, b, c].some(isSameValue)) {
doStuff();
}
// exemple 3
[a, b, c].includes(x);
I know you can do ternary expressions in Javascript for an if - else statement, but how about an else- else if- else statement? I thought that surely this would be supported but I haven't been able to find any info about it and wasn't able to get it to work just hacking around.
In contrast to Robby Cornelissen's answer - there is no problems with readability if you format it properly (and not writing PHP, since it messed up the operator by making it left-associative in contrast to all other languages that have that construct):
var y =
x == 0 ? "zero" :
x == 1 ? "one" :
"other";
EDIT
What I was looking for is a shorter version of "if expression 1 is true, return expression 1. Else if expression 2 is true, return expression 2. Else return expression 3". Is there no clean way to do this?
There is: expression1 || expression2 || expression3. (It would have been nice if you had put this into your question in the first place.) This is commonly used for default values:
var defaults = null;
function hello(name) {
var displayName = name || (defaults && defaults.name) || "Anonymous";
console.log("Hello, " + displayName + ".");
}
hello("George");
// => Hello, George.
hello();
// => Hello, Anonymous.
defaults = {};
hello();
// => Hello, Anonymous.
defaults.name = "You"
hello();
// => Hello, You.
However, it is important to be aware of the conditions for truthiness. For example, if you expect "" or 0 to be a valid value that does not need to be replaced by a default, the code will fail; this trick only works when the set of possible non-default values is exactly the set of truthy values, no more and no less. E.g.
function increment(val, by) {
return val + (by || 1); // BUG
}
increment(10, 4);
// => 14
increment(10, 1);
// => 11
increment(10);
// => 11
increment(10, 0);
// => 11 <-- should be 10
In this case you need to be explicit:
function increment(val, by) {
return val + (typeof(by) === "undefined" ? 1 : by);
}
I wouldn't recommend it because of readability, but you could just nest ternary operators:
var y = (x == 0 ? "zero" : (x == 1 ? "one" : "other"));
This would be the equivalent of:
var y;
if (x == 0) {
y = "zero";
} else if (x == 1) {
y = "one";
} else {
y = "other";
}
You can extend a ternary condition if you're good. It gets to be messy though.
var number = 5;
var power = 2;
var ans = Math.pow(number,power);
var suggest = ( ans == 5 ? 5 : ans == 10 ? 10 : ans == 15 ? 15 : ans == 25 ? "works" : null);
console.log(suggest);
I may have added to many because I'm on my phone haha but try it in your developer panel.
I obviously got something terribly wrong here so I'll appreciate any good 'ol advice.
How come that if I write
var x='';
var y="12345";
(y.substring(0, 3) === "000"||"999") ? x=1: x=0;
console.log (x, y.substring(0, 3));
The answer would be 1 "123"
instead of 0 "123"?
Thanks y'all!
First the ternary operator syntax is not how you use it normally and you'll have to make two comparisons instead of one.
var str = y.substring(0, 3);
x = (str === "000"|| str === "999") ? 1 : 0;
MDN
For condition ? expr1 : expr2
If condition is true, the operator returns the value of expr1;
otherwise, it returns the value of expr2.
The or operater works like this: a || b
Where each statement is isolated from eachother, basically you can make i more visible like this:
var c1 = y.substring(0, 3) === "000";
var c2 = "999";
if ( c1 || c2 ) { x = 1; } else { x = 0; };
See the problem here?
I would rewrite your statement so something like this:
x = ["000", "999"].indexOf(y.slice(0, 3)) > -1 ? 1 : 0;
Note how I'm using Array.prototype.indexOf to test multiply cases:
["000", "999"].indexOf(y.slice(0, 3)) // returns the index of the array or -1 if not in the array.
What is this javascript syntax?
parent[currentPart] = parent[currentPart] || {};
especially this part || {}
It is taken from this javascript code (at http://elegantcode.com/2011/01/26/basic-javascript-part-8-namespaces/)
// Creates a namespace
function namespace(namespaceString) {
var parts = namespaceString.split('.'),
parent = window,
currentPart = '';
var length = parts.length;
for (var i = 0; i < length; i++) {
currentPart = parts[i];
parent[currentPart] = parent[currentPart] || {};
parent = parent[currentPart];
}
return parent;
}
The || operator in javascript works a little differently than many other languages. In javascript, it evaluates to the first 'truthy' value, allowing a "fallthrough" sort of behavior.
Example:
var a = false;
var b = "asdf";
alert(a || b); //alert box with "asdf" since a was false
var c = true;
var d = "asdf";
var e = false;
alert(c || d || d); //alert box with true. d and e were never evaluated, so "asdf" isn't returned. This is called "short-circuiting" operation.
The && operator works similarly in that it evaluates to the first 'falsey' value or the last 'truthy' value if everything is true:
var a = true;
var b = "asdf";
alert(a && b); //alert box with "asdf"
alert(b && a): //alert box with true
var c = 6;
var d = 0;
alert(c && d); //alert box with 0
alert(d && c); //alert box with 0
In JS, logical operators (e.g. &&, ||) return a value, which, when part of an expression, can be used in an assignment.
Thus in the code below:
var a = false
, b = 'hello'
, c = (function() { return a || b })()
c is assigned the string 'hello', because || returns 'hello' to the return statement, which, in turn, returns it from the function and makes the assignment to c.
The definition of the || operator is:
expr1 || expr2 Returns expr1 if it can be converted to true; otherwise, returns expr2.
If parent[currentPart] does not exist, then the expression evaluates to an empty object ({}) and thus parent[currentPart] is initialized to that empty object. If it does exist, then it is left unchanged (that is, it is assigned to itself). The effect is to guarantee that parent[currentPart] always has a (non-falsy) value.
In the expression a = b || c, a will be set to b if b evaluates to true; otherwise, a will be set to c. This is often used because null and undefined both evaluate to false, so it's shorter than saying something like if (b == null) {a = c} else {a = b}.