passing variables from one function to the other in Javascript - javascript

I have a JavaScript program with 3 functions. The first 2 functions both have the variable values inside and I want to access those variables in the third function but i get an error which says the variables are undefined.
I tried setting the variables globally outside the function and then accessing them but been having the same errors.
var result;
var result2;
function getOpens(){
result = 10;
}
function getClicks(){
result2 = 6
}
function getTotal(){
if(result >= 10 && result2 < 1)
{
//DO SOMETHING
}
}
getOpens();
getClicks();
getTotal();
Im not sure if this is the correct way for accessing variables from other functions. I tried setting the globally but still no luck and the getTotal function is not able to get access to variables result and result2.

Why not use the return values from the function in your third function? It works without global variables.
function getOpens(){
return 10;
}
function getClicks(){
return 6;
}
function getTotal() {
if(getOpens() >= 10 && getClicks() < 1) {
//DO SOMETHING
}
}

few options
Option 1 - call functions in getTotal()
function getOpens(){
return 10;
}
function getClicks(){
return 6;
}
function getTotal(){
var result = getOpens();
var result2 = getClicks();
if(result >= 10 && result2 < 1)
{
//DO SOMETHING
}
}
Option 2 - pass params with function getTotal()
function getTotal(opens, myClicks){
if(opens >= 10 && myClicks< 1)
{
//DO SOMETHING
}
}

How about this :
var result;
var result2;
function getOpens(){
return 10;
}
function getClicks(){
return 6;
}
function getTotal(){
if(result >= 10 && result2 < 1)
{
console.log("DO SOMETHING");
} else {
console.log("DO SOMETHING ELSE");
}
}
result = getOpens();
result2 = getClicks();
getTotal();

Related

Returning Function Javascript

I'm new to Javascript and I'm trying to write a program that will use a variable to call a function, I defined the variable var X; as a global variable and initialized it on startGame() function. Problem is if I'm running startGame() once, then calling X(); as a function works fine but say I put it in a loop, it runs on first iteration and when it returns, it says Uncaught TypeError: X is not a function. Being new to Javascript I'm confused and I need help on how using variable as function works.
var X,
i=0,
lastmove = 100; //Randomly initialize function
function A(){
console.log('A');
}
function B(){
console.log('B');
}
function C(){
console.log('C');
}
function pickFunc(){
var temp = Math.floor(Math.random() * 3) + 1;
if(temp==lastmove)
temp = pickFunc()
else
lastStr = temp;
if(temp == 1)
return A();
else if(temp == 2)
return B();
else
return C();
}
function startGame(){
X = pickFunc();
for(i; i<10; i++)
X()
}
When you do X = pickFunc(); at the end, you're assigning the RESULT of pickFunc() to X.
It seems you intend to alias the function so you can call X() in place of pickFunc(). To do this with minimal changes to your code you would change that line to:
X = pickFunc;
This will make it so overtime you call X(), it reevaluates pickFunc().
Currently you are returning the result of calling the functions A, B and C inside of pickFunc when you need to be returning a reference to them. Try the following code:
function pickFunc(){
var temp = Math.floor(Math.random() * 3) + 1;
if(temp==lastmove)
temp = pickFunc()
else
lastStr = temp;
if(temp == 1)
return A;
else if(temp == 2)
return B;
else
return C;
}
var i=0;
var lastmove = 100; //Randomly initialize function
function A(){
console.log('A');
}
function B(){
console.log('B');
}
function C(){
console.log('C');
}
var X = function pickFunc(){
var temp = Math.floor(Math.random() * 3) + 1;
if(temp==lastmove)
temp = pickFunc()
else
lastStr = temp;
if(temp == 1)
return A();
else if(temp == 2)
return B();
else
return C();
}
function startGame(){
for(i; i<10; i++)
X()
}

closure in javascript with multiple empty calls to sum function

