I'm beginner on JavaScript and AngularJS. So I encounter following code from Adam Freeman books
var selectedCategory = null;
...
$scope.categoryFilterFn = function(product) {
return selectedCategory == null ||
product.category === selectedCategory;
};
I get confused by the return statement above, can you guys re-write the code above with clear code (no shorthand).
Thanks.
This is a short-hand form of returning a boolean value. Look closely:
return selectedCategory == null || product.category === selectedCategory;
Here, return statement has two expressions:
selectedCategory == null
product.category === selectedCategory
When the method returns, it will evaluate these two expressions separately. Consider yout selectedCategory is null, and the product.category is equal to selectedCategory then the statement is
return true || true;
which will eventually simplifies to
return true; // (true || true) = true
Likewise, you can think of this expressions return value by substituting values and evaluate them separately.
Longer version for this is:
if (selectedCategory == null || product.category == selectedCategory) {
return true;
} else {
return false;
}
The return statement could be re-written easily as an if() block as follows:
$scope.categoryFilterFn = function(product) {
if( selectedCategory == null || product.category === selectedCategory )
{
return true;
}
return false;
};
Essentially, the return is going to return true if either of the specified conditions is true. Otherwise, it will return false.
Related
I have a function that takes a variable called (compactArray) (there is another function to produce and return a compact array that works fine)
I know it's because my function is not returning any value, but I am struggling to solve the return = undefined.
the code is below
let a = null;
let b = null;
let operand = null;
let total = null;
function testGrab (compactArray) {
if(compactArray == typeof(Number) && a == null) {
return a = compactArray;
} else if (compactArray == typeof(Number) && a !== null){
return b = compactArray;
} else if (compactArray == typeof(String)){
return operand = compactArray;
}
return total
};
const compactArray = 467;
console.log(testGrab(compactArray));
console.log(a)
I want this function to take the compactArray returned from a different function and assign it to the correct variable a,b,operand.
is this possible, or would I need to make a function to return the relevant if statement, and then create another function to assign the returned value to the correct variable?
I know it's because my function is not returning anything but I am stumped at the moment.
if you want to check whether compactArray's type is a number:
change this statement "if(compactArray == typeof(Number) && a == null)"
to this statement "if("number" == typeof(compactArray) && a == null)"
function test(val) {
const hasError = val ?? true;
if (hasError) {
//error handling...
} else {
//do something...
}
}
test(null) //error handling...
test(undefined) //error handling...
test('text') //error handling...
test(true) //error handling...
like this case i want to filter 'null' and 'undefined'
but it`s work every truthy value.
So i have only one option...
const hasError = (val === undefined || val === null);
Is there any way of use nullish operator in this case?
and when nullish operator is used generally?
thank you
If you're sure that
const hasError = (val === undefined || val === null);
captures the logic you want, then the problem is that
const hasError = val ?? true;
gives you the opposite of that if you're subsequently going to use that flag in an if expression. You'd really want to follow with
if (hasError !== true)
which is really confusing (to me). Instead, you can think of the ?? operator giving you the opposite:
const noError = val ?? true;
if (!noError)
which makes a little more sense. Personally I'd use
const hasError = val == null;
or just perform the test in the if directly.
I have the following the condition:
useEffect(() => {
const hasFalsyValue = (
dropdownValue === undefined
|| dropdownValue === null
);
if (hasFalsyValue && !onChangeText) {
return;
}
onChangeText(dropdownValue);
}, [
dropdownValue,
onChangeText,
inputProps,
]);
If hasFalsyValue is true, then, the effect will return right away. But TS is yelling on me saying the dropdownValue can still be undefined
If I extract the conditions from the constant and put it inside the conditional parenthesis, it will work
If hasFalsyValue is true, then, the effect will return right away.
No - only when hasFalsyValue is true and onChangeText is falsy. You might have meant
const hasFalsyValue = (dropdownValue === undefined || dropdownValue === null);
if (hasFalsyValue || !onChangeText) {
return;
}
onChangeText(dropdownValue);
or
const hasFalsyValue = (dropdownValue === undefined || dropdownValue === null);
if (!hasFalsyValue && onChangeText) {
onChangeText(dropdownValue);
}
Btw I'd recommend to shorten this to
if (dropdownValue != null) {
onChangeText?(dropdownValue);
}
That's almost OK. you misused && and TypeScript is not so smart to pick up variable, so this should work:
#1 Define guard
function isDefined<T>(v: T|undefined): v is T {
return v!= null
}
#2 use it
if (!isDefined(dropdownValue) || !onChangeText) {
return;
}
onChangeText(dropdownValue);
Is there a way to write the JavaScript code below as a one-liner?
this.isContactPage = (window.location.pathname === '/contact');
if (!this.isContactPage) return false;
The method continues on if this.isContactPage is true.
The property this.isContactPage is needed in other places in the script.
return !(this.isContactPage = (window.location.pathname === '/contact'));
Another example:
console.log(window.prop); // undefined
console.log(!(window.prop = true) || undefined); // undefined
console.log(!(window.prop = true)); // false
console.log(window.prop); // true
It'll be fairly dense and "obscured" code, but you can inline assignments in conditionals:
if ( !this.isContactPage = ( window.location.pathname == '/contact' ) ) return false;
This will only return the function if this.isContactPage is assigned the value false otherwise the function is not returned and continues on execution, as opposed to:
return ( this.isContactPage = ( window.location.pathname == '/contact' ) );
Which will return true or false immediately.
return !this.isContactPage = (window.location.pathname === '/contact')
I have something makes your code as short as possible!
return !(this.isContactPage=location.pathname=='/contact')
You don't need "Window"
You don't need returning false or true directly through your code
You don't need ===, then change it to ==
The shortest way guys suggested has 88 letters and this suggestion has just 68 letter and is more readable and understandable!
with this you will not have errors!
this.isContactPage = /contact/gi.test(window.location.pathname);
if (!this.isContactPage) return false;
or
return !(/contact/gi.test(window.location.pathname))
If I had multiple points in which I needed to use the same if statement, could I use a javascript variable:
var query = ((val!=='CLOSED')||(val!=='OFF')||(val!=='Off'));
if query {
//statement true;
}
Absolutely.
var query = (val!=='CLOSED' || val!=='OFF' || val!=='Off');
if (query) {
//statement true;
}
Note that (val!=='CLOSED' || val!=='OFF' || val!=='Off') doesn't really make a lot of sense. It would evaluate to true for the string 'OFF', for example.
You probably want !(val == 'CLOSED' || val == 'OFF' || val == 'Off').
You can, but your syntax needs to be correct:
var query = ((val!=='CLOSED')||(val!=='OFF')||(val!=='Off'));
if(query) {
//statement true;
}
Notice the parenthesis around query
You can use function for that if variable will change.
function checkVariable(variable) {
return ((variable !== 'CLOSED') || (variable !== 'OFF') || (variable !== 'Off'));
}
if (checkVariable(variable)) {}
If not, then just assign statement value to variable and use it again.
var result = (variable !== 'CLOSED' || variable !== 'OFF' || variable !== 'Off');
if (result) {}
No.
You could store the result of performing the tests and reuse that (the if statement does require the test to be placed in parentheses though):
var result = ((val!=='CLOSED')||(val!=='OFF')||(val!=='Off'));
if (result) {
//statement true;
}
… but that wouldn't re-evaluate the statements if val was to change. So it is not the same as repeating the tests each time.
You could use a function though.
var query = function (val) {
return ((val!=='CLOSED')||(val!=='OFF')||(val!=='Off'));
}
if (query(some_value)) {
//statement true;
}
Yes you can, but it will always contain a value evaluated at the time the query variable was created.