How to use return; with functions - javascript

In some places of my program I use a check that holds the script if the data doesn't match:
const a = 1;
//...
//...
if (param1 != 1 && param2 != 3) {
return; // stop script
}
//...
//...
if (param1 != 1 && param2 != 3) {
return; // stop script
}
//...
//...
So i create function:
function checkIfOk(param1, param2)
{
if (param1 != 1 && param2 != 3) {
return; // stop script
}
}
But now:
const a = 1;
//...
//...
checkIfOk(param1, param2);
//...
//...
checkIfOk(param1, param2);
//...
//...
Doesn't pause the function at error.
const a = 1;
//...
//...
return checkIfOk(param1, param2);
//...
//...
return checkIfOk(param1, param2);
//...
//...
This stops the function in any situation.
I don't want use throw errors because I use it in functions, so program should still running.

Here's a quicker way to implement what you want:
function checkIfOk(param1, param2) {
return (param1 != 1 && param2 != 3);
}
if (checkIfOk(param1, param2))
return;
I guess semantically it should be checkIfNotOk(), but eh...

You need to return a value (e.g. false and true), and only stop for example when returning false
e.g.
function checkIfOk(param1, param2)
{
if (param1 != 1 && param2 != 3) {
return false; // stop script
}
return true; // OK!!
}
if(!checkIfOk(param1, param2))
return; //only return if checkIfOk returns false

Related

can we validate multiple functions inside if condition with AND operator using java script is there any other way to check multiple functions true?

I have added these functions and need return something based which function is returning true but it is not working.
//this is function1/
function A() {
return true;
}
function B() {
return true;
}
function C() {
if ({
{
var -customJS - page_type_lookup
}
} === 'product') {
var config = document.querySelector('#product-content > div.product-variations.clearfix > div.attribute.variant-dropdown > div.attribute-values-section > div.label.va-navSectionalOrientation').innerText;
if (config.includes('Sectional Orientation')) {
return true;
} else {
return false;
}
}
}
if (A() === true && B() === true && C() === true) {
return 'A+ Content, RTA Product, Sectional Configurator';
} else if (A() === true && B() === true) {
return 'A+ Content, RTA Product';
} else if (B() === true && C() === true) {
return 'RTA Product, Sectional Configurator';
} else if (C() === true && A() === true) {
return 'Sectional Configurator, A+ Content';
} else if (A() === true) {
return 'A+ Content';
} else if (B() === true) {
return 'RTA Product';
} else {
return 'Sectional Configurator';
}
}
If you have more than one function and a data set which reflects the wanted value of each flag, you could take an array for the functions retun values and another for the strings which are filterd and joined for the result.
const
flags = [a(), b(), c()],
result = ['A+ Content', 'RTA Product', 'Sectional Configurator']
.filter((_, i) => flags[i])
.join(', ');

How are pointers referenced in JS?

I found this code while doing a random task, and I'm wondering how it works with the memory in JS.
There are obviously more that one level of nested functions, which reference variables from all sorts of levels above (outer contexts). Specifically the variable i.
!function () {
function valOrDef(val, def) {
var _val, _def = typeof def === 'undefined' ? 0 : def;
if (typeof val !== 'undefined' && typeof val !== null) _val = parseFloat(val, 10);
return !isNaN(_val) ? _val : _def;
}
function reg(els,l) {
if (!els || !(l = els.length)) return;
function h(el) {
var p = el.querySelector('button.decrease'),
i = el.querySelector('input'),
n = el.querySelector('button.increase');
var min = valOrDef(i.min, 0), step = valOrDef(i.step, 1);
function inc(e) { e.preventDefault(); e.stopPropagation(); i.value = Math.max(min, valOrDef(i.value, 0) + step); fire(); }
function dec(e) { e.preventDefault(); e.stopPropagation(); i.value = Math.max(min, valOrDef(i.value, 0) - step); fire(); }
function chk() { i.value = valOrDef(i.value, min); }
function fire() { i.dispatchEvent(new Event('change')); }
p.addEventListener('pointerup', dec, true);
n.addEventListener('pointerup', inc, true);
i.addEventListener('change', chk, false);
}
while (l--) h(els[l]);
}
reg(document.querySelectorAll('.single-inc-dec'));
}();
So, I'm wondering, is that a wasting memory, because each callback has it's own "environment" with it's own pointers?
I think it will be more efficent to have the methods in an outer scope, and provide them with arguments. In this case the inc, dec & fire outside the reg function, and recieve the i as a parameter. So something like this:
!function () {
function valOrDef(val, def) {
var _val, _def = typeof def === 'undefined' ? 0 : def;
if (typeof val !== 'undefined' && typeof val !== null) _val = parseFloat(val, 10);
return !isNaN(_val) ? _val : _def;
}
function inc(i) { return function(e) { e.preventDefault(); e.stopPropagation(); i.value = Math.max(min, valOrDef(i.value, 0) + step); fire(i); } }
function dec(i) { return function(e) { e.preventDefault(); e.stopPropagation(); i.value = Math.max(min, valOrDef(i.value, 0) - step); fire(); }
function fire(i) { i.dispatchEvent(new Event('change')); }
function reg(els,l) {
if (!els || !(l = els.length)) return;
function h(el) {
var p = el.querySelector('button.decrease'),
i = el.querySelector('input'),
n = el.querySelector('button.increase');
var min = valOrDef(i.min, 0), step = valOrDef(i.step, 1);
function chk() { i.value = valOrDef(i.value, min); }
p.addEventListener('pointerup', dec(i), true);
n.addEventListener('pointerup', inc(i), true);
i.addEventListener('change', chk, false);
}
while (l--) h(els[l]);
}
reg(document.querySelectorAll('.single-inc-dec'));
}();
I know that this code will still produce a callback-function for each instance of the listeners, just wondering about the mechanics behind this.
Any pointers to what keywords I should be lookign for to read up on this are also welcomed. :)
Please don't crusify me over this code. It's not mine. I was just told "The buttons are slow on the iPhone. Fix that", while doing that I found this gem.