I faced this question in one interview. I did not get how to solve this.
Question: Write a sum function which will add 2 numbers, but numbers can be passed to a function in following ways:
sum(3)(4) // answer should be 7
sum(3)()(4)//answer should be 7
sum(3)()()()()(4) //answer should b 7
I can solve first function using closure, in fact for the second function also I can check the arguments and if arguments length is zero I can again make a call to sum to except next parameter.
But how to make it generic ? Means even your first parameter and last parameter has 'N' number of calls & those can be empty or parameterized, it should return sum.
Recorded a video how to solve it:
https://youtu.be/7hnYMIOVEg0
Text answer:
function sum(numberOne) {
return function innerSum(numberTwo) {
if (typeof(numberTwo) === 'number') {
return numberOne + numberTwo;
}
return innerSum;
}
}
Output:
sum(3)(4); => 7
sum(5)()()(10); => 15
Basically, you need to return inner function (innerSum) up until you receive a value - then you return number.
You could also choose another name - like _sum(), or addToFirstNumber() for your method.
You can always return a function from within a function:
let a;
function sum(value) {
if (typeof value !== "number") {
return sum;
}
if (typeof a !== "number") {
a = value;
return sum;
}
let result = a + value;
a = null;
return result;
}
see https://jsfiddle.net/d9tLh11k/1/
function sum(num1) {
return function sum2(num2) {
if(num2 === undefined) {
return sum2;
}
return num1 + num2;
}
}
console.log(sum(4)()()()(3)); // -> 7
Or in ES6:
const add = num1 => num2 => num2 === undefined ? add(num1) : num1 + num2;
console.log(add(4)()()()()()(3)); // -> 7
function add (n) {
var func = function (x) {
if(typeof x==="undefined"){
x=0;
}
return add (n + x);
};
func.valueOf = func.toString = function () {
return n;
};
return func;
}
console.log(+add(1)(2)(3)()()(6));
I have already given answer of this question Here
but according to your question I have modified that
function add (n) {
var func = function (x) {
if(typeof x==="undefined"){
x=0;
}
return add (n + x);
};
func.valueOf = func.toString = function () {
return n;
};
return func;
}
console.log(+add(1)(2)(3)()()(6));
Run code like that
console.log(+add(1)(2)(3)()()(6));
This should do it
function sum(num1) {
if (arguments.length === 0){
return sum;
}
return function innerSum(num2) {
if (arguments.length > 0){
return num1 + num2;
}else{
return innerSum;
}
}
}
You can do this in a number of ways, but mostly you'll want named recursion. That is, you can have something like:
sum = start => (...args) => args.length? args[0] + start : sum(start)
but it might look cleaner to write this as:
function sum(start) {
function out(...args) {
return args.length? start + args[0] : out
}
return out;
}

Trying to understand why function is returning undefined in recursive function

I am having trouble understanding whats happening in this recursive function.
Why does y === undefined??
function f(num){
if(num !== 10){
f(num + 1);
} else {
return num;
}
}
var y = f(0);
console.log(y);
If I log "num" right before its returned the value is 10.
Here is a jsfiddle:
https://jsfiddle.net/
if num is not 10, you just call f again. The value returned from f is not allocated anywhere. You should return that value.
function f(num){
if(num !== 10){
return f(num + 1); //you were returning nothing except when num reached 10
} else {
return num;
}
}
var y = f(0);
console.log(y);
You should rather return f(num + 1) inside if block.
Without which it returns nothing except when "num" reaches 10.
function f(num){
if(num !== 10){
return f(num + 1);
} else {
return num;
}
}
var y = f(0);
console.log(y);
// 10

JavaScript function as argument of function on a variable?

Here's what I have:
function verificarNumero(test, num) {
return (test(num));
};
var resultadoTesteMultiplos = verificarNumero(function (num){return (num % 10 == 0);}, num1);
This function is supposed to find out if a number is a multiple of 10.
I know there are simpler ways to do it, but I really want to make this work.
I want to be able to do something like console.log(resultadoTesteMultiplos(10)); but the console returns "resultadoTesteMultiplos is not a function", and "num1 is undefined."
What am I doing wrong?
Sounds like you meant to curry but only got half way:
function verificarNumero(test) {
return function(num) {
return test(num);
};
}
var resultadoTesteMultiplos = verificarNumero(function(num) {
return (num % 10 == 0);
});
console.log(resultadoTesteMultiplos(10));
If you define num1 variable your code should work and the type of the resultadoTesteMultiplos is boolean. See the working snippet below please:
var num1 = 10;
function verificarNumero(test, num) {
return (test(num));
};
var resultadoTesteMultiplos = verificarNumero(function(num) {
return (num % 10 == 0);
}, num1);
console.log(typeof resultadoTesteMultiplos);
console.log(resultadoTesteMultiplos);
Return a function from verificarNumero, not the result of the function.
function verificarNumero (cb) {
return function (num) {
return cb.apply(this, [num]);
}
};
resultadoTesteMultiplos = verificarNumero(function (num) {
return (num % 10 == 0);
};
console.log(resultadoTesteMultiplos(10));

trying to understand if/else loops combined with functions

so I am trying to create a function with two parameters. This function will be passed with two numbers as arguments. calculate the sum of the parameters. If the sum is less than or equal to 25, the function should return true. If not it should return false.
I know I must use a if and else loop to check the parameters (or a ternary which we have not covered yet.) This is what I have gotten so far. Please tell me if I am on the right track or completely wrong.
function sum(augment1,augment2) {
var num= augment1 + augment2;
return num;
}
var a=sum(10,30)
console.log(a);
if (num > 25) {
return true
}
else {
return false;
}
There's no reason to use an if-else statement - the <= operator returns a boolean result, so you could just return it:
function isSumEqualOrLessThan25(augment1, augment2) {
var sum = augment1 + augment2;
return sum <= 25;
}
Your conditions should be inside your function right? So if the sum is less than or equal to 25 return true else return false. Can you try following?
function sum(augment1, augment2) {
var num = augment1 + augment2;
if (num <= 25) {
return true
} else {
return false;
}
}
var a = sum(10, 30)
console.log(a); // should be false

Categories

Resources