Javascript ||, how to compare multiple variables value? - javascript

How to right this syntax correctly:
if (tipoTropaPrioritaria[m] || troopsCount[m] || availableTroops[m]) == ("null" || "undefined") {
...
}
(to check if any of the first 3 variables is null or undefined)

You could define a small helper function that does the check and then use it on all the values:
function notset(v) {
return (v === undefined) || (v === null);
}
if (notset(tipoTropaPrioritaria[m]) || notset(troopsCount[m]) ||
notset(availableTroops[m])) {
...
}

Use:
if (tipoTropaPrioritaria[m] == null || troopsCount[m] == null || availableTroops[m] == null ||
tipoTropaPrioritaria[m] == undefined || troopsCount[m] == undefined || availableTroops[m] == undefined) {
// ...
}
EDIT: It's probably better to use the === (threequals) operator in this case.
if (tipoTropaPrioritaria[m] === null || troopsCount[m] === null || availableTroops[m] === null ||
tipoTropaPrioritaria[m] === undefined || troopsCount[m] === undefined || availableTroops[m] === undefined) {
// ...
}
or:
if (null in {tipoTropaPrioritaria[m]:0, troopsCount[m]:0, availableTroops[m]:0} || undefined in {tipoTropaPrioritaria[m]:0, troopsCount[m]:0, availableTroops[m]:0}) {

The way to do is:
if ((tipoTropaPrioritaria[m] == null || tipoTropaPrioritaria[m] == undefined)
|| (troopsCount[m] == null || troopsCount[m] == undefined) ||
(availableTroops[m] == null || availableTroops[m] == undefined)) {
...
}

If you do this a lot you can create a helper function
function isNullOrUndef(args) {
for (var i =0; i < arguments.length; i++) {
if (arguments[i] == null || typeof arguments[i] === "undefined") {
return true
}
}
return false
}
if (isNullOrUndef(tipoTropaPrioritaria[m], troopsCount[m], availableTroops[m]))
...

This is the best way to do what you want
if (!tipoTropaPrioritaria[m] || !troopsCount[m] || !availableTroops[m]) {
...
}
The ! operator coerces the result into a boolean that can be tested for (null and undefined becomes false), and with the ! in front false is negated into true.
The other way to do it is to test each expression against null and undefined.
function isNullOrUndefined(val) {
return (val === null || typeof val == "undefined");
}
if (isNullOrUndefined(a) || isNullOrUndefined(b) ... ) {
And so you know it, the correct way to test for undefined is
if (typeof foo === "undefined") {...

if (tipoTropaPrioritaria[m] && troopsCount[m] && availableTroops[m]) { }
else { /* At least ones is undefined/null OR FALSE */ }
if (tipoTropaPrioritaria[m] == null || troopsCount[m] == null || availableTroops[m] == null)
{ /* One is null. */ }

if you want to check if they are null or undefined you can write
if (!tipoTropaPrioritaria[m] || !troopsCount[m] || !availableTroops[m])
both null and undefined are falsely values. Then this will only be true if none of this are null or undefined.
Please consider that there are other falsely values as well:
0
empty string
NaN

Related

How can I push data into an array?

I have pushed some data into an array:
if(target === 'create'){
if(name === 'form[username]' || name === 'form[name]' || name === 'form[slug]' || name === 'form[plainPassword]'){
errors.push(name);
}
} else {
if(name === 'form[username]' || name === 'form[name]' || name === 'form[slug]' ){
errors.push(name);
}
}
It actually works fine. But it seems to me that it is really too much repeating code, but I still cannot find a way to reduce the code, or make a simpler better solution.
I would do it in two methods
function CheckErrors(target,name){
switch(target){
case 'create':
SaveError(name,true);
break;
default:
SaveError(name);
break;
}
}
function SaveError(name,checkPassword){
if(name === 'form[username]' || name === 'form[name]' || name === 'form[slug]' ||(checkPassword && name === 'form[plainPassword]')){
errors.push(name);
}
}
You could use arrays to simplify your if statement:
if((target === 'create' && name === 'form[plainPassword]') || ['form[username]', 'form[name]', 'form[slug]'].includes(name)){
errors.push(name);
}
If I rigth understand you, you want to simplify your statements. From my perspective it could be like this:
if(name === 'form[username]' || name === 'form[name]' || name === 'form[slug]'
|| (name === 'form[plainPassword]' && target === 'create')){
errors.push(name);
}
Since:
name === 'form[username]' || name === 'form[name]' || name === 'form[slug]'
is repeated two times, it doesn't matter if target === 'create' is true or false for this statements.
In fact just add (name === 'form[plainPassword]' && target === 'create') to if statement and that's all

Table filters in Vuejs

I'm building a small application in vuejs where I'm having a filter something like this:
tableFilter: function () {
const searchTerm = this.search.toLowerCase();
const searchByType = this.search_by_tag.toLowerCase();
if(this.contactStore.contactList)
{
return this.contactStore.contactList.data.filter((item) =>
(item.first_name.toLowerCase().includes(searchTerm)
|| (item.last_name !==null && item.last_name.toLowerCase().includes(searchTerm))
|| (item.company.name !==null && item.company.name.toLowerCase().includes(searchTerm))
|| item.email.toLowerCase().includes(searchTerm)
|| (item.address !== null && item.address.toLowerCase().includes(searchTerm))
|| (item.city !== null && item.city.toLowerCase().includes(searchTerm))
|| (item.mobile !==null && item.mobile.toLowerCase().includes(searchTerm)))
&& ((item.profile !==null && item.profile.toLowerCase().includes(searchByType))
|| (item.company.type !== null && item.company.type.toLowerCase().includes(searchByType))
|| (item.company.sub_type !== null && item.company.sub_type.toLowerCase().includes(searchByType))));
}
},
In this I've a property called item.company which can be null, so while implementing
(item.company.type !== null && item.company.type.toLowerCase().includes(searchByType))
it is throwing error:
Error in render function: "TypeError: Cannot read property 'type' of null"
I'm looking for a solution where I can have if-else to find out whether the item is having company or not, if property is available then it can do the filters respectively.
Thanks
If you just want to fix the error:
|| (item.company && item.company.type !== null && item.company.type.toLowerCase().includes(searchByType))
But if you want to not filter by company if it is null:
|| (item.company ? && item.company.type !== null && item.company.type.toLowerCase().includes(searchByType) : true)

Why use (!fn || zid(handler.fn) === zid(fn)) to (!fn || handler.fn === fn) in zepto.js - event.js?

In event.js, to judge the same handler, here is code:
return handler
&& (!event.e || handler.e == event.e)
&& (!event.ns || matcher.test(handler.ns))
&& (!fn || zid(handler.fn) === zid(fn))
&& (!selector || handler.sel == selector)
Why use (!fn || zid(handler.fn) === zid(fn)) to (!fn || handler.fn === fn)
Here is the source code of zid
var _zid = 1
function zid(element) {
return element._zid || (element._zid = _zid++)
}
if I have to judge two functions, a === b is enough
why to use zid(a) === zid(b)? Maybe some trap?
I don't know why?
Here is the source code of zepto.js event.js: https://github.com/madrobby/zepto/blob/master/src/event.js

JS | Why is the property of the Object truthy although it's empty?

So the value of the first object with the property "single" is empty, but still truthy, what did I wrong?
function every(collection, pre) {
var rtr = null;
for(var e in collection){
if(collection[e][pre] !== null &&
collection[e][pre] !== undefined &&
collection[e][pre] !== 0 &&
collection[e][pre] !== "" &&
collection[e][pre] !== false &&
collection[e][pre] !== NaN){
rtr = true;
}
else
rtr = false;
}
console.log(rtr);
}
every([{"single": ""}, {"single": "double"}], "single");
You console.log outside the loop. Try this (I also removed the stray `):
function every(collection, pre) {
var rtr = null;
for(var e in collection){
if(collection[e][pre] !== null &&
collection[e][pre] !== undefined &&
collection[e][pre] !== 0 &&
collection[e][pre] !== "" &&
collection[e][pre] !== false &&
collection[e][pre] !== NaN){
rtr = true;
}
else
rtr = false;
console.log(rtr);
}
}
every([{"single": ""}, {"single": "double"}], "single");
It logs
false
true

JavaScript: Parsing a string Boolean value? [duplicate]

This question already has answers here:
How can I convert a string to boolean in JavaScript?
(102 answers)
Closed 4 years ago.
JavaScript has parseInt() and parseFloat(), but there's no parseBool or parseBoolean method in the global scope, as far as I'm aware.
I need a method that takes strings with values like "true" or "false" and returns a JavaScript Boolean.
Here's my implementation:
function parseBool(value) {
return (typeof value === "undefined") ?
false :
// trim using jQuery.trim()'s source
value.replace(/^\s+|\s+$/g, "").toLowerCase() === "true";
}
Is this a good function? Please give me your feedback.
Thanks!
I would be inclined to do a one liner with a ternary if.
var bool_value = value == "true" ? true : false
Edit: Even quicker would be to simply avoid using the a logical statement and instead just use the expression itself:
var bool_value = value == 'true';
This works because value == 'true' is evaluated based on whether the value variable is a string of 'true'. If it is, that whole expression becomes true and if not, it becomes false, then that result gets assigned to bool_value after evaluation.
You can use JSON.parse for that:
JSON.parse("true"); //returns boolean true
It depends how you wish the function to work.
If all you wish to do is test for the word 'true' inside the string, and define any string (or nonstring) that doesn't have it as false, the easiest way is probably this:
function parseBoolean(str) {
return /true/i.test(str);
}
If you wish to assure that the entire string is the word true you could do this:
function parseBoolean(str) {
return /^true$/i.test(str);
}
You can try the following:
function parseBool(val)
{
if ((typeof val === 'string' && (val.toLowerCase() === 'true' || val.toLowerCase() === 'yes')) || val === 1)
return true;
else if ((typeof val === 'string' && (val.toLowerCase() === 'false' || val.toLowerCase() === 'no')) || val === 0)
return false;
return null;
}
If it's a valid value, it returns the equivalent bool value otherwise it returns null.
You can use JSON.parse or jQuery.parseJSON and see if it returns true using something like this:
function test (input) {
try {
return !!$.parseJSON(input.toLowerCase());
} catch (e) { }
}
last but not least, a simple and efficient way to do it with a default value :
ES5
function parseBool(value, defaultValue) {
return (value == 'true' || value == 'false' || value === true || value === false) && JSON.parse(value) || defaultValue;
}
ES6 , a shorter one liner
const parseBool = (value, defaultValue) => ['true', 'false', true, false].includes(value) && JSON.parse(value) || defaultValue
JSON.parse is efficient to parse booleans
Personally I think it's not good, that your function "hides" invalid values as false and - depending on your use cases - doesn't return true for "1".
Another problem could be that it barfs on anything that's not a string.
I would use something like this:
function parseBool(value) {
if (typeof value === "string") {
value = value.replace(/^\s+|\s+$/g, "").toLowerCase();
if (value === "true" || value === "false")
return value === "true";
}
return; // returns undefined
}
And depending on the use cases extend it to distinguish between "0" and "1".
(Maybe there is a way to compare only once against "true", but I couldn't think of something right now.)
Why not keep it simple?
var parseBool = function(str) {
if (typeof str === 'string' && str.toLowerCase() == 'true')
return true;
return (parseInt(str) > 0);
}
You can add this code:
function parseBool(str) {
if (str.length == null) {
return str == 1 ? true : false;
} else {
return str == "true" ? true : false;
}
}
Works like this:
parseBool(1) //true
parseBool(0) //false
parseBool("true") //true
parseBool("false") //false
Wood-eye be careful.
After looking at all this code, I feel obligated to post:
Let's start with the shortest, but very strict way:
var str = "true";
var mybool = JSON.parse(str);
And end with a proper, more tolerant way:
var parseBool = function(str)
{
// console.log(typeof str);
// strict: JSON.parse(str)
if(str == null)
return false;
if (typeof str === 'boolean')
{
if(str === true)
return true;
return false;
}
if(typeof str === 'string')
{
if(str == "")
return false;
str = str.replace(/^\s+|\s+$/g, '');
if(str.toLowerCase() == 'true' || str.toLowerCase() == 'yes')
return true;
str = str.replace(/,/g, '.');
str = str.replace(/^\s*\-\s*/g, '-');
}
// var isNum = string.match(/^[0-9]+$/) != null;
// var isNum = /^\d+$/.test(str);
if(!isNaN(str))
return (parseFloat(str) != 0);
return false;
}
Testing:
var array_1 = new Array(true, 1, "1",-1, "-1", " - 1", "true", "TrUe", " true ", " TrUe", 1/0, "1.5", "1,5", 1.5, 5, -3, -0.1, 0.1, " - 0.1", Infinity, "Infinity", -Infinity, "-Infinity"," - Infinity", " yEs");
var array_2 = new Array(null, "", false, "false", " false ", " f alse", "FaLsE", 0, "00", "1/0", 0.0, "0.0", "0,0", "100a", "1 00", " 0 ", 0.0, "0.0", -0.0, "-0.0", " -1a ", "abc");
for(var i =0; i < array_1.length;++i){ console.log("array_1["+i+"] ("+array_1[i]+"): " + parseBool(array_1[i]));}
for(var i =0; i < array_2.length;++i){ console.log("array_2["+i+"] ("+array_2[i]+"): " + parseBool(array_2[i]));}
for(var i =0; i < array_1.length;++i){ console.log(parseBool(array_1[i]));}
for(var i =0; i < array_2.length;++i){ console.log(parseBool(array_2[i]));}
I like the solution provided by RoToRa (try to parse given value, if it has any boolean meaning, otherwise - don't). Nevertheless I'd like to provide small modification, to have it working more or less like Boolean.TryParse in C#, which supports out params. In JavaScript it can be implemented in the following manner:
var BoolHelpers = {
tryParse: function (value) {
if (typeof value == 'boolean' || value instanceof Boolean)
return value;
if (typeof value == 'string' || value instanceof String) {
value = value.trim().toLowerCase();
if (value === 'true' || value === 'false')
return value === 'true';
}
return { error: true, msg: 'Parsing error. Given value has no boolean meaning.' }
}
}
The usage:
var result = BoolHelpers.tryParse("false");
if (result.error) alert(result.msg);
stringjs has a toBoolean() method:
http://stringjs.com/#methods/toboolean-tobool
S('true').toBoolean() //true
S('false').toBoolean() //false
S('hello').toBoolean() //false
S(true).toBoolean() //true
S('on').toBoolean() //true
S('yes').toBoolean() //true
S('TRUE').toBoolean() //true
S('TrUe').toBoolean() //true
S('YES').toBoolean() //true
S('ON').toBoolean() //true
S('').toBoolean() //false
S(undefined).toBoolean() //false
S('undefined').toBoolean() //false
S(null).toBoolean() //false
S(false).toBoolean() //false
S({}).toBoolean() //false
S(1).toBoolean() //true
S(-1).toBoolean() //false
S(0).toBoolean() //false
I shamelessly converted Apache Common's toBoolean to JavaScript:
JSFiddle: https://jsfiddle.net/m2efvxLm/1/
Code:
function toBoolean(str) {
if (str == "true") {
return true;
}
if (!str) {
return false;
}
switch (str.length) {
case 1: {
var ch0 = str.charAt(0);
if (ch0 == 'y' || ch0 == 'Y' ||
ch0 == 't' || ch0 == 'T' ||
ch0 == '1') {
return true;
}
if (ch0 == 'n' || ch0 == 'N' ||
ch0 == 'f' || ch0 == 'F' ||
ch0 == '0') {
return false;
}
break;
}
case 2: {
var ch0 = str.charAt(0);
var ch1 = str.charAt(1);
if ((ch0 == 'o' || ch0 == 'O') &&
(ch1 == 'n' || ch1 == 'N') ) {
return true;
}
if ((ch0 == 'n' || ch0 == 'N') &&
(ch1 == 'o' || ch1 == 'O') ) {
return false;
}
break;
}
case 3: {
var ch0 = str.charAt(0);
var ch1 = str.charAt(1);
var ch2 = str.charAt(2);
if ((ch0 == 'y' || ch0 == 'Y') &&
(ch1 == 'e' || ch1 == 'E') &&
(ch2 == 's' || ch2 == 'S') ) {
return true;
}
if ((ch0 == 'o' || ch0 == 'O') &&
(ch1 == 'f' || ch1 == 'F') &&
(ch2 == 'f' || ch2 == 'F') ) {
return false;
}
break;
}
case 4: {
var ch0 = str.charAt(0);
var ch1 = str.charAt(1);
var ch2 = str.charAt(2);
var ch3 = str.charAt(3);
if ((ch0 == 't' || ch0 == 'T') &&
(ch1 == 'r' || ch1 == 'R') &&
(ch2 == 'u' || ch2 == 'U') &&
(ch3 == 'e' || ch3 == 'E') ) {
return true;
}
break;
}
case 5: {
var ch0 = str.charAt(0);
var ch1 = str.charAt(1);
var ch2 = str.charAt(2);
var ch3 = str.charAt(3);
var ch4 = str.charAt(4);
if ((ch0 == 'f' || ch0 == 'F') &&
(ch1 == 'a' || ch1 == 'A') &&
(ch2 == 'l' || ch2 == 'L') &&
(ch3 == 's' || ch3 == 'S') &&
(ch4 == 'e' || ch4 == 'E') ) {
return false;
}
break;
}
default:
break;
}
return false;
}
console.log(toBoolean("yEs")); // true
console.log(toBoolean("yES")); // true
console.log(toBoolean("no")); // false
console.log(toBoolean("NO")); // false
console.log(toBoolean("on")); // true
console.log(toBoolean("oFf")); // false
Inspect this element, and view the console output.
Enough to using eval javascript function to convert string to boolean
eval('true')
eval('false')

Categories