How to check if a variable is declared in JavaScript? - variables

If I declare variable like this,
let variable;
How to check if the variable is declared?
(If it is initilized, I will do this way..)
if (typeof variable !== 'undefined') { }

You can catch ReferenceError to check if the variable is declared or not.
var declared = true;
try{
theVariable;
}
catch(e) {
if(e.name == "ReferenceError") {
declared = false;
}
}

A variable that is not declared will produce a ReferenceError, so you need a simple try catch:
try {
if (typeof variable !== 'undefined') { }
} catch(error) {
//Handle nondeclared
}

Related

I am writing a client side code to retreive a record but facing the below issue

I am writing this code using Xrm.Webapi.RetreiveRecord as below but I am getting the below error when debugging.
TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
if (typeof (ContosoPermit) == "undefined") { var ContosoPermit = { __namespace: true }; }
if (typeof (ContosoPermit.Scripts) == "undefined") { ContosoPermit.Scripts = { __namespace: true }; }
ContosoPermit.Scripts.PermitForm = {
handleOnLoad: function (executionContext) {
console.log('on load - permit form');
},
handleOnChangePermitType: function (executionContext)
{
console.log('on change - permit type');
},
_handlePermitTypeSettings: function (executionContext) {
var formContext = executionContext.getFormContext();
var permitType = formContext.getAttribute("contoso_permittype").getValue();
if (permitType == null) {
formContext.ui.tabs.get("inspectionsTab").setVisible(false);
return;
} else {
var permitTypeID = permitType[0].id;
debugger;
Xrm.WebApi.retrieveRecord("contoso_permittype", permitTypeID).then(
function success(result) {
if (result.contoso_requireinspections) {
formContext.ui.tabs.get("inspectionstab").setVisible(true);
}
else {
formContext.ui.tabs.get("inspectionstab").setVisible(false);
}
},
function (error) { alert('Error' + error.message) });
}
},
__namespace: true
}

Vuejs check for a null or undefined value in a method

I don't understand why I can't do
openAndFillModalSoin(soin)
{
this.show = true,
this.vDate = soin.date,
this.vCategorie = soin.categoriesoin.name,
//This can be null
if(soin.rabaisraion){
this.vReasonReduction = soin.rabaisraison.id;
}
this.vPaiement = soin.moyendepaiement.nam,
this.vRefer = soin.referedBy,
//This can be null aswell
this.vGiftCard = soin.boncadeau.id,
this.vVoucher = soin.bonreduction.id;
this.vID = soin.id;
},
The "if" parts doesn't work, it asks for an expression.
You have commas instead of semicolons ending the preceding line.
if(soin.rabaisraion){
this.vReasonReduction = soin.rabaisraison.id;
}
This this code will run when the following is NOT TRUE
soin.rabaisraion is the number 0, false, null, undefined, or an empty string.
To reiterate, the string 'false', the string '0' and and an array (empty or not) are all true.
Also, if soin is null or undefined, that will be a runtime error.
Perhaps you want this:
if(soin && soin.rabaisraion){
this.vReasonReduction = soin.rabaisraison.id;
}
Regardless, add a log before to see what's going on:
console.log('checking soin', soin)
console.log('checking boolean soin', !!soin)
if(soin && soin.rabaisraion){
this.vReasonReduction = soin.rabaisraison.id;
}
The '!!' will force the value to boolean.
//check undefined Array
if (typeof myArray === "undefined") {
alert("myArray is undefined");
}
// check undefined object
if (typeof myObj === "undefined") {
alert("myObj is undefined");
}
//check object property
if (typeof myObj.some_property === "undefined") {
alert("some_property is undefined");
}

Override a javascript function in Odoo 11?

