Variable reassignment with chained booleans or ternary operator [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
To clarify:
This is purely for experimental purposes, to learn the quirks, odds and ends of a new (to me) language. I would of course write it readable if I ever were to share this code with anyone else. :-)
I have a function someFunction(x), and two global variables:
let m = 2;
let e = 5;
Inside the function, I want to check if x == m. If this is true, I'd like to pass m to a side function call (sideFunction(m)), then reassign x to e to complete someFunction.
This does work as expected:
const someFunction = x => {
if (x == m) {
sideFunction(m);
x = e;
}
doOtherStuffWith(x);
}
However, I'd like to shorten it, preferably to one line. This is also to understand more about ternaries and/or boolean chaining.
I have tried these two methods:
// Boolean chaining
const someFunction = x => {
x == m && sideFunction(m) && (function () {x = e})();
doOtherStuffWith(x);
}
This does not work, presumably because the assignment x = e only applies to the x in the local scope of the inner, anonymous function...?
// Ternary operator
const someFunction = x => {
x = (x == m && sideFunction(m)) ? e : x;
doOtherStuffWith(x);
}
This does not work, presumably because sideFunction(m) doesn't actually get called, for some reason...?
How can I fix these to make them work?
Alternatively, are there other, elegant ways to perform this check/call/reassignment without a full multi-line if block?
Thank you very much!

The problem with
x == m && sideFunction(m) && (function () {x = e})();
is that && evaluates left-to-right, and will stop as soon as the first falsey value is found. Unless sideFunction returns something explicitly truthy, the third IIFE:
(function () {x = e})()
will never run, resulting in x never being reassigned.
x is local in that function. If you can get the function to run, it will reassign x as desired.
You could use the comma operator:
x == m && (sideFunction(m), x = e);
Similarly
x = (x == m && sideFunction(m)) ? e : x;
won't work because sideFunction would have to return something truthy for the left side of the conditional to evaluate truthily - otherwise, x will be assigned to x, no change.
All this said - I'd highly recommend not doing any of these. Your first approach is much more readable, and readability is much more important than line conservation.

You could take a compound expression with a comma operator and do not care about the result value of sideFunction.
const fn = x => (x == m && (sideFunction(m), x = e), doOtherStuffWith(x));

The comma operator , can be used to chain expressions and return the last one e.g.,
var x = (1 + 2, 10 + 2, 100 + 2);
x;
//=> 102
We can use it to evaluate sideFunction(m) and return e: (sideFunction(m), e).
Since you always want to execute doOtherStuffWith you only need to work out whether to give it e or the original x:
const someFunction = x => doOtherStuffWith(x == m ? (sideFunction(m), e) : x);

Related

