Code only works when not wrapped in a function - javascript

Really not sure what's going on here as am new to JavaScript, but actually cannot figure it out, even after reading other posts like this one: Simple function returning 'undefined' value. For some reason, when my code is placed inside a function, it returns 'undefined' instead of true or false.
If I use the code without a function and define var a on the first line, it works OK:
var a = "wjebh ghbui ayub";
var b = (a.split(' ').join('')).split('a'); // creates array
var trueOrFalse = b.map(function(c, i){ // puts into array true/false for each index
if (c[2] == 'b') {
console.log('value: ' + c[2] + ' is b; true');
return true;
} else {
console.log('false');
return false;
}
});
var answer = function(el) {
// checks whether any element is true
return el === true;
};
trueOrFalse.some(answer); // return true/false
But the moment I add it inside a function, it doesn't work.
function bThreeAfterA(a) {
var b = (a.split(' ').join('')).split('a'); // creates array
var trueOrFalse = b.map(function(c, i){ // puts into array true/false for each index
if (c[2] == 'b') {
console.log('value: ' + c[2] + ' is b; true');
return true;
} else {
console.log('false');
return false;
}
});
var answer = function(el) {
// checks whether any element is true
return el === true;
};
trueOrFalse.some(answer); // return true/false
}
Even if it's put in an IIFE it doesn't work properly:
(function(){
var a = "wjebh ghbui ayub";
var b = (a.split(' ').join('')).split('a'); // creates array
var trueOrFalse = b.map(function(c, i){ // puts into array true/false for each index
if (c[2] == 'b') {
console.log('value: ' + c[2] + ' is b; true');
return true;
} else {
console.log('false');
return false;
}
});
var answer = function(el) {
// checks whether any element is true
return el === true;
};
trueOrFalse.some(answer); // return true/false
})();
I feel I'm doing something very daft here that most will easily spot. Can someone explain what I'm doing wrong here? Presumably this is some sort of beginner syntax error. Links to any reading resources would be helpful too.

We've all been there.
Give this a run.
function bThreeAfterA(a) {
var b = (a.split(' ').join('')).split('a'); // creates array
var trueOrFalse = b.map(function(c, i){ // puts into array true/false for each index
if (c[2] == 'b') {
console.log('value: ' + c[2] + ' is b; true');
return true;
} else {
console.log('false');
return false;
}
});
var answer = function(el) {
// checks whether any element is true
return el === true;
};
return trueOrFalse.some(answer); //ACTUALLY return true/false
}
console.log("Answer: " + bThreeAfterA("wjebh ghbui ayub")); // Returns true.
When you're operating on variables outside of the block scope, they persist. When they're inside, they vanish.
Hence, it "worked" but it didn't "work" when you have it in a function.

Related

JavaScript If / else statement not return false statement