I want to inherit function add_product of models.Order.
Here is the original function
/point_of_sale/static/src/js/models.js
add_product: function(product, options){
if(this._printed){
this.destroy();
return this.pos.get_order().add_product(product, options);
}
this.assert_editable();
options = options || {};
var attr = JSON.parse(JSON.stringify(product));
attr.pos = this.pos;
attr.order = this;
var line = new exports.Orderline({}, {pos: this.pos, order: this, product: product});
if(options.quantity !== undefined){
line.set_quantity(options.quantity);
}
if(options.price !== undefined){
line.set_unit_price(options.price);
}
//To substract from the unit price the included taxes mapped by the fiscal position
this.fix_tax_included_price(line);
if(options.discount !== undefined){
line.set_discount(options.discount);
}
if(options.extras !== undefined){
for (var prop in options.extras) {
line[prop] = options.extras[prop];
}
}
var to_merge_orderline;
for (var i = 0; i < this.orderlines.length; i++) {
if(this.orderlines.at(i).can_be_merged_with(line) && options.merge !== false){
to_merge_orderline = this.orderlines.at(i);
}
}
if (to_merge_orderline){
to_merge_orderline.merge(line);
} else {
this.orderlines.add(line);
}
this.select_orderline(this.get_last_orderline());
if(line.has_product_lot){
this.display_lot_popup();
}
},
I need to add one more condidtion like,
if(options.is_promo !== undefined){
line.set_promo(options.is_promo);
}
},
So in my custom module, I tried this,
var _super_order = models.Order.prototype;
models.Order = models.Order.extend({
add_product: function(product, options){
if(options.is_promo !== undefined){
line.set_promo(options.is_promo);
}
_super_order.add_product.apply(this,arguments);
},
But it throws an error, line is not defined.
How can i do it?

How to stop Promise.all loop when it rejects

I'm having a hard time trying to stop the loop in promise.all if one promise rejects it. Here's how I did it. Is there something wrong with this?
Promise.all(myArray.map((obj) => {
this.someFunction(obj);
}))
Here's the function I call..
someFunction(){
return new Promise(function (resolve, reject) {
....
reject()
})}
I have updated my code, it is tested and it works on my machine with the mock data I feed it with. I am not exactly sure how the rest of your code is structured but it is something likes this: Oh and you cannot break out of a map, but we will use a simple for loop because we can break out of that:
function someFunction(){
return new Promise(function (resolve, reject) {
// I will be rejeccting a boolean
// If you are resolving something, resolve it as true
reject(false)
})}
async function shouldStopLoop(){
// the boolean will come here
// if it is false, the catch block will return
// if it is true, the try block will return
let stopLoop = null;
let result = null;
try {
result = await someFunction();
return result
} catch(error) {
stopLoop = error;
return stopLoop;
}
}
function mayReturnPromiseAll() {
let myArray = ['stuf to loop over...']
let arraytoGoInPrimiseAll = [];
// Array.prototype.map cannot be stopped
// Thats why we will use a for loop and we will push the data we need
// into another array
for (var i = 0; i < myArray.length; i++) {
if (!this.someFunction(obj)) {
break;
} else {
// push things in arraytoGoInPrimiseAll
}
}
if(arraytoGoInPrimiseAll.length > 0){
return Promise.all(arraytoGoInPrimiseAll)
} else {
// do something else
}
};
Try this:
const arrayOfFunctions = myArray.map(obj => this.someFunction(obj))
Promise.all(arrayOfFunctions).then(values => {
console.log(values);
}).catch(error => {
console.log(error)
});

How to yield in map?

I am using react native to build my application and I am trying to convert my variables to camelCase using the code below
export default function formatToCamelCase(inputObject: {[key: string]: any}) {
let snakeKeys = Object.keys(inputObject);
let newObject = {};
for (let key of snakeKeys) {
if (typeof inputObject[key] !== 'object') {
newObject[parseToCamelCase(key)] = inputObject[key];
} else if (inputObject[key] !== null && !Array.isArray(inputObject[key])) {
newObject[parseToCamelCase(key)] = formatToCamelCase(inputObject[key]);
} else {
newObject[parseToCamelCase(key)] = inputObject[key];
}
}
return newObject;
}
export function formatArrayToCamelCase(inputArray: Array<{[key: string]: any}>) {
return inputArray.map((object) => {
return formatToCamelCase(object);
});
}
And I am trying to call the formatArrayToCamelCase method in the function here (in a separate file):
import formatToCamelCase, {formatArrayToCamelCase} from '../helpers/formatToCamelCase';
export function* fetchWeighInWeighOutEvent(action: FetchWeighInWeighOutEventAction): any {
...
Object.values(locations).map((location) => {
let timeslotsArray = location.timeslots;
if (timeslotsArray.length > 0) {
//Problem here - shows that yield is a reserved word
let camelCaseTimeslots = yield call(formatArrayToCamelCase, timeslotsArray);
}
});
I was unable to put the yield call in the .map, when trying to run the code, I get the following error:
SyntaxError: yield is a reserve word
How can I overcome this issue so that I can call the formatArrayToCamelCase function and convert my array accordingly?