Javascript toFixed is not a function - javascript

Hi the problem is following:
I define:
var total = 0;
function add(a){
total+=a;
var float_num = total.toFixed(2);
return float_num;
}
The JS give me an error said Uncaught TypeError total.toFixed is not a function
I don't get it. the total I declare is not a number type?

I think the easiest way to prevent the error from happening is to always parse the parameter as number:
var total = 0;
function add(a){
total+=a;
var float_num = Number(total).toFixed(2);
return float_num;
}

Check if any of the code above has redefined the toFixed on the Number prototype, For instance
Number.prototype.toFixed = {};
var total = 0;
function add(a) {
total += a;
var float_num = total.toFixed(2);
return float_num;
}
add(2)
is one way to replicate the error.

It depends on the value of a. If a happens to be a "string" then you're trying to do:
"0string".toFixed(2)
which should throw an error.

This works:
var total = 1.0;
function add(a) {
total += a;
var float_num = total.toFixed(2);
return float_num;
}
console.log(add(4.89));
This code is a bit unsafe since you assume that a is a float and not a string.
https://jsfiddle.net/6to7kbbm/
This will throw the exception:
var total = 1.0;
function add(a) {
total += a;
var float_num = total.toFixed(2);
return float_num;
}
console.log(add("4.89"));

Okay, so I've just run your code a few times, and I can confirm that your .toFixed() line is working just fine.
However, it only works if you pass a numeric value into the function. If the a parameter is not numeric, then toFixed() will fail as described.
So the problem isn't with the function, but how you're calling it. In your question, you're not showing how you're calling the function, so I can't give you any direct guidance on that, other than to make sure that you're giving it a numeric every time.
Maybe you're passing in a string? That would break things (even if the string does contain a numeric value).
Or maybe it's a null or undefined or NaN due to an error or oversight elsewhere in your system? I can't tell, but in those cases you probably don't want to be calling the add() function at all.

I found the problem. My some other function has a code that xxx.text(total). It actually convert total back to string. That cause the problem.
Thanks for all your help!

Verify if you have any declared function with the same name as the variable you are using. To prevent this you may declare global variables like:
var global_variable = 0;
function myfunction()
{
var variable = 0;
global_variable = variable + 1;
}

Related

It errors when I define variable in function

function addNumbers(x,y) {
sum = x + y;
var sum;
return sum;
}
addNumbers(5,9);
alert(sum);
It says: Uncaught ReferenceError: sum is not defined
When I put "var sum" before the function it works. What is the reason?
sum is only defined within the function. To use the function's return value, you do that directly:
function addNumbers(x,y) {
var sum;
sum = x + y;
return sum;
}
alert(addNumbers(5,9));
or
function addNumbers(x,y) {
var sum;
sum = x + y;
return sum;
}
var outerSum = addNumbers(5,9);
alert(outerSum);
Also note that I moved the var sum; to the top of the function. It doesn't really matter with var (I wrote a blog post about that), but it's better form. (It does matter with let and const, which you should probably be using instead of var.)
A variable only exists inside of it's scope (rule of thumb: starts at the previous { ends at the matching }), which especially makes sense for functions, as the variables inside the function only exist as long as the function gets executed.
function addNumbers(x,y) { // sum can be used from here on
var sum = x + y; // always declare variables where you ise them first, otherwide you get funny behaviour
return sum; // <-
} // you cannot use sum from here on
Now that means that you cannot access sum outside of addNumbers. However as your function returns the value of sum, you can store that in another variable:
var cool = addNumbers(1, 2);
Now you can use that cool variable and eventually log it.

Named vs nameless function for replacing numbers in a string

I am a JavaScript beginner, and one of the problems in the latest programming assignment I got is to replace all numbers in a string with sum of their digits, so, for example, for an input like this:
"m123a"
the output should be
"m6a"
I actually managed to write a working code, but I do not understand why it works.
This is my HTML:
<html>
<TEXTAREA ID = "text" ROWS = 10 COLS = 30></TEXTAREA>
<br>
<INPUT TYPE = "button" ID = "button" VALUE = "Replace">
<SCRIPT src = "zaz3.js" type="text/javascript"></SCRIPT>
</html>
This is my working JavaScript code:
function ReplaceNumbers()
{
var s = document.getElementById("text").value;
document.getElementById("text").value = s.replace(/\d+/g, function DigitSum(x)
{
var sum = 0;
while (x > 0)
{
sum += x%10;
x = x/10;
x = Math.floor(x);
}
return sum;
});
}
var button = document.getElementById( "button");
button.addEventListener("click" , ReplaceNumbers);
And this is the first version of my JavaScript code which does not work:
function DigitSum(x)
{
var sum = 0;
while (x > 0)
{
sum += x%10;
x = x/10;
x = Math.floor(x);
}
return sum;
}
function ReplaceNumbers()
{
var s = document.getElementById("text").value;
document.getElementById("text").value = s.replace(/\d+/g, DigitSum(x));
}
var button = document.getElementById( "button");
button.addEventListener("click" , ReplaceNumbers);
The only difference here is that function DigitSum is implemented separately in the second version.
When debugging the second code, the error returned is "ReferenceError: x is not defined". I do not understand how the parameter x in the first code is even interpreted since it's not mentioned anywhere else in the code.
So, my question is, what is the difference between implementing the function DigitSum separately vs implementing it where it is needed, and what actually is x in the first version, and what is it in the second version.
because in the second one you are calling the function and whatever it returns is being assigned to the replace. In your case you should have an error that says "x is undefined".
document.getElementById("text").value = s.replace(/\d+/g, DigitSum(x));
It should just be
document.getElementById("text").value = s.replace(/\d+/g, DigitSum);
You are using a callback
document.getElementById("text").value = s.replace(/\d+/g, DigitSum(x));
// ^^^^^^^^^^^
but instead to use only the function reference, you insert a call of the function with x, which does not exist.
Use this for a valid reference of a callback.
document.getElementById("text").value = s.replace(/\d+/g, DigitSum);
// ^^^^^^^^ without parenthesis
A calback is a function which is used for repeating calls with a fixed parameter list. The surrounding function defines the parameters and in this case you may have a look to String#replace.