Function returns true, however if / else statement is logging false result. Any idea where I'm going wrong?
function loginDetails(arrayCheck, value) {
for(i = 0; i < arrayCheck.length; i++){
if(arrayCheck[i] === value){
return true;
}
}
return false;
}
var username = [1,2,3,4,5,6,7,8,9,10];
document.write('Login Details: ', loginDetails(username, 9), '</p>');
if(loginDetails === true) {
document.write('Redirect ....Welcome !!</p>');
} else {
document.write('There seems to be an error please try again !!');
}
loginDetails is a function. You then test to see if it is boolean true. Funnily enough, it never will be!
I presume you actually want to run the function. You will need to cache the result in order not to run it twice:
function loginDetails(arrayCheck, value) {
for(i = 0; i < arrayCheck.length; i++){
if(arrayCheck[i] === value){
return true;
}
}
return false;
}
var username = [1,2,3,4,5,6,7,8,9,10];
var loggedIn = loginDetails(username, 9);
document.write('Login Details: ', loggedIn, '</p>');
if(loggedIn === true) {
document.write('Redirect ....Welcome !!</p>');
} else {
document.write('There seems to be an error please try again !!');
}
What do you mean by if(loginDetails === true) ? This doesn't pass any parameters to loginDetails function.
Instead try if(loginDetails(username, 9) === true). Hope this works. Else store loginDetails(username, 9) in a variable and check whether that variable is true?
loginDetails is a function I suppose you want to check its result to be equal with true.
function loginDetails(arrayCheck, value) {
for(i = 0; i < arrayCheck.length; i++){
if(arrayCheck[i] === value){
return true;
}
}
return false;
}
var username = [1,2,3,4,5,6,7,8,9,10];
var loginDetailsResult = loginDetails(username, 9);
document.write('Login Details: ',loginDetailsResult, '</p>');
if(loginDetailsResult === true) {
document.write('Redirect ....Welcome !!</p>');
} else {
document.write('There seems to be an error please try again !!');
}
You are checking if the reference to the function is equal to true, which will always evaluate to false. A function and a boolean are different types and therefore comparing for strict equality will always return false. I have corrected the code, so that the function is called, and the result of the function is compared, instead of the reference to the function.
function loginDetails(arrayCheck, value) {
for(i = 0; i < arrayCheck.length; i++){
if(arrayCheck[i] === value){
return true;
}
}
return false;
}
var username = [1,2,3,4,5,6,7,8,9,10];
document.write('Login Details: ', loginDetails(username, 9), '</p>');
if(loginDetails(username, 9) === true) {
document.write('Redirect ....Welcome !!</p>');
} else {
document.write('There seems to be an error please try again !!');
}

Return functions recursively to form nested functions - Javascript

I'm trying to build a function in JS that has a return composed of different nested functions based on a parameter passed by the user.
function addA(otherFunction)
{
//gets the result from some base function and modifies it
//e.g. +1
}
function addB(otherFunction)
{
//does the same thing as addA, except different values. Consider it a variation of addA.
//eg. -1
}
function constr(input)
{
//based on the chars in input, we will recursively select a new function to be applied.
//the value of this function should be a function
if (...) return addA(constr(shorterInput))
if (*last char) return addA
if (*last char) return addB
if (...) return addB(constr(shorterInput))
}
So far, my script is recognizing addA and and addB as functions. But when it strings two functions together, for example
addB(addA)
The type becomes undefined. Can anybody let me know why it does not register as a function and/or the proper way to return nested functions. Thanks!
Edit: Here is the real code:
function cons(a,b)
{
return function (selector) {
return selector(a,b);
};
}
function a(list)
{
function aHelper(a,b)
{
return a
}
return list(aHelper);
}
function d(list)
{
function dHelper(a,b)
{
return b
}
return list(dHelper);
}
function abc(input)
{
if (input.length==0 || input==null) return null;
var x=input.charAt(input.length-1);
if (x==='a')
{
if (input.length>1)
{
var z=a(abc(input.substr(0,input.length-1)));
return z;
}
return a;
}
if (x==='d')
{
if (input.length>1)
{
var z=d(abc(input.substr(0,input.length-1)));
return z;
}
return d;
}
}
function show(list) {
var sval;
if (list == null) return '()';
else if (typeof list!='string')
{
sval = '(' + show(a(list)) + ' ' + show(d(list)) + ')';
}
else
{
sval=list;
}
return sval;
}
var func=abc('ad');
var func2=abc('a');
var list=cons('a',cons('b','c'));
console.log(typeof func);
console.log(typeof func2);
console.log(typeof list);
console.log(typeof func2(list));
console.log(typeof func(list));
Your function abc is supposed to return a function that can process lists, like a or d. However, you match that signature only in 2 out of 7 cases:
return a, return d are fine
return null - that's not a callable value
z = d(…); return z does return a list
z = a(…); return a does return an element of the list (of whatever type)
d(abc(…)) and a(abc(…)) use abc as if it would return a list
A correct implementation would look like this:
function abc(directions) {
if (directions.length == 0) {
return function id(list) { return list; }; // a function that does nothing
}
var f = directions[0] == 'a' ? car : cdr; // ignoring other values, you might also throw an error
var processRest = abc(input.slice(1));
return function(list) { // make a function to process a list
var z = f(list); // do the current operation
return processRest(z); // do the rest of operations
};
}
Or even better/shorter with the help of higher-order function composition:
function id(x) { return x; }
function compose(f, g) {
if (f == id) return g;
if (g == id) return f;
return function(x) { return f(g(x)); };
}
function abc(dirs) {
return !dirs.length ? id : compose(abc(dirs.slice(1)), dirs[0]=='a'?car:cdr);
}