need help calling text_a(), that was initially declared in foo(), inside the called function foo()

I am creating code similar to this:
function foo(type,callback) {
if(type === "a") {
function text_a() {
return "a";
}
}else if(type === "b") {
function text_b() {
return "b";
}
}else if(type === "c") {
function text_c() {
return "c";
}
}
if(typeof callback === "function") callback();
}
foo("a",function() {
console.log(text_a());
});
I want the function text_a() inside foo() to only be available when the type is equal to the relevant type and is called inside the foo() function. However this does not work. I keep getting an error message saying that text_a() is not defined, which makes no sense because when the foo function is called it should also declare the text_a function if the type is "a".
Just save a reference to the function and pass it to the callback..
eg.
function foo(type,callback) {
var fn;
if(type === "a") {
fn = function text_a() {
return "a";
}
}else if(type === "b") {
fn = function text_b() {
return "b";
}
}else if(type === "c") {
fn = function text_c() {
return "c";
}
}
if(typeof callback === "function") callback(fn);
}
foo("a",function(fn) {
console.log(fn());
});
foo("b",function(fn) {
console.log(fn());
});

return from function in another function

I have this case:
function f1(a) {
a = f2(a);
// do some other stuff
console.log("I don't want the function f1 to log this.")
}
function f2(a) {
if (a == null) {
console.log("enters here")
return;
}
return a;
}
f1(null)
if a is null, I don't want f1 to continue with the console.log(). What can I change to obtain this behavior? (I know I can do this with some booleans but I was wondering if there is another way to solve this)
You could store the last value of a and exit if temp is null.
function f1(a) {
let temp = a;
a = f2(a);
// do some other stuff
if (temp === null) return;
console.log("I don't want the function f1 to log this.");
}
function f2(a) {
if (a == null) {
console.log("enters here");
return;
}
return a;
}
f1(null);
if a is null, I don't want f1 to continue with the console.log()
In that case you have to test the value of a within the f1 function:
function f1(a) {
a = f2(a);
// do some other stuff
if (a == null) return;
console.log("I don't want the function f1 to log this.")
}
function f2(a) {
if (a == null) {
console.log("enters here")
return;
}
return a;
}
f1(null)
just return false
function f1(a) {
a = f2(a);
// do some other stuff
if (!a) return
console.log("I don't want the function f1 to log this.")
}
function f2(a) {
if (a == null) {
console.log("enters here")
return false;
}
return a;
}
f1(null)

I have similar code to this and im wondering if there is way to make it short

I am wondering how i can make them short in my js file. i have so many code similar to this. I have repeated this if function again and again also have to repeat else function as well.The only thing is changed is Mission() Doclick() and Yesdo(). If there is way to make it short let me know thanks.
function Buy() {
if (uida == '234' || uidb == '4563') {
Mission();
} else {
stop();
};
};
function Start() {
if (uida == '234' || uidb == '4563') {
Doclick();
} else {
stop();
};
};
function ReBuy() {
if (uida == '234' || uidb == '4563') {
Yesdo();
} else {
stop();
};
};
Use function pointers!
function Uida(fn) {
if (uida == '234' || uidb == '4563') {
fn();
} else {
stop();
};
}
function Buy() {
Uida(Mission);
};
function Start() {
Uida(Doclick);
};
function ReBuy() {
Uida(Yesdo);
}
Of course, you'll want to rename the Uida function to something more descriptive :)
You could look to make them all call one similar function and pass a uida paremeter, something like this:
// You could change the following 3 functions to have ternary statements
// eg: if ( uidaCheck() ) ? Function() : stop();
//
function Buy() {
if ( uidaCheck() ) {
Mission();
} else {
stop();
}
}
function Start() {
if ( uidaCheck() ) {
Doclick();
} else {
stop();
}
}
function ReBuy() {
if ( uidaCheck() ) {
Yesdo();
} else {
stop();
}
}
function uidaCheck() {
// uida assumed to be globally accessible var
//
if ( ( uida == '234' ) || ( uida == '4563' ) ) {
return true;
} else {
return false;
}
}
That's the theory anyway, gimme a sec and I'll see if I can tidy it up a bit. (ternary)
Here's a quick jsfiddle.

Categories

Resources