How to negate and atribute a function to a variable in javascript? - javascript

I'm going to make a validation of a string, using javascript isNaN build in function. But depending of other variable, I want to negate de value of the isNaN, so I can check if its a Number or Not a Number
e.g.:
I'm trying to do something like this, but in javascript, it's not valid
function validation(objectWithStrings, type){
let stringCheck = type == 1 ? isNaN : !isNaN
...
}
I want to make this so I don't need to make a lot of if / else statements in the middle of my code, I can't just call stringCheck(someString) and get if it's true or false.
Is there a way to get the function in a variable but when you call it, it return the result of the function negated?
Observation: I don't want a better way to check if a string is a number or not, I want to get a way of returning the negated value of any function.

The expression isNaN is valid javascript function but !isNaN is not. You need to pass a valid javascript function that returns the opposite of isNaN:
function validation(objectWithStrings, type){
const stringCheck = type == 1 ? isNaN : (str) => !isNaN(str)
...
}

Taking into account the observation, you can create a negate function that accepts a callback and negates the result of callback execution:
const isNumber = value => !isNaN(+value);
const negate = fn => (...args) => !fn(...args);
const isNotNumber = negate(isNumber);
console.log(isNumber('10'));
console.log(isNotNumber('10'));

Related

Can I use the logical OR operator with Strings in function arguments in JS? Function does not evaluate the second string (I think)

I check the backend through Vuex to conditionally render error messages. I have the following function:
const getByTitle = (memberTitle) => {
return state.errors.find(e => e.meta.memberTitle === memberTitle)
?.content.error.title;
}
Now, as an argument I would like to pass 2 strings, as there are 2 options in this component.
getNumber() {
return this.getErrorByMemberId('B2Bvr' || 'Cvr' || undefined);
},
If the correct value in the backend is Cvr, then in this case I unfortunately don't get the error message (because it comes after B2Bvr). If I change the order of the arguments (see following snippet) abd put the correct value first (Cvr), then it works and correctly displays the error message.
getNumber() {
return this.getErrorByMemberId('Cvr' || 'B2Bvr' || undefined);
},
Why does it stop in the first argument? And does not evaluate the second one? Which is the correct way to use Logical OR operators in parameters?
It stops at the first argument because that's the first argument that is truthy, so the other arguments are ignored. If you attempted to call the function with undefined first (falsy value), it would skip that one and send the second argument.
One way to accomplish your intended goal would be to send all possible arguments as an array of arguments and use Array.includes() in your function:
getNumber() {
return this.getErrorByMemberId(['Cvr', 'B2Bvr', undefined]);
},
const getByTitle = (memberTitleArray) => {
return state.errors.find(e => memberTitleArray.includes(e.meta.memberTitle))
?.content.error.title;
}

Can I pass a comparison as a function parameters?

My main question is, what type of data function parameters is accepting?
I would pass a comparison as parameters as for exemple
Function test(a) //where A is a comparison so for example
test("a" == "a")
I'm trying to get the comparison expression and not the result.
Is it something possible? Any way to do it? Thanks
Yes, you can pass functions as parameters, and it's quite a common pattern in both JS and other languages to pass "predicate" functions.
let isGreaterThan5 = v => v > 5;
let out = [1,3,5,7,9].filter(isGreaterThan5);
console.log(out);
Yes it is possible:
function isPosible(param) { // Here you define a function
return param;
}
// Below you are executing the function and printing the result
console.log(isPosible("a === a")); // Returns the whole expression
More important is to understand that you can pass any expression as argument to a function, including but not limited to: Any primitive type (string, number, boolean, undefined, null, etc..), functions (callbacks), expressions that evaluates something like your case.

Using ternary operators in a function with javascript

