|| ('OR') operator alternative - javascript

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.

Related

Comparing 3 identical values for equality using Javascript [duplicate]

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

JavaScript Weird behavior in a condition

there's something that i just solved but I don't understand why i got that kind of behavior, here's my js code
function fibonacci () {
let fibonacciNumber = document.getElementById("my-input").value;
let numberInitialize = 0;
let numberNext = 1;
let sum = numberInitialize + numberNext;
if (fibonacciNumber === "" || fibonacciNumber === 0) {
return (0);
}
for (index = 1; index < fibonacciNumber; index++)
{
numberInitialize = numberNext;
numberNext = sum;
sum = numberInitialize + numberNext;
console.log(sum);
console.log("premier tour");
}
console.log(sum);
document.getElementById("fibo-result").innerHTML = `${sum}`;
}
So on the html side I just have an input and im writing down number, my questions concerned this line of code
if (fibonacciNumber === "" || fibonacciNumber === 0) {
return (0);
}
when im writing down 0, its still printing one but i write the condition like that
if (fibonacciNumber === "" || fibonacciNumber <= 0) {
return (0);
}
its working and when I got 0 as an input nothing is printed like i wanted, my question is: Why when im putting fibonacciNumber === 0 return (0) its not working properly its 0, the condition match no ?
Thanks guys
The reason is because your field actually has the string "0". The identity operator (===) will not do any type coercion before comparing the values, so "0" === 0 is false.
Numeric comparison operators like <= will do type coercion, so "0" <= 0 will evaluate to true.
You can see this all in action below.
console.log("0" === 0);
console.log("0" <= 0);
You will need to use parseInt() and then treat the input as integer.
let fibonacciNumber = parseInt(document.getElementById("my-input").value);

Javascript comma syntax, and complex expressions, minified, obfuscated: please help me understand a piece of code

I need to understand some pieces of code. I feel fine with the syntax of Java, C++, PHP, but Javascript syntax is still a "dark forest" for me. Here are the original forms and possible interpretations, I mean equivalents in terms of program logic:
1.
var o,
a,
s = "https://widget.kiwitaxi.com",
c = e.createElement("iframe"),
l = e.getElementById(r.target),
p = r && r.height_bias ? 4 + r.height_bias : 4,
u = !1,
f = parseInt(r.min_height, 10) ? parseInt(r.min_height, 10) : r.hide_form_extras && !r.default_form_title ? 304 : 386;
I'm almost sure about this one, here I can replace commas with semicolons and add VAR statement to the beginning of each line and it will produce the same results, am I right?
var o;
var a;
var s = "https://widget.kiwitaxi.com";
var c = e.createElement("iframe");
var l = e.getElementById(r.target);
var p = r && r.height_bias ? 4 + r.height_bias : 4;
var u = !1;
var f = parseInt(r.min_height, 10) ? parseInt(r.min_height, 10) : r.hide_form_extras && !r.default_form_title ? 304 : 386;
And this one is really tough for me, I cannot presume any interpretation
As I understand:
"o" is evaluated to s + "/w", then is concatenated with "-", and then with ".html" ? Are any conditions applied to that string building, I mean, can any of that two concatenations be applied by condition in this code ?
What does comparison == operator do in the statement (the part "en" == r.language...), which variable receives that result ? Or can it be just an obfuscation trick ?
And the last one, after the last comma, r.banner_id || (r.banner_id = "22995c4e"); Here goes an assignment, that is clear, but what is the point of other stuff in this part ? Is the assignment made by condition here (if r.banner is not undefined-or-null-or-false) ?
o = s + "/w",
"en" == r.language && (o += "-" + r.language.toString().toLowerCase()),
("biletik" == r.theme || "ostrovok" == r.theme) &&
(o += "-" + r.theme.toString().toLowerCase()),
o += ".html",
r.banner_id || (r.banner_id = "22995c4e");
"en" == r.language && (o += "-" + r.language.toString().toLowerCase()),
Ooh...that line's tricky.
So, example: If you were to write var myVar = false && thisFunctionThrowsError(), where the function would throw an exception if it were called, that would actually not return an error - because anything after the ampersand won't be evaluated. It's called short-circuit evaluation. In this case, someone has cut out the part where he checks the result of the && comparison, and only uses it to determine whether or not to run the right side.
So, if I write:
"biletik" == r.theme && (o += "-");
That means it will add a dash to o only if r.theme == 'biletik'.
The last line is the opposite; it looks like it's a lazy-initializer. If r.banner_id is null, that evaluates to false - so it runs the second part of the ||, initializing it to 22995c4e.

Extended Ternary expression

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.

A quick way to test equality of more than 2 values at once?

I was wondering if there was a quick way to test the equality of more than two values in js. Something similar to (= 6 6 6).
In the console, I tried things like...
1 == 1 == 1 == 1
true
2 == 2 == 2 == 2
false
0 == 0 == 0
false
0 == 0 == 0 == 0
true
...which was amusing, but also puzzling.
Is there a quick way of doing this in js?
Thanks.
The reason you got unexpected behavior is because we need to adjust your expectations in js a bit ;) 2 == 2 == 2 == 2 does 3 comparisons, all from left to right. The first comparison is the leftmost 2 == 2, which evaluates to true. After that we get the result of the first comparison being compared to (what is in this case) the 3rd 2. Ie, true === 2, which is false. And finally, we get false === 2, which is also false.
It might help to visualize it as such:
(((2 == 2) == 2) == 2)
I think in general a === b && b === c might be what you're looking for.
EDIT: Ah, and sorry I keep switching out the == for ===. It's just habit. And it's a habit I'd recommend. the === operator doesn't do type casting, so it evaluates the value proper, not a casted version of the value.
It's because true == 1 but true != 2
You can try:
function isEquals() {
var flag = true;
for(var i=1; i<arguments.length; i++) flag = flag && (arguments[i] == arguments[0]);
return flag;
}
isEquals(2,2,2); // true
or:
function isEquals() {
var ar = arguments;
return Array.prototype.every.call(arguments, function(a){return a==ar[0];});
}
Yes you can, but you need to use the "Logical Operators" like the && or || to check more than 1 statement like (x<1 && y>0).
You can use this as a quick easy reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
If you have more than three values, it might be more convenient to create a function for use on an array:
function allEqual(arr) {
return arr.every(function (x, i) {
return i === 0 || x === arr[i - 1];
});
}
allEqual([1, 1, 1])
ES6:
function allEqual(...arr) {
return arr.every((x, i) => i === 0 || x === arr[i - 1]);
}
allEqual(1, 1, 1)
As an addition to #vp_arth's answer you could even add a method to the Array prototype
Array.prototype.isHomogeneous = function(){
return Array.prototype.every.call(this, function(c,i,a){ return c === a[0];})
}
So you could do
[1,2,3].isHomogeneous() = false
[1,1,1].isHomogeneous() = true

Categories