JavaScript equation returning stinky NaN value - javascript

var shaftDepth = 1;
var nextShaftDepth = ((maxThreshold - shaftDepth) / 20) + shaftDepth;
var maxThreshold = 10;
The equation for nextShaftDepth spits out an NaN value.
For context, I'm planning to have an "upgrade" in my game which decreases the distance of "shaftDepth" to "maxThreshold" by 5%. To do this, shaftDepth = nextShaftDepth after the formula is done.
"nextShaftDepth" is expected to be equal to 1.45, but instead it just returns an NaN value. Am I doing approaching this wrong or is my syntax incorrect? Thanks.

var is hoisted, it will be undefined as you're trying to access it before the declaration , change your code to
var shaftDepth = 1;
var maxThreshold = 10;
var nextShaftDepth = ((maxThreshold - shaftDepth) / 20) + shaftDepth;

Related

why isn't this js code for finding derivative working?

When ran it gives an alert box with undefined written, Can you help me debug this code? I am unable to find the correct error you can check it and please help me. It must give the derivative at point x=10 for f(x)=x^2+1 by using smaller and smaller h till desired accuracy is reached.
function f(x) {
return x * x + 1;
}
var iter = [];
var h = 0;
var ddx = 0;
iter[0] = ((f(10 + h) - f(10)) / h);
function d_dx(p) {
for (i = 1; i < 20; i++) {
iter[i] = ((f(p + h) - f(p)) / h);
if (iter[i] = iter[i - 1]) {
break;
var ddx = iter[i];
} else {
h = h / 2;
}
}
return ddx;
}
console.log(d_dx(10));
Your iter array will be NaN. h will be always 0 and you divide by 0.
if (iter[i] = iter[i - 1]) statement is wrong, you should use === to compare values. You cannot use break in if if you want to loop this code multiple times. There are many mistakes in your code.
var ddx is not reachable after break. That's why it is returning undefined. And one more thing, you are using assignment instead of conditional expression.(correct comparison is - if (iter[i] == iter[i - 1])) )
You have used var ddx out of scope while you are returning the ddx.

returning NaN and Undefined in JavaScript

var currDice, totDice, dice, complete;
function moveIt(){
dice = Math.floor(Math.random()*6) + 1,
currDice = 40,
totDice = totDice+complete,
complete = dice * currDice
return totDice;
};
The function moveIt returns NaN.
It should return multiple of 40 till six randomly and keep the previous value.
If I remove it returns Undefined.
I know it is a scope problem. Please help.
You are using complete before initialising it! you habe to swap your lines of code:
function moveIt(beforeTotal) {
var dice = Math.floor(Math.random()*6) + 1;
var currDice = 40;
var complete = dice * currDice;
var totDice = (beforeTotal || 0)+complete;
return totDice;
};
var total = moveIt();
console.log(total);
total = moveIt(total);
console.log(total);
I try to point out how this method work.
You can call this function without an inital value. Then (beforeTotal || 0) is (undefined || 0) and will evaluate to 0, that's JS logic, and you get the result for one dice.
If you pass a value to this function it will be used to add complete to it. By passing 1000 and complete gets 120, you get 1120 out of it.
All other variables are only available in this function.
Initialy totDIce is undefined and when you add undefined to something, you get the value casted to NaN
function moveIt(){
//memoizing the mutable value as key of the function itself
moveIt.totDice = moveIt.totDice || 0;
// you might wanna wrap it with parseInt()/Math.floor()/Math.ceil()
var dice = Math.floor(Math.random()*6) + 1;
var currDice = 40;
var complete = dice * currDice;
var totDice = totDice+complete;
return moveIt.totDice ;
};
var totDice; will have undefined and that's why you get NaN
Assign totDice = 0 on the first line...
Also move complete = dice * currDice line above because complete has no value yet
var currDice, totDice = 0, dice, complete;
function moveIt(){
dice = Math.floor(Math.random()*6) + 1,
currDice = 40,
complete = dice * currDice,
totDice = totDice+complete
return totDice;
};
you can use the browser's integrated console.
In Chrome: Tools > Javascript Console. Or CTRL + SHIFT + J. There you can console.log from your code and watch it there, or you can use the Sources tab (at the top of the panel). Navigate to the file, click on it and you can put a breakpoint in the line you want by ckicking the line number.
In Firefox: Tools > development > Web console. Or CTRL + SHIFT + K. Yu can debug in a similar fashion like the aforementioned.
You can also use tools like Firebug. See https://getfirebug.com/wiki/index.php/Script_Debugging

Easy- Function arguments

