I have an if-statement: if all the properties of an object have values, then the next button will be enabled.
const handleButton = () => {
if(
values.streetAdress !== ""
&& values.postalCode !== ""
&& values.city !== ""
&& values.sex !== ""
&& values.birthName !== ""
&& values.birthPlace !== ""
&& values.birthday !== ""
&& values.country !== ""
&& values.family !== ""
&& values.insuranceID !== ""
){
setDisabeld(false)
}else{
setDisabeld(true)
}
Is there a way to shorten this expression, so all properties will be checked at once?
you can use the Array.prototype.every() method on the values of the object.
const isNotEmpty = Object.values(values).every((v) => v !== '')
if(isNotEmpty) {
setDisabeld(false)
} else{
setDisabeld(true)
}
this is a very dummy question for all the experts here I suppose.
I have a bunch of if statements (16), and I'm trying to find a way to write 48 lines of code in much less because I'm sure it's possible.
I've read everywhere that long if/else if statements are bad practices.
So how to write this bunch of code the clever way? Thanks
if (!latitude || typeof latitude == 'undefined') {
latitude == 'undefined';
} else if( !longitude || typeof longitude == 'undefined' ) {
longitude == 'undefined';
} else if( !name || typeof name == 'undefined' ) {
name == 'undefined';
} else if( !adresseNum || typeof adresseNum == 'undefined' ) {
adresseNum == 'undefined';
} else if( !adresseVille || typeof adresseVille == 'undefined' ) {
adresseVille == 'undefined';
} else if( !adresseDpt || typeof adresseDpt == 'undefined' ) {
adresseDpt == 'undefined';
} else if( !adresseRg || typeof adresseRg == 'undefined' ) {
adresseRg == 'undefined';
} else if( !adresseFr || typeof adresseFr == 'undefined' ) {
adresseFr == 'undefined';
} else if( !adresseCp || typeof adresseCp == 'undefined' ) {
adresseCp == 'undefined';
} else if( !telephone || typeof telephone == 'undefined' ) {
telephone == 'undefined';
} else if( !horaires || typeof horaires == 'undefined' ) {
horaires == 'undefined';
} else if( !note || typeof note == 'undefined' ) {
note == 'undefined';
} else if( !reviewFinale || typeof reviewFinale == 'undefined' ) {
reviewFinale == 'undefined';
} else if( !website || typeof website == 'undefined' ) {
website == 'undefined';
} else if( !types || typeof types == 'undefined' ) {
types == 'undefined';
} else {
console.log('All fields OK');
}
var isOk = [
latitude,
longtitude,
name,
adresseNum,
adresseVille,
adresseDpt,
adresseRg,
adresseFr,
adresseCp,
telephone,
horaires,
note,
reviewFinale,
website,
types
].every(function (value) {
return !!value;
});
if (isOk) {
console.log('All fields OK');
}
But I think you'd better combine all variables to object or form
you can do a function that checks them all like this
var isDefined = [latitude, longtitude, name, adresseNum, adresseVille, adresseDpt, adresseRg, adresseFr, adresseCp, telephone, horaires, note, reviewFinale, website, types].every(function (value) {return !!value;});
With ES6, you could use an object with all variables as key and value pair, then iterate with Array#every and assign on falsy values undefined and check the result with an if statement.
var data = { latitude, longitude, name, adresseNum, adresseVille, adresseDpt, adresseRg, adresseFr, adresseCp, telephone, horaires, note, reviewFinale, website, types };
if (Object.keys(data).every(k => data[k] || (data[k] = 'undefined', false))) {
console.log('All fields OK');
}
is every variable defined by itself or is it coming from another object or similar to var telephone = obj.telephone?
if that is the case you could do something like this:
var ok = true;
for (var o in obj) {
if (!obj[o]) {
obj[o] == 'undefined';
ok = false;
}
}
if (ok) {
console.log('all fields are ok');
}
An option that might works is using default value in argument destructure. Basically you check for every variable if it's undefined (by the way, what happens if one of those are the value 'false'?).
This is specific for this case though...
function functionWithSomeLogic({
latitude = 'undefined',
longitude = 'undefined',
name = 'undefined',
adresseNum = 'undefined'
// ... and the rest of the variables
}) {
// Do whatever here, all the arguments are initialized or have the string value of 'undefined'
}
by the way, if instead of setting a default value you would like to throw an exception
const throwArg = argName => throw new Error(`Argument missing: ${argName}`);
function functionWithSomeLogic({
latitude = throwArg('latitude'),
longitude = throwArg('longitude'),
name = throwArg('name'),
adresseNum = throwArg('adresseNum')
// ... and the rest of the variables
}) {
// Do whatever here, all the arguments are initialized, if one of them
// had been undefined, an appropriate exception will be thrown before this body
}
A simple es6 function will do the trick. as #Andrey pointed out.
const areDefined = (...args) => args.every(elm => !!elm);
if(areDefined(latitude, longitude, name/*, ...*/)) {
console.log('All fields OK');
}
I have set a validation for undefined here below in my javascript code. Even if the value is undefined it is going inside the if condition
if (VSATSaving.PANORAMIC_IMAGES != 'undefined' || VSATSaving.PANORAMIC_IMAGES != "") {
VSATSaving.PANORAMIC_IMAGES = lstPanaromicImages.join();
}
update
Updated code
var PANAROMIC_120 = $(document.getElementById('ImgPanaromic120')).data('imagename');
if (PANAROMIC_120 != "" && PANAROMIC_120 != undefined)
lstPanaromicImages.push(PANAROMIC_120);
var PANAROMIC_150 = $(document.getElementById('ImgPanaromic150')).data('imagename');
if (PANAROMIC_150 != "" && PANAROMIC_150 != undefined)
lstPanaromicImages.push(PANAROMIC_150);
var PANAROMIC_180 = $(document.getElementById('ImgPanaromic180')).data('imagename');
if (PANAROMIC_180 != "" && PANAROMIC_180 != undefined)
lstPanaromicImages.push(PANAROMIC_180);
var PANAROMIC_210 = $(document.getElementById('ImgPanaromic210')).data('imagename');
if (PANAROMIC_210 != "" && PANAROMIC_210 != undefined)
lstPanaromicImages.push(PANAROMIC_210);
var PANAROMIC_240 = $(document.getElementById('ImgPanaromic240')).data('imagename');
if (PANAROMIC_240 != "" && PANAROMIC_240 != undefined)
lstPanaromicImages.push(PANAROMIC_240);
if (VSATSaving.PANORAMIC_IMAGES != undefined || VSATSaving.PANORAMIC_IMAGES != "") {
VSATSaving.PANORAMIC_IMAGES = lstPanaromicImages.join();
}
You used an OR operator. This means that if the VSATSaving.PANORAMIC_IMAGES value is undefined, it is still different from "", that's why the if statement is true.
Just replace the OR operator by an AND:
if (VSATSaving.PANORAMIC_IMAGES !== undefined && VSATSaving.PANORAMIC_IMAGES !== "") {
VSATSaving.PANORAMIC_IMAGES = lstPanaromicImages.join();
}
Note that I removed the single quotes around the undefined keyword.
you can use isNaN function in javascript.
if (!isNaN(VSATSaving.PANORAMIC_IMAGES)) {
VSATSaving.PANORAMIC_IMAGES = lstPanaromicImages.join();
}
if you are using "use strict" in your document then you can use the following way to check:
if (typeof PANAROMIC_120 != "undefined" && PANAROMIC_120 != "")
lstPanaromicImages.push(PANAROMIC_120);
Note that I am using quotes over undefined when I have added typeof
Check undefined condition like as follows
var PANAROMIC_120 = $(document.getElementById('ImgPanaromic120')).data('imagename');
if (PANAROMIC_120 != "" && typeof(PANAROMIC_120) != "undefined")
lstPanaromicImages.push(PANAROMIC_120);
var PANAROMIC_150 = $(document.getElementById('ImgPanaromic150')).data('imagename');
if (PANAROMIC_150 != "" && typeof(PANAROMIC_150) != "undefined")
lstPanaromicImages.push(PANAROMIC_150);
var PANAROMIC_180 = $(document.getElementById('ImgPanaromic180')).data('imagename');
if (PANAROMIC_180 != "" && typeof(PANAROMIC_180) != "undefined")
lstPanaromicImages.push(PANAROMIC_180);
var PANAROMIC_210 = $(document.getElementById('ImgPanaromic210')).data('imagename');
if (PANAROMIC_210 != "" && typeof(PANAROMIC_210) != "undefined")
lstPanaromicImages.push(PANAROMIC_210);
var PANAROMIC_240 = $(document.getElementById('ImgPanaromic240')).data('imagename');
if (PANAROMIC_240 != "" && typeof(PANAROMIC_240) != "undefined")
lstPanaromicImages.push(PANAROMIC_240);
if (typeof(VSATSaving.PANORAMIC_IMAGES) != "undefined" || VSATSaving.PANORAMIC_IMAGES != "") {
VSATSaving.PANORAMIC_IMAGES = lstPanaromicImages.join();
}
HTML:
<div class="form-group">
<div id="errorsum"></div>
</div>
JavaScript:
var errornbr = 0;
var mess;
$("#addclient input.form-control").each(function (index) {
if ($(this).val() == "") {
if ($(this).attr("data-val") != undefined) {
if ($(this).attr("data-val-required") != undefined) {
errornbr = errornbr + 1;
mess = mess + "<br/>" + $(this).attr("data-val-required");
}
}
}
});
$("#errorsum").empty();
if (errornbr > 0) {
$("#errorsum").append("<label class='col-xs-3 control-label text-danger' >" + mess + "</label>");
}
First line of the label text is always undefined. the mess didn't contains such value.
So I need to know:
Does the empty() method is the reason of this?
How can I fix this issue?
change var mess; to var mess = '';
Make the assume text value making it not return undefined
Please use ( typeof VALUE != 'undefined' ) instead of ( VALUE != undefined )
Please write condition like this
if( typeof $(this).attr("data-val") != 'undefined' ){
if( typeof $(this).attr("data-val-required") != 'undefined' ){
}
}
I have two properties where i need to check null and undefined both for each, how can i use that in if else statements ?
main.js
var validateControlRating = function () {
if ( ($scope.controlProcessRatingDTO.controlPerformanceRatingKey === null ||
$scope.controlProcessRatingDTO.controlPerformanceRatingKey === undefined)
&&
($scope.controlProcessRatingDTO.controlDesignRatingKey === null ||
$scope.controlProcessRatingDTO.controlDesignRatingKey === undefined) ) {
$scope.caculatedRatingDiv = false;
} else {
$http.get('app/control/rest/calculateControlEffectiveness/' + $scope.controlProcessRatingDTO.controlDesignRatingKey + '/' + $scope.controlProcessRatingDTO.controlPerformanceRatingKey).success(function (data) {
$scope.calcaulatedRating = data;
}, function (error) {
$scope.statusClass ='status invalid userErrorInfo';
var errorMessage = error.data.errorMsg;
if (error.data.techErrorMsg) {
errorMessage = error.data.techErrorMsg;
}
$scope.statusInfo = errorMessage;
});
$scope.ratingValidationMsg = '';
$scope.ratingWinValidationClass = 'valid';
$scope.caculatedRatingDiv = true;
$scope.enableRatingSave = false;
}
};
It's a little tedious in javascript, you have to write each condition, and use parentheses etc
if ( ($scope.controlProcessRatingDTO.controlPerformanceRatingKey === null ||
$scope.controlProcessRatingDTO.controlPerformanceRatingKey === undefined)
&&
($scope.controlProcessRatingDTO.controlDesignRatingKey === null ||
$scope.controlProcessRatingDTO.controlDesignRatingKey === undefined) ) {...
or just
if ([null, undefined].indexOf( $scope.controlProcessRatingDTO.controlPerformanceRatingKey ) === -1
&&
[null, undefined].indexOf( $scope.controlProcessRatingDTO.controlDesignRatingKey ) === -1) {...
I think you need to to check this correclty, check for undefined then for null
and use && not || because your code will go to check null value for undefined variable and this surely will throw exception
code:
if( typeof myVar == 'undefined' ? false: myVar )
{ // go here defined and value not null
}
or
code:
if(typeof myVar != 'undefined' && myVar)
{ // go here defined and value not null
}
In your code check will go like
if ((typeof $scope.controlProcessRatingDTO.controlDesignRatingKey !== undefined||
typeof $scope.controlProcessRatingDTO.controlPerformanceRatingKey !== undefined) &&
($scope.controlProcessRatingDTO.controlDesignRatingKey !== null ||
$scope.controlProcessRatingDTO.controlPerformanceRatingKey !== null)) {
// do home work
}else { // do other home work }
You can use negate operator as well, but this would make work for "false" as well:
if (!$scope.controlProcessRatingDTO.controlPerformanceRatingKey && !$scope.controlProcessRatingDTO.controlDesignRatingKey) {
This is a bit shorter but if you want to treat False values separately, then use the Adeneo's answer above.
You could do this:
if ( some_variable == null ){
// some_variable is either null or undefined
}
taken from: How to check for an undefined or null variable in JavaScript?