Returning Function Javascript - 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()
}

Related

Write code that uses an immediately-invoked function expression (IIFE) to create the fibonacci function where indicated

Currently, I am trying to write javascript to do a fibonacci sequence. I got the math part but we have to have an array named fibonacciResults and I am unsure on how to use an array named fibonacciResults and initialize it so that fibonacci(0) will be 0 and fibonacci(1) will be 1. Also, If the result (fibonacci(n)) has never been calculated before, calculate the new result recursively and save it in the fibonacciResults array.
document.querySelector('#calculate-fibonacci').addEventListener('click', function () {
var fibonacci; // Do not declare more variables here.
// WRITE YOUR fibonacci FUNCTION HERE
fibonacci = function fibonacci(n) {
fibonacciResults = [];
n = Math.round(n);
if (Number.isFinite(n) && n >= 0) {
if (n < 2) {
return n;
}
return fibonacci(n - 2) + fibonacci(n - 1);
}
return 0;
};
(function () {
var whichFibonacciNumber;
// Get the user's number.
whichFibonacciNumber = parseInt(document.querySelector('#fibonacci-input').value, 10);
// Use the fibonacci function to calculate the output.
document.querySelector('#which-fibonacci-number').textContent = whichFibonacciNumber;
document.querySelector('#fibonacci-number').textContent = fibonacci(whichFibonacciNumber);
}());
}, false);
fibonacci = (function () {
var cache = {};
return function (n) {
var cached = cache[n];
if (cached) return cached;
if (n <= 1) return n;
console.log(n);
return (cache[n] = fibonacci(n - 2) + fibonacci(n - 1));
};
}());

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

passing variables from one function to the other in 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();

Recursive function or loop in javascript?

I am trying to write a recursive function, but I am completely lost as to how to implement it. I currently have the following:
function change(p){
// code for function
}
var c1 = change(start);
var c2 = change(c1);
var c3 = change(c2);
// etc. etc.
Is there any way to do this with a while loop? For example:
while(currentResultofFunction != goal)
nestedly loop through as before until reaches true
function change(p) {
if (p != 1) { // your condition
change(p);
} else return p;
}
What about:
var val = start;
while(val) //or while val != goal
val = change(val);
What you are doing, is not recursive. You maybe mean iterative.
You can loop through the variables in this way:
var n = 2;
for (var i = 1; i <= n; i++) {
if (i == 1) window['c1'] = change(start);
else window['c' + i] = change(window['c' + (i - 1)]);
}

How to change a variable to something if it's undefined?

I don't have my script completed yet or anything so I can't post the code. Basically I need a variable to change and keep going through a function increasing by one until it reaches its destination. Something like:
function one(a) {
var x = a;
var max = 3;
if (a < 3) {
// some code
two(x);
} else {
// function will end here quitting the whole thing and possibly other code
}
}
function two(x) {
var change = x+1;
one(change);
}
It all works how I need it but when I first enter function one how would I make it so when x = a doesn't have a value that it will by default be 0?
something like...
function one(a) {
var x = a;
var max = 3;
if (x = undefined) {
x = 0;
} else {
if (x < 3) {
// some code
two(x);
} else {
// function will end here quitting the whole thing and possibly other code
}
}
}
function two(x) {
var change = x+1;
one(change);
}
Any ideas?
You could do this:
function one(a) {
var x = a || 0;
if (x < 3) {
//debugger;
two(x);
} else {
// function will end here quitting the whole thing and possibly other code
alert('Done');
}
}
function two(x) {
x++;
one(x);
}
one();
FIDDLE
var x = a || 0 means x is a if a can be asserted as true or 0.
x++ means x = x + 1
You can check to see if the variable is defined and send it in the functions argument by using the short hand conditional.
typeof(a)=="undefined" ? 0 : a;
You can change your code to:
function one(a) {
var x = (typeof(a)=="undefined" ? 0 : a);
var max = 3;
if (x < 3) {
// some code
two(x);
} else {
// function will end here quitting the whole thing and possibly other code
return;
}
}
Fiddle: http://jsfiddle.net/gBBL2/
var x = (typeof a === 'undefined') ? 0 : a;
If a is undefined, use 0. Otherwise use a as the value of x.

Categories

Resources