Javascript variable interpolation with variable

I've got the following JS
var decSep_1 = true;
function radioButtons(stuff){
if( decSep_1 === true ){
return ','
}
return false
}
alert(radioButtons());
How can I make stuff in radioButtons be a part of the variable I am comparing in the if statements?
For example:
function radioButtons(stuff){
if( stuff + _1 === true ){
return ','
}
return false
}
alert(radioButtons(decSep));
I have discovered that with eval this is possible: http://jsfiddle.net/f2f87ko5/10/
var decSep_1 = true;
function radioButtons(stuff){
if(eval(stuff + "_1") === true){
return 'ytjyjju'
}
return false
}
alert(radioButtons("decSep"));

Closure multiplate call function im javascript

Example i write down
myFunc('asdas')
It's console.log me
'asdas'
Then after i write down
myFunc('as')('ds')('ko')....('other')
function must console.log me
"as ds ko .... other"
I tried do realize this but have many problems with it.
function me (str){
//var temp = str;
return function mes(val) {
val += ' '+ str;
console.log(val);
//return mes;
}
}
How correctly realize this function?
Well, this is a bit funny, but works:
concat = function(x, val) {
val = (val || "") + x;
var p = function(y) { return concat(y, val) };
p.toString = function() { return val };
return p
}
x = concat('a')('b')('c')('d');
document.write(x)
You can generate multiple console logs and chain it like this:
function me(str) {
console.log(str);
return me; // or whatever you called the function
}
me(1)(2)(3);
As far as I'm aware though, there's no way for the function to know when it should be outputting if you're just chaining, though.
The best option I can think of would be this:
function me(str) {
me.str = me.str || ''; // make sure me.str is set
// set me.write if this is the first call to me()
me.write = me.write || function() {
console.log(me.str);
}
me.str += (me.str.length ? ' ' : '') + str; // add a space if needed
return me; // or whatever you called the function
}
me(1)(2)(3).write();

how to return right value in js?

I am trying an angular program but cant return the right value:
function facilityChecked(facility, search) {
var result;
search.filter(
function (v) {
var rtn = (v["facility_Item"]["text"] == facility);
if (rtn) {
var checked = (v.inherit_To_Service === 'true');
result = checked;
}
else {
result = false;
}
}
);
return result;
}
In the code below $scope.parking should be true and $scope.toilet should be false however they both return as false?
parking = facilityChecked('Parking', rtn.Organisation.Facility);
$scope.parking = parking;
toilet = facilityChecked('Toilet', rtn.Organisation.Facility);
$scope.toilet = toilet;
See also this plunkr link
This function is using filter which loops through each item in the array, so it is always setting result to the value of the last item in the array...
so init result to start, and if the value is found, then parse it out of the item
function facilityChecked(facility, search) {
var result = false;
search.filter(
function (v) {
var rtn = (v["facility_Item"]["text"] == facility);
if (rtn) {
var checked = (v.inherit_To_Service === 'true');
result = checked;
}
}
);
return result;
}
Here the problem is with else part in search.filter(); Actually, search.filter() function is executing for all the Json objects.So, it stores and returns the last object value i.e false".
I think, else part is not necessary, because you taking the values from data.json.
function facilityChecked(facility, search) {
var result;
search.filter(
function(v) {
var rtn = (v["facility_Item"]["text"] == facility);
if (rtn) {
var checked = (v.inherit_To_Service === 'true');
result = checked;
}
}
);
return result;
}
Updated Plunker:http://plnkr.co/edit/SETl5Zqapsdp8FmB6t56?p=preview

Categories