I am new to Javascript and sort of working through the weeds on these ternary operators. I have this small code segment:
const x = MSys.inShip ? 'ship launch' : '';
if (x != '') {send_command(x);}
While this works efficiently enough I am curious as to if it can be rewritten inside of the function call. Something like the following:
send_command(const x = MSys.inShip
? 'ship launch'
: MSys.alert("You aren't in your ship!);
This may not make sense with the current example but it's the best idea I had at the time. Basically, I like the shorthand of the ternary style for easy if/then conditionals but I don't like how it's tied to a variable which must then be called. I'm looking for a way to use that shorthand without having to tie to a variable.
Finally, the purpose of this is to see if you are in the ship and if you are, launch. If you aren't don't do anything at all or just send an alert message.
I am curious as to if it can be rewritten inside of the function call.
Yes, it can. But, if you do it there, then there is no need for a variable. You would be passing the function's argument directly inline.
Having said that, you can't pass that MSys.alert() statement as the "else" value because it will be executed in all cases. You'd have to pass a value there that the function can use as its input argument
send_command(MSys.inShip ? 'ship launch' : 'some other string');
Here's an example:
function foo(x){
console.log(x);
}
// If a random number is even, pass "even". If not, pass "odd"
foo(Math.floor(Math.random() * 10) % 2 === 0 ? "even" : "odd");
An important distinction between your two approaches - The second approach will ALWAYS call send_command() whereas your first approach will conditionally call it.
This distinction will matter depending on your implementation of send_command, but it sounds like you want the behavior of the first approach.
Additionally, You can't declare variables using const in a function call. If you just pass in the ternary operator, you will end up calling send_command with either your string, or undefined (the return of calling alert() ).
However, as an answer to your question, yes you can pass the ternary operator to a function like any other value. The ternary operator is an expression that will return a value.
Technically, you could keep a variable (such as operation) below, which references which method you want to execute, depending upon some conditional. And then you could pass that variable method the variable string it should get.
So, as you can see, it can be done. But look at how much complication was added to the process, rather than just using a simple if else statement.
function test_logic ( inShip ) {
// if they are in their ship, the operation should be the send_command method
// otherwise it should be the window alert
var operation = inShip ? send_command : window.alert;
function send_command ( command ) {
console.log( command );
}
// give the operation the desired string
operation( inShip ? 'ship launch' : "You aren't in your ship!" );
}
console.log( "Not in ship test" );
test_logic( false );
console.log( "In ship test" );
test_logic( true );

Var's boolean value in JavaScript

I am not so expert in JavaScript and I am wonder if there is a way to test the boolean value of a variable in javascript.
In Python I can do this:
>>>list_var = []
>>>bool(list_var)
False # This is the boolean value of a empty list
>>>
And if I try get an element in JS that does not exist, i.e:
document.getElementById('b-advanced')
[] // This is what returns
Is there a way to test the expression above as boolean without using an if... statement?
EDIT
I think I need to point something.
This is the full expression I use:
angular.element(document.getElementById('b-advanced'))
There is not. The best you can do is list_var.length === 0. For a full test, you'd want to test as follows
// Return true if arg is an array or string containing at least one item
function isTrueness(arg) {
return !!(arg && arg.length > 0);
}
angular.element(isTrueness(document.getElementById('b-advanced')));
You can use !! in front which will return its boolean status.
!![] // true
!!null // false
var x = Boolean(document.getElementById('b-advanced'));
Boolean is a wrapper for boolean values.
you can test to see what type a variable is by using typeof so for example:
var myVar = true;
if (typeof myVar === "boolean") console.log("It is a boolean");
In Python, an empty list is false. In Javascript, an empty array is true. You can mimic this by saying myArray.length && myArray. If myArray is empty, then its length is zero and the expression is false. If myArray isn’t empty, then Javascript returns the second operand, just like Python.

JavaScript: functions passed as a parameter to an if block

In the below code how does passing bar as
function (n) { return n; }
to foo evaluate to true in the if block?
function foo(bar) {
if (bar) {
// true
} else {
// false
}
}
This has me puzzled so any help is much appreciated.
If bar is bound to an anonymous function, then it is an object. Objects are 'truthy' in JavaScript.
The only values in JavaScript that are 'falsy' are:
false
null
undefined
'' (empty string)
0 (zero as a number)
NaN
Everything else is 'truthy', including function objects.
If you meant to call the anonymous function, you'd do if (bar(5)) which would call your anonymous function with the argument 5. Then your anonymous function would return n (which is 5 in this case). As 5 is not a falsy object, this would go to the true branch as well. Doing if (bar(0)) would got to the else branch, because 0 is falsy.
Anything not null, 0, false, empty string or undefined is going to evaluate to true in an if(something) statement, this is just how weak-typing in JavaScript works.
If you want more specificity you may want to look at the typeof operator to check for the type you're expecting, or use a another stronger check like this:
if(bar === true) {
Using === checks for both value and type equivalence.
You could use typeof() if you want to know what type it returns
It always return true, because bar is not null. if an expression within an if statement is not a logic expression (e.g. if(x <7)) then performs a check for null. If it is null it returns false, otherwise true.
In your example you have defined bar as the function {returns n;} so that is why your if statement is evaluating to true.
If bar returns a bool (true or false) then you need to call the function and get the result, rather than passing a reference to the function - this is done using parentheses:
var exampleA = bar(false); // executes function bar and returns the result (false) in exampleA
var exampleB = bar; // stores a reference to the function bar in variable exampleB

Categories

Resources