I'm currently struggling with getting the below calcRatio function calculate properly. This is probably basic maths!
The below function works as expected:
function calcRatio(){
var r = frontRing.value/backCog.value;
return r;
}
e.g. frontRing = 52, backCog = 11 r=4.7272....
The below gives me the wrong result:
function calcRatio(){
var r = frontRing.value/(backCog.value + 5);
return r;
}
e.g. frontRing = 52, backCog = 11 r=0.4521.
I ultimately want the 5 to be swapped with an argument.
I am also unable to set the frontRing and backCog variable as .value's without doing it within the function. Could this be causing the issue?
Codepen link
When you expect the extracted value to be a string and have additional computations, it is preferred you use either
parseInt( value , 10) - for integers
parseFloat( value ) - for decimals
In the use case var r = frontRing.value/(backCog.value + 5);
backCog.value is a string since it it a value of input element. When you use + to add a number, it performs a concatenation instead of addition.
var backCogValue = backCog.value; // "11";
"11" + 5 --> 115 and not 16 as you expected.
So the right way to write this piece of code is to use either of the above methods before you want to add a number.
var frontRingValue = parseFloat(frontRing.value);
var backCogValue = parseFloat(backCog.value);
var r = (frontRingValue/ (backCogValue + 5)).toFixed(4);
toFixed is use to format into the number of decimal points that you are expecting.
If 5 is the argument that is passed to the function, then your code will look like
function calcRatio(param) {
var frontRingValue = parseFloat(frontRing.value);
var backCogValue = parseFloat(backCog.value);
var paramValue = parseFloat(paramValue);
var r = (frontRingValue/ (backCogValue + paramValue)).toFixed(4);
}

Function Variable's Value Become Undefined After It Is Returned

I wrote a function to find number in 9, 99, 999, 9999... in which the sum of the digit factorials (9! + 9! for 99) of the number is less than the number itself:
function findLimit(starting_limit){
var starting_limit_string = starting_limit.toString();
var limit_factorial = factorial(9) * starting_limit_string.length;
if(limit_factorial > starting_limit){
var new_starting_limit = (starting_limit * 10) + 9;
findLimit(new_starting_limit);
} else {
return starting_limit;
}
}
var final_limit = findLimit(9);
However, final_limit turns out to be undefined. This is despite the fact that, when I set a break point at "return starting_limit", starting_limit is clearly defined as 9999999.
So what's going on here? Why would a defined value change to undefined when returned by my function?
You forgot the return on this line:
findLimit(new_starting_limit);

Get Values from one google sheet enter it onto another sheet with a 4 loop

I have to spreadsheets. I want the program to look at Row A on spreadsheet Ind and see if it is a 1 or 0. if it is a one on the active sheet "return" I want it to grab the date from Row D in spreadsheet "Ind" and post it onto Spreadhseet "return". I can't figure this out and I have it working on VBA in excel.
Any help would be greatly appreciated.
function myFunction() {
X = 5;
Y = 2;
Z = 1;
Count = 4560;
var ss = SpreadsheetApp.getActiveSpreadsheet();
var source_sheet = ss.getSheetByName("Ind");
var target_sheet = ss.getSheetByName("Returns");
while (Z < Count){
if (source_sheet.getRange("A" & X) = 1) {
var buydate = source_sheeet.getRange("D" & X).getValues()
target_sheet.getRange("A" & Y) = buydate
target_sheet.getRange("B" & Y) = "Buy"
Y = Y + 1
} else if (source_sheeet.Range("C" & X) = 2) {
var selldate = source_sheeet.Range("D" & X).getvalues()
target_sheet.getRange("A" & Y) = selldate
target_sheet.getRange("B" & Y) = "Sell"
Y = Y + 1
}
X = X + 1
Z = Z + 1
}}
This line:
if (source_sheet.getRange("A" & X) = 1) {
Is using an ampersand, and it should be a plus sign. To concatenate strings in JavaScript, use a plus sign.
Also, source_sheet.getRange() will return a range, not a value, so it's never going to equal 1. You would need to use something like the following:
if (source_sheet.getRange("A" + X.toString()).getValue() === 1) {
And use triple equal signs for an equality check. JavaScript is constantly attempting to coerce variables into the type that seems correct. So, it might convert the number in the variable "X" to a string, but you can also use the toString() method.
getValues() returns a two-dimensional array. Each inner array represent a row. Each element in the inner array represents a cell in a row.
If you only want to get one value, use getValue() (no "s" on the end) instead of getValues().
var buydate = source_sheet.getRange("D" + X.toString()).getValue();
You are trying to set the value by using an equal sign. That won't work. You need to use the setValue() or setValues() method.
target_sheet.getRange("A" + Y.toString()).setValue(buydate);
By not using the var key word in your assignments, the variables automatically become "global" variables.
X = 5;
Y = 2;
Z = 1;
There's no need to make them global variables in this case, I don't think.
var X = 5,
Y = 2,
Z = 1;
You can declare multiple variables all at the same time.

Categories