Creating a new function that takes default arguments for another function (Javascript)

I am currently trying to create a defaultArguments function that takes in a function and some parameters that are set as default values. The steps I am thinking about taking to solve this particular problem is to:
Parse through the function in order to obtain what its arguments which could be anything.
Go through each argument that was extracted and replace arguments that have input parameters to its respective value.
Now, what I was thinking about doing next was to add additional default arguments into the input 'func'. I tried to:
Look up how to input a string as an argument into an existing function. However, the function then just reads the argument string as just a string.
Use the JavaScript .apply method. However, I won't always have all input values.
Here is the code I wrote so far.
function defaultArguments(func, params) {
var reg = /\(([\s\S]*?)\)/;
var extractVar = reg.exec(func);
if (extractVar) {
var arguments = extractVar[1].split(',');
}
for (i = 0; i < arguments.length; i++) {
if (params[arguments[i]]) {
arguments[i] = params[arguments[i]];
}
}
}
So for example, if I have a function
function add(a,b) { return a+b; };
I would use the defaultArguments function as such
var add_ = defaultArguments(add,{b:9});
console.log(add_(10) === 19); // b is defaulted to 9
console.log(add_(10,7) === 17); // b is given so use given value
console.log(add_()); // NaN
I would love some hints as to how to solve this problem and a different approach if I am approaching this problem incorrectly. I appreciate your time for reading this and I hope to see your response!
UPDATE:
So I was able to come up with a rough solution for this question. I was wondering if I approached the problem correctly and if there's any improvements do to my code. After researching a lot, I know that I shouldn't use eval(), but I don't know how else to tackle the problem. I am open to suggestions. Thanks in advance!
function defaultArguments(func, params) {
var stringed = func.toString();
var inputs = stringed.match(/\(.+\)/)[0].replace("(", "").replace(")", "").split(",")
for (i = 0; i < inputs.length; i++) {
inputs[i] = ""+inputs[i]+" = "+inputs[i]+" || "+params[inputs[i]]+";"
}
for (i = 0; i < inputs.length; i ++) {
stringed = stringed.replace("{", "{ "+inputs[i]+"")
}
var newFunc = "var restoreFunc = " + stringed;
eval(newFunc);
return restoreFunc;
}

Function updating a number var through a parameter doesn't correctly update number var

So I have this bit of code that goes like this
var number = 0;
function addnumber(numbertype){
numbertype = numbertype +50;
}
function numberupdate() {
document.getElementById('adiv').innerHTML = number;
}
Somewhere, I call
onClick="addnumber(number);"
Now, if I check the value of number with an alert, it displays correctly. But the number only goes to 50 once and doesn't climb the more I click, and even though an alert called within the addnumber() function will caluclate number correctly, it will not update the value of number when checked outside of that function.
I'm sure I'm missing something simple.
In your addnumber function, the variable that you're passing in is getting increased by 50, not (I'm assuming) number.
You could change it to:
function addnumber(){
number += 50;
}
You are confused with number and numbertype variable.
var number = 0;
function addnumber(numbertype){
number = number + numbertype +50;
}
function numberupdate() {
document.getElementById('adiv').innerHTML = number;
}
Arguments to a javascript function are either passed 'by value' in case of primitives, or 'by reference' in case of objects. Your var 'number' is a primitive. In this case, a copy is made of the primitive value, and passed as the argument. Addnumber therefore adds 50 to a copy of number, not to number itself.
When you want to change the value of a variable in this way, use an object, then it will work as you initially expected:
var number={value:0};
function addnumber(numbertype){
numbertype.value = numbertype.value +50;
}

Uniquely identify a function in JavaScript

Is there any way I can uniquely identify a function without giving it an expando property? I've been just using "toString()" to identify the function, but when two functions are identical, they conflict.
The following sample code reproduces the problem. In my actual code, the key for the associative array "myfunctions" is built from other parameters as well. I don't want to generate a meaningless key since the developers using this code need to be able to rebuild this key at any time without holding a reference to some random key.
var myfunctions = {};
(function(){
var num = 1;
function somefunc() {
alert(num);
}
myfunctions[somefunc.toString()] = somefunc;
})();
(function(){
var num = 2;
function somefunc() {
alert(num);
}
myfunctions[somefunc.toString()] = somefunc;
})();
for (var f in myfunctions) {
myfunctions[f]();
}
When this code is run, only one alert fires, and it always has the message "2".
The answer is no, there isn't any unique string value you can draw from a function with which you can associate that specific instance.
Why do you want to avoid using an expando?
I suspect that whatever you put in a property name (not a hash key, a property name) will be converted to string anyway.
This does not work either
(function(){
var num = 1;
function somefunc() {
alert(num);
}
somefunc.blah = 1;
myfunctions[somefunc] = somefunc;
})();
(function(){
var num = 2;
function somefunc() {
alert(num);
}
somefunc.bloh = 1;
myfunctions[somefunc] = somefunc;
})();
I just did some reading, and it seems like a property name can only be a string.

Categories