javascript object related query [duplicate]

Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
Moderator note: Please resist the urge to edit the code or remove this notice. The pattern of whitespace may be part of the question and therefore should not be tampered with unnecessarily. If you are in the "whitespace is insignificant" camp, you should be able to accept the code as is.
Is it ever possible that (a== 1 && a ==2 && a==3) could evaluate to true in JavaScript?
This is an interview question asked by a major tech company. It happened two weeks back, but I'm still trying to find the answer. I know we never write such code in our day-to-day job, but I'm curious.
If you take advantage of how == works, you could simply create an object with a custom toString (or valueOf) function that changes what it returns each time it is used such that it satisfies all three conditions.
const a = {
i: 1,
toString: function () {
return a.i++;
}
}
if(a == 1 && a == 2 && a == 3) {
console.log('Hello World!');
}
The reason this works is due to the use of the loose equality operator. When using loose equality, if one of the operands is of a different type than the other, the engine will attempt to convert one to the other. In the case of an object on the left and a number on the right, it will attempt to convert the object to a number by first calling valueOf if it is callable, and failing that, it will call toString. I used toString in this case simply because it's what came to mind, valueOf would make more sense. If I instead returned a string from toString, the engine would have then attempted to convert the string to a number giving us the same end result, though with a slightly longer path.
I couldn't resist - the other answers are undoubtedly true, but you really can't walk past the following code:
var aᅠ = 1;
var a = 2;
var ᅠa = 3;
if(aᅠ==1 && a== 2 &&ᅠa==3) {
console.log("Why hello there!")
}
Note the weird spacing in the if statement (that I copied from your question). It is the half-width Hangul (that's Korean for those not familiar) which is an Unicode space character that is not interpreted by ECMA script as a space character - this means that it is a valid character for an identifier. Therefore there are three completely different variables, one with the Hangul after the a, one with it before and the last one with just a. Replacing the space with _ for readability, the same code would look like this:
var a_ = 1;
var a = 2;
var _a = 3;
if(a_==1 && a== 2 &&_a==3) {
console.log("Why hello there!")
}
Check out the validation on Mathias' variable name validator. If that weird spacing was actually included in their question, I feel sure that it's a hint for this kind of answer.
Don't do this. Seriously.
Edit: It has come to my attention that (although not allowed to start a variable) the Zero-width joiner and Zero-width non-joiner characters are also permitted in variable names - see Obfuscating JavaScript with zero-width characters - pros and cons?.
This would look like the following:
var a= 1;
var a‍= 2; //one zero-width character
var a‍‍= 3; //two zero-width characters (or you can use the other one)
if(a==1&&a‍==2&&a‍‍==3) {
console.log("Why hello there!")
}
IT IS POSSIBLE!
var i = 0;
with({
get a() {
return ++i;
}
}) {
if (a == 1 && a == 2 && a == 3)
console.log("wohoo");
}
This uses a getter inside of a with statement to let a evaluate to three different values.
... this still does not mean this should be used in real code...
Even worse, this trick will also work with the use of ===.
var i = 0;
with({
get a() {
return ++i;
}
}) {
if (a !== a)
console.log("yep, this is printed.");
}
Example without getters or valueOf:
a = [1,2,3];
a.join = a.shift;
console.log(a == 1 && a == 2 && a == 3);
This works because == invokes toString which calls .join for Arrays.
Another solution, using Symbol.toPrimitive which is an ES6 equivalent of toString/valueOf:
let i = 0;
let a = { [Symbol.toPrimitive]: () => ++i };
console.log(a == 1 && a == 2 && a == 3);
If it is asked if it is possible (not MUST), it can ask "a" to return a random number. It would be true if it generates 1, 2, and 3 sequentially.
with({
get a() {
return Math.floor(Math.random()*4);
}
}){
for(var i=0;i<1000;i++){
if (a == 1 && a == 2 && a == 3){
console.log("after " + (i+1) + " trials, it becomes true finally!!!");
break;
}
}
}
When you can't do anything without regular expressions:
var a = {
r: /\d/g,
valueOf: function(){
return this.r.exec(123)[0]
}
}
if (a == 1 && a == 2 && a == 3) {
console.log("!")
}
It works because of custom valueOf method that is called when Object compared with primitive (such as Number). Main trick is that a.valueOf returns new value every time because it's calling exec on regular expression with g flag, which causing updating lastIndex of that regular expression every time match is found. So first time this.r.lastIndex == 0, it matches 1 and updates lastIndex: this.r.lastIndex == 1, so next time regex will match 2 and so on.
This is possible in case of variable a being accessed by, say 2 web workers through a SharedArrayBuffer as well as some main script. The possibility is low, but it is possible that when the code is compiled to machine code, the web workers update the variable a just in time so the conditions a==1, a==2 and a==3 are satisfied.
This can be an example of race condition in multi-threaded environment provided by web workers and SharedArrayBuffer in JavaScript.
Here is the basic implementation of above:
main.js
// Main Thread
const worker = new Worker('worker.js')
const modifiers = [new Worker('modifier.js'), new Worker('modifier.js')] // Let's use 2 workers
const sab = new SharedArrayBuffer(1)
modifiers.forEach(m => m.postMessage(sab))
worker.postMessage(sab)
worker.js
let array
Object.defineProperty(self, 'a', {
get() {
return array[0]
}
});
addEventListener('message', ({data}) => {
array = new Uint8Array(data)
let count = 0
do {
var res = a == 1 && a == 2 && a == 3
++count
} while(res == false) // just for clarity. !res is fine
console.log(`It happened after ${count} iterations`)
console.log('You should\'ve never seen this')
})
modifier.js
addEventListener('message' , ({data}) => {
setInterval( () => {
new Uint8Array(data)[0] = Math.floor(Math.random()*3) + 1
})
})
On my MacBook Air, it happens after around 10 billion iterations on the first attempt:
Second attempt:
As I said, the chances will be low, but given enough time, it'll hit the condition.
Tip: If it takes too long on your system. Try only a == 1 && a == 2 and change Math.random()*3 to Math.random()*2. Adding more and more to list drops the chance of hitting.
It can be accomplished using the following in the global scope. For nodejs use global instead of window in the code below.
var val = 0;
Object.defineProperty(window, 'a', {
get: function() {
return ++val;
}
});
if (a == 1 && a == 2 && a == 3) {
console.log('yay');
}
This answer abuses the implicit variables provided by the global scope in the execution context by defining a getter to retrieve the variable.
This is also possible using a series of self-overwriting getters:
(This is similar to jontro's solution, but doesn't require a counter variable.)
(() => {
"use strict";
Object.defineProperty(this, "a", {
"get": () => {
Object.defineProperty(this, "a", {
"get": () => {
Object.defineProperty(this, "a", {
"get": () => {
return 3;
}
});
return 2;
},
configurable: true
});
return 1;
},
configurable: true
});
if (a == 1 && a == 2 && a == 3) {
document.body.append("Yes, it’s possible.");
}
})();
Alternatively, you could use a class for it and an instance for the check.
function A() {
var value = 0;
this.valueOf = function () { return ++value; };
}
var a = new A;
if (a == 1 && a == 2 && a == 3) {
console.log('bingo!');
}
EDIT
Using ES6 classes it would look like this
class A {
constructor() {
this.value = 0;
this.valueOf();
}
valueOf() {
return this.value++;
};
}
let a = new A;
if (a == 1 && a == 2 && a == 3) {
console.log('bingo!');
}
I don't see this answer already posted, so I'll throw this one into the mix too. This is similar to Jeff's answer with the half-width Hangul space.
var a = 1;
var a = 2;
var а = 3;
if(a == 1 && a == 2 && а == 3) {
console.log("Why hello there!")
}
You might notice a slight discrepancy with the second one, but the first and third are identical to the naked eye. All 3 are distinct characters:
a - Latin lower case A
a - Full Width Latin lower case A
а - Cyrillic lower case A
The generic term for this is "homoglyphs": different unicode characters that look the same. Typically hard to get three that are utterly indistinguishable, but in some cases you can get lucky. A, Α, А, and Ꭺ would work better (Latin-A, Greek Alpha, Cyrillic-A, and Cherokee-A respectively; unfortunately the Greek and Cherokee lower-case letters are too different from the Latin a: α,ꭺ, and so doesn't help with the above snippet).
There's an entire class of Homoglyph Attacks out there, most commonly in fake domain names (eg. wikipediа.org (Cyrillic) vs wikipedia.org (Latin)), but it can show up in code as well; typically referred to as being underhanded (as mentioned in a comment, [underhanded] questions are now off-topic on PPCG, but used to be a type of challenge where these sorts of things would show up). I used this website to find the homoglyphs used for this answer.
Yes, it is possible! 😎
» JavaScript
if‌=()=>!0;
var a = 9;
if‌(a==1 && a== 2 && a==3)
{
document.write("<h1>Yes, it is possible!😎</h1>")
}
The above code is a short version (thanks to #Forivin for its note in comments) and the following code is original:
var a = 9;
if‌(a==1 && a== 2 && a==3)
{
//console.log("Yes, it is possible!😎")
document.write("<h1>Yes, it is possible!😎</h1>")
}
//--------------------------------------------
function if‌(){return true;}
If you just see top side of my code and run it you say WOW, how?
So I think it is enough to say Yes, it is possible to someone that said to
you: Nothing is impossible
Trick: I used a hidden character after if to make a function that its name is similar to if. In JavaScript we can not override keywords so I forced to use this way. It is a fake if, but it works for you in this case!
» C#
Also I wrote a C# version (with increase property value technic):
static int _a;
public static int a => ++_a;
public static void Main()
{
if(a==1 && a==2 && a==3)
{
Console.WriteLine("Yes, it is possible!😎");
}
}
Live Demo
JavaScript
a == a +1
In JavaScript, there are no integers but only Numbers, which are implemented as double precision floating point numbers.
It means that if a Number a is large enough, it can be considered equal to four consecutive integers:
a = 100000000000000000
if (a == a+1 && a == a+2 && a == a+3){
console.log("Precision loss!");
}
True, it's not exactly what the interviewer asked (it doesn't work with a=0), but it doesn't involve any trick with hidden functions or operator overloading.
Other languages
For reference, there are a==1 && a==2 && a==3 solutions in Ruby and Python. With a slight modification, it's also possible in Java.
Ruby
With a custom ==:
class A
def ==(o)
true
end
end
a = A.new
if a == 1 && a == 2 && a == 3
puts "Don't do this!"
end
Or an increasing a:
def a
#a ||= 0
#a += 1
end
if a == 1 && a == 2 && a == 3
puts "Don't do this!"
end
Python
You can either define == for a new class:
class A:
def __eq__(self, who_cares):
return True
a = A()
if a == 1 and a == 2 and a == 3:
print("Don't do that!")
or, if you're feeling adventurous, redefine the values of integers:
import ctypes
def deref(addr, typ):
return ctypes.cast(addr, ctypes.POINTER(typ))
deref(id(2), ctypes.c_int)[6] = 1
deref(id(3), ctypes.c_int)[6] = 1
deref(id(4), ctypes.c_int)[6] = 1
print(1 == 2 == 3 == 4)
# True
It might segfault, depending on your system/interpreter.
The python console crashes with the above code, because 2 or 3 are probably used in the background. It works fine if you use less-common integers:
>>> import ctypes
>>>
>>> def deref(addr, typ):
... return ctypes.cast(addr, ctypes.POINTER(typ))
...
>>> deref(id(12), ctypes.c_int)[6] = 11
>>> deref(id(13), ctypes.c_int)[6] = 11
>>> deref(id(14), ctypes.c_int)[6] = 11
>>>
>>> print(11 == 12 == 13 == 14)
True
Java
It's possible to modify Java Integer cache:
package stackoverflow;
import java.lang.reflect.Field;
public class IntegerMess
{
public static void main(String[] args) throws Exception {
Field valueField = Integer.class.getDeclaredField("value");
valueField.setAccessible(true);
valueField.setInt(1, valueField.getInt(42));
valueField.setInt(2, valueField.getInt(42));
valueField.setInt(3, valueField.getInt(42));
valueField.setAccessible(false);
Integer a = 42;
if (a.equals(1) && a.equals(2) && a.equals(3)) {
System.out.println("Bad idea.");
}
}
}
This is an inverted version of #Jeff's answer* where a hidden character (U+115F, U+1160 or U+3164) is used to create variables that look like 1, 2 and 3.
var a = 1;
var ᅠ1 = a;
var ᅠ2 = a;
var ᅠ3 = a;
console.log( a ==ᅠ1 && a ==ᅠ2 && a ==ᅠ3 );
* That answer can be simplified by using zero width non-joiner (U+200C) and zero width joiner (U+200D). Both of these characters are allowed inside identifiers but not at the beginning:
var a = 1;
var a‌ = 2;
var a‍ = 3;
console.log(a == 1 && a‌ == 2 && a‍ == 3);
/****
var a = 1;
var a\u200c = 2;
var a\u200d = 3;
console.log(a == 1 && a\u200c == 2 && a\u200d == 3);
****/
Other tricks are possible using the same idea e.g. by using Unicode variation selectors to create variables that look exactly alike (a︀ = 1; a︁ = 2; a︀ == 1 && a︁ == 2; // true).
Rule number one of interviews; never say impossible.
No need for hidden character trickery.
window.__defineGetter__( 'a', function(){
if( typeof i !== 'number' ){
// define i in the global namespace so that it's not lost after this function runs
i = 0;
}
return ++i;
});
if( a == 1 && a == 2 && a == 3 ){
console.log( 'Oh dear, what have we done?' );
}
Honestly though, whether there is a way for it to evaluate to true or not (and as others have shown, there are multiple ways), the answer I'd be looking for, speaking as someone who has conducted hundreds of interviews, would be something along the lines of:
"Well, maybe yes under some weird set of circumstances that aren't immediately obvious to me... but if I encountered this in real code then I would use common debugging techniques to figure out how and why it was doing what it was doing and then immediately refactor the code to avoid that situation... but more importantly: I would absolutely NEVER write that code in the first place because that is the very definition of convoluted code, and I strive to never write convoluted code".
I guess some interviewers would take offense to having what is obviously meant to be a very tricky question called out, but I don't mind developers who have an opinion, especially when they can back it up with reasoned thought and can dovetail my question into a meaningful statement about themselves.
If you ever get such an interview question (or notice some equally unexpected behavior in your code) think about what kind of things could possibly cause a behavior that looks impossible at first glance:
Encoding: In this case the variable you are looking at is not the one you think it is. This can happen if you intentionally mess around with Unicode using homoglyphs or space characters to make the name of a variable look like another one, but encoding issues can also be introduced accidentally, e.g. when copying & pasting code from the Web that contains unexpected Unicode code points (e.g. because a content management system did some "auto-formatting" such as replacing fl with Unicode 'LATIN SMALL LIGATURE FL' (U+FB02)).
Race conditions: A race-condition might occur, i.e. a situation where code is not executing in the sequence expected by the developer. Race conditions often happen in multi-threaded code, but multiple threads are not a requirement for race conditions to be possible – asynchronicity is sufficient (and don't get confused, async does not mean multiple threads are used under the hood).
Note that therefore JavaScript is also not free from race conditions just because it is single-threaded. See here for a simple single-threaded – but async – example. In the context of an single statement the race condition however would be rather hard to hit in JavaScript.
JavaScript with web workers is a bit different, as you can have multiple threads. #mehulmpt has shown us a great proof-of-concept using web workers.
Side-effects: A side-effect of the equality comparison operation (which doesn't have to be as obvious as in the examples here, often side-effects are very subtle).
These kind of issues can appear in many programming languages, not only JavaScript, so we aren't seeing one of the classical JavaScript WTFs here1.
Of course, the interview question and the samples here all look very contrived. But they are a good reminder that:
Side-effects can get really nasty and that a well-designed program should be free from unwanted side-effects.
Multi-threading and mutable state can be problematic.
Not doing character encoding and string processing right can lead to nasty bugs.
1 For example, you can find an example in a totally different programming language (C#) exhibiting a side-effect (an obvious one) here.
Here's another variation, using an array to pop off whatever values you want.
const a = {
n: [3,2,1],
toString: function () {
return a.n.pop();
}
}
if(a == 1 && a == 2 && a == 3) {
console.log('Yes');
}
Okay, another hack with generators:
const value = function* () {
let i = 0;
while(true) yield ++i;
}();
Object.defineProperty(this, 'a', {
get() {
return value.next().value;
}
});
if (a === 1 && a === 2 && a === 3) {
console.log('yo!');
}
Using Proxies:
var a = new Proxy({ i: 0 }, {
get: (target, name) => name === Symbol.toPrimitive ? () => ++target.i : target[name],
});
console.log(a == 1 && a == 2 && a == 3);
Proxies basically pretend to be a target object (the first parameter), but intercept operations on the target object (in this case the "get property" operation) so that there is an opportunity to do something other than the default object behavior. In this case the "get property" action is called on a when == coerces its type in order to compare it to each number. This happens:
We create a target object, { i: 0 }, where the i property is our counter
We create a Proxy for the target object and assign it to a
For each a == comparison, a's type is coerced to a primitive value
This type coercion results in calling a[Symbol.toPrimitive]() internally
The Proxy intercepts getting the a[Symbol.toPrimitive] function using the "get handler"
The Proxy's "get handler" checks that the property being gotten is Symbol.toPrimitive, in which case it increments and then returns the counter from the target object: ++target.i. If a different property is being retrieved, we just fall back to returning the default property value, target[name]
So:
var a = ...; // a.valueOf == target.i == 0
a == 1 && // a == ++target.i == 1
a == 2 && // a == ++target.i == 2
a == 3 // a == ++target.i == 3
As with most of the other answers, this only works with a loose equality check (==), because strict equality checks (===) do not do type coercion that the Proxy can intercept.
Actually the answer to the first part of the question is "Yes" in every programming language. For example, this is in the case of C/C++:
#define a (b++)
int b = 1;
if (a ==1 && a== 2 && a==3) {
std::cout << "Yes, it's possible!" << std::endl;
} else {
std::cout << "it's impossible!" << std::endl;
}
Same, but different, but still same (can be "tested" multiple times):
const a = { valueOf: () => this.n = (this.n || 0) % 3 + 1}
if(a == 1 && a == 2 && a == 3) {
console.log('Hello World!');
}
if(a == 1 && a == 2 && a == 3) {
console.log('Hello World!');
}
My idea started from how Number object type equation works.
An ECMAScript 6 answer that makes use of Symbols:
const a = {value: 1};
a[Symbol.toPrimitive] = function() { return this.value++ };
console.log((a == 1 && a == 2 && a == 3));
Due to == usage, JavaScript is supposed to coerce a into something close to the second operand (1, 2, 3 in this case). But before JavaScript tries to figure coercing on its own, it tries to call Symbol.toPrimitive. If you provide Symbol.toPrimitive JavaScript would use the value your function returns. If not, JavaScript would call valueOf.
I think this is the minimal code to implement it:
i=0,a={valueOf:()=>++i}
if (a == 1 && a == 2 && a == 3) {
console.log('Mind === Blown');
}
Creating a dummy object with a custom valueOf that increments a global variable i on each call. 23 characters!
This one uses the defineProperty with a nice side-effect causing global variable!
var _a = 1
Object.defineProperty(this, "a", {
"get": () => {
return _a++;
},
configurable: true
});
console.log(a)
console.log(a)
console.log(a)
By overriding valueOf in a class declaration, it can be done:
class Thing {
constructor() {
this.value = 1;
}
valueOf() {
return this.value++;
}
}
const a = new Thing();
if(a == 1 && a == 2 && a == 3) {
console.log(a);
}
What happens is that valueOf is called in each comparison operator. On the first one, a will equal 1, on the second, a will equal 2, and so on and so forth, because each time valueOf is called, the value of a is incremented.
Therefore the console.log will fire and output (in my terminal anyways) Thing: { value: 4}, indicating the conditional was true.
As we already know that the secret of loose equality operator (==) will try to convert both values to a common type. As a result, some functions will be invoked.
ToPrimitive(A) attempts to convert its object argument to a primitive
value, by invoking varying sequences of A.toString and A.valueOf
methods on A.
So as other answers using Symbol.toPrimitive, .toString, .valueOf from integer. I would suggest the solution using an array with Array.pop like this.
let a = { array: [3, 2, 1], toString: () => a.array.pop() };
if(a == 1 && a == 2 && a == 3) {
console.log('Hello World!');
}
In this way, we can work with text like this
let a = { array: ["World", "Hello"], toString: () => a.array.pop() };
if(a == "Hello" && a == "World") {
console.log('Hello World!');
}
Surprisingly, yes. The == loose equality operator in JS calls the valueOf() method of the object that's being compared. Therefore, you can create a class that returns an internal value, then increments that interval value every time it's called. Like this:
class AClass {
constructor(initalVal) {
this.val = initalVal;
}
valueOf() {
return this.val++;
}
}
const a = new AClass(1);
console.log(a==1 && a==2 && a==3)
I know that there are a lot of other answers to this question, but this is how you'd do it with ES6 syntax.
Note: If you don't want this to happen, then you should use the === operator to check for strict instead. Like this:
class AClass {
constructor(initalVal) {
this.val = initalVal;
}
valueOf() {
return this.val++;
}
}
const a = new AClass(1);
console.log(a===1 && a===2 && a===3)
Yes, you can Do that, see the following JavaScript code:
let a = 0 // Create a variable and give it a value
if( a !== 1 && a !== 2 && a !== 3 )
{
console.log("true")
}
Explanation of the solution:
Simply , we add the not equal sign
before the == sign so that we tell the language that these values are
not equal to the value in the variable

shorthand for conditions like (x === y) || (x === z)? [duplicate]

This question already has answers here:
Check variable equality against a list of values
(16 answers)
JavaScript: Simple way to check if variable is equal to one of two or more values? [duplicate]
(8 answers)
Closed 2 years ago.
I want to make my condition easier to read and wandering if it is possible to simplify this Scenario:
if((x === y)||(x === z)){...}
//and this one:
x = (x === y) || (x === z)? ... : ...;
//To something like:
if(x === (y || z)){...}
x = x === (y || z) ? ... : ...;
This would get rid of the tons of brackets and variable duplication as well as "sounding" logical (at least for me):
if this var x is this or that then I do this.
Especially when x is some long object reference e.g.:
this.someObject.KeyOfKeys[200].language === this.someOtherObject.KeyY.languages[10] || ...;
Or how do you deal with logical "easy" but cumbersome to write conditions?
You can use includes() like so:
if ([y, z].includes(x)) { ... }
x = [y, z].includes(x) ? ... : ...;
As noted in the comments, this will not work with IE11 and older browsers.

Overwrite variable or check for existance

I am making a simple script in Javascript, calculating some stuff like minimum, maximum etc. and I was wondering which of the following would be faster, and mostly, why:
var x, y, z;
function test(){
if (x === undefined)
x = Math.min(a, b);
if (y === undefined)
y = a / b;
if (z === undefined)
z = a - b;
return [x, y, z];
}
test(); test(); test();
or
function test() {
return [Math.min(a, b), a / b, a - b]
}
Also, should I create variables the first way (Defining them only when requested) or should I define the variables as soon as possible, e.g. at the start of my function? I am creating a RGB to HSV script, using constant RGB values. The HSV is not nececairly always requested (User desides).
Always define your javascript variables at the top, and use them later like:
'use strict';
var a, b, c;
a = 1;
if (typeof b === 'undefined') {
b = a || c;
}
// b is now 1
It is worth mentioning that if you don't define a variable, it becomes a global when first used (which is very bad).
Defining a variable in a condition (e.g. if) is also a very bad practice.
If you do not want to change the x,y,z values if they already exist then checking for their existance and then over writing would be a better option.
if (x === undefined)
x = Math.min(a, b);
if (y === undefined)
y = a / b;
if (z === undefined)
z = a - b;
Since you are working with RGB ,this is the best practice.
Defining the variable at the start is always considered helpful and it hardly has any impact on the performance.
if the variable is not defined use typeof . The Condition should be like
if(typeof x === 'undefined'){
//do something
}
It is totally depending on context whether you want to overwrite existing value or not. Irrespective of the existence of variable if you want to perform operation then below ways is best.
x = Math.min(a, b);
y = a / b;
z = a - b;
This way it faster because in first way you are just check variable is undefined or not if undefined then perform task. Its best to directly perform task.
hope this helps you.

How do I write an arrow function in ES6 recursively?

Arrow functions in ES6 do not have an arguments property and therefore arguments.callee will not work and would anyway not work in strict mode even if just an anonymous function was being used.
Arrow functions cannot be named, so the named functional expression trick can not be used.
So... How does one write a recursive arrow function? That is an arrow function that recursively calls itself based on certain conditions and so on of-course?
Writing a recursive function without naming it is a problem that is as old as computer science itself (even older, actually, since λ-calculus predates computer science), since in λ-calculus all functions are anonymous, and yet you still need recursion.
The solution is to use a fixpoint combinator, usually the Y combinator. This looks something like this:
(y =>
y(
givenFact =>
n =>
n < 2 ? 1 : n * givenFact(n-1)
)(5)
)(le =>
(f =>
f(f)
)(f =>
le(x => (f(f))(x))
)
);
This will compute the factorial of 5 recursively.
Note: the code is heavily based on this: The Y Combinator explained with JavaScript. All credit should go to the original author. I mostly just "harmonized" (is that what you call refactoring old code with new features from ES/Harmony?) it.
It looks like you can assign arrow functions to a variable and use it to call the function recursively.
var complex = (a, b) => {
if (a > b) {
return a;
} else {
complex(a, b);
}
};
Claus Reinke has given an answer to your question in a discussion on the esdiscuss.org website.
In ES6 you have to define what he calls a recursion combinator.
let rec = (f)=> (..args)=> f( (..args)=>rec(f)(..args), ..args )
If you want to call a recursive arrow function, you have to call the recursion combinator with the arrow function as parameter, the first parameter of the arrow function is a recursive function and the rest are the parameters. The name of the recursive function has no importance as it would not be used outside the recursive combinator. You can then call the anonymous arrow function. Here we compute the factorial of 6.
rec( (f,n) => (n>1 ? n*f(n-1) : n) )(6)
If you want to test it in Firefox you need to use the ES5 translation of the recursion combinator:
function rec(f){
return function(){
return f.apply(this,[
function(){
return rec(f).apply(this,arguments);
}
].concat(Array.prototype.slice.call(arguments))
);
}
}
TL;DR:
const rec = f => f((...xs) => rec(f)(...xs));
There are many answers here with variations on a proper Y -- but that's a bit redundant... The thing is that the usual way Y is explained is "what if there is no recursion", so Y itself cannot refer to itself. But since the goal here is a practical combinator, there's no reason to do that. There's this answer that defines rec using itself, but it's complicated and kind of ugly since it adds an argument instead of currying.
The simple recursively-defined Y is
const rec = f => f(rec(f));
but since JS isn't lazy, the above adds the necessary wrapping.
Use a variable to which you assign the function, e.g.
const fac = (n) => n>0 ? n*fac(n-1) : 1;
If you really need it anonymous, use the Y combinator, like this:
const Y = (f) => ((x)=>f((v)=>x(x)(v)))((x)=>f((v)=>x(x)(v)))
… Y((fac)=>(n)=> n>0 ? n*fac(n-1) : 1) …
(ugly, isn't it?)
A general purpose combinator for recursive function definitions of any number of arguments (without using the variable inside itself) would be:
const rec = (le => ((f => f(f))(f => (le((...x) => f(f)(...x))))));
This could be used for example to define factorial:
const factorial = rec( fact => (n => n < 2 ? 1 : n * fact(n - 1)) );
//factorial(5): 120
or string reverse:
const reverse = rec(
rev => (
(w, start) => typeof(start) === "string"
? (!w ? start : rev(w.substring(1), w[0] + start))
: rev(w, '')
)
);
//reverse("olleh"): "hello"
or in-order tree traversal:
const inorder = rec(go => ((node, visit) => !!(node && [go(node.left, visit), visit(node), go(node.right, visit)])));
//inorder({left:{value:3},value:4,right:{value:5}}, function(n) {console.log(n.value)})
// calls console.log(3)
// calls console.log(4)
// calls console.log(5)
// returns true
I found the provided solutions really complicated, and honestly couldn't understand any of them, so i thought out a simpler solution myself (I'm sure it's already known, but here goes my thinking process):
So you're making a factorial function
x => x < 2 ? x : x * (???)
the (???) is where the function is supposed to call itself, but since you can't name it, the obvious solution is to pass it as an argument to itself
f => x => x < 2 ? x : x * f(x-1)
This won't work though. because when we call f(x-1) we're calling this function itself, and we just defined it's arguments as 1) f: the function itself, again and 2) x the value. Well we do have the function itself, f remember? so just pass it first:
f => x => x < 2 ? x : x * f(f)(x-1)
^ the new bit
And that's it. We just made a function that takes itself as the first argument, producing the Factorial function! Just literally pass it to itself:
(f => x => x < 2 ? x : x * f(f)(x-1))(f => x => x < 2 ? x : x * f(f)(x-1))(5)
>120
Instead of writing it twice, you can make another function that passes it's argument to itself:
y => y(y)
and pass your factorial making function to it:
(y => y(y))(f => x => x < 2 ? x : x * f(f)(x-1))(5)
>120
Boom. Here's a little formula:
(y => y(y))(f => x => endCondition(x) ? default(x) : operation(x)(f(f)(nextStep(x))))
For a basic function that adds numbers from 0 to x, endCondition is when you need to stop recurring, so x => x == 0. default is the last value you give once endCondition is met, so x => x. operation is simply the operation you're doing on every recursion, like multiplying in Factorial or adding in Fibonacci: x1 => x2 => x1 + x2. and lastly nextStep is the next value to pass to the function, which is usually the current value minus one: x => x - 1. Apply:
(y => y(y))(f => x => x == 0 ? x : x + f(f)(x - 1))(5)
>15
var rec = () => {rec()};
rec();
Would that be an option?
Since arguments.callee is a bad option due to deprecation/doesnt work in strict mode, and doing something like var func = () => {} is also bad, this a hack like described in this answer is probably your only option:
javascript: recursive anonymous function?
This is a version of this answer, https://stackoverflow.com/a/3903334/689223, with arrow functions.
You can use the U or the Y combinator. Y combinator being the simplest to use.
U combinator, with this you have to keep passing the function:
const U = f => f(f)
U(selfFn => arg => selfFn(selfFn)('to infinity and beyond'))
Y combinator, with this you don't have to keep passing the function:
const Y = gen => U(f => gen((...args) => f(f)(...args)))
Y(selfFn => arg => selfFn('to infinity and beyond'))
You can assign your function to a variable inside an iife
var countdown = f=>(f=a=>{
console.log(a)
if(a>0) f(--a)
})()
countdown(3)
//3
//2
//1
//0
i think the simplest solution is looking at the only thing that you don't have, which is a reference to the function itself. because if you have that then recusion is trivial.
amazingly that is possible through a higher order function.
let generateTheNeededValue = (f, ...args) => f(f, ...args);
this function as the name sugests, it will generate the reference that we'll need. now we only need to apply this to our function
(generateTheNeededValue)(ourFunction, ourFunctionArgs)
but the problem with using this thing is that our function definition needs to expect a very special first argument
let ourFunction = (me, ...ourArgs) => {...}
i like to call this special value as 'me'. and now everytime we need recursion we do like this
me(me, ...argsOnRecursion);
with all of that. we can now create a simple factorial function.
((f, ...args) => f(f, ...args))((me, x) => {
if(x < 2) {
return 1;
} else {
return x * me(me, x - 1);
}
}, 4)
-> 24
i also like to look at the one liner of this
((f, ...args) => f(f, ...args))((me, x) => (x < 2) ? 1 : (x * me(me, x - 1)), 4)
Here is the example of recursive function js es6.
let filterGroups = [
{name: 'Filter Group 1'}
];
const generateGroupName = (nextNumber) => {
let gN = `Filter Group ${nextNumber}`;
let exists = filterGroups.find((g) => g.name === gN);
return exists === undefined ? gN : generateGroupName(++nextNumber); // Important
};
let fg = generateGroupName(filterGroups.length);
filterGroups.push({name: fg});

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.

Categories

Resources