Anonymous Function prints as string - javascript

In Javascript, I wanted to calculate total of two variables received from textbox, let us say txtBoxA and txtBoxB. The value gets calculated in an anonymous function and is stored in a variable total. Please take a look at the following code to see how it is calculated:
var total = function () {
var total = parseFloat(txtbox[1].value) + parseFloat(txtbox[2].value);
if (total == NaN) return 0;
else return total;
};
alert(total);
but unfortunately, the anonymous function itself is printed as it is as shown in the image below.

alert(total);
You are just printing the function variable. If you want to execute it, you have to add (), so that it calls.
alert(total());
And that is not an anonymous function. Just a function declaration and assigning to a variable.

Related

How to use Global Variable in a function and then use the output of the function in another function

I want to initialize a global variable and then use it in a function to compute the number of clicks and then use the computed output in another function inside a for loop to set the max limit i.e. for(i=0; i >= count; i++). The issue I'm having here is that since the variable is global, I'm unable to use the computed value of the onClick function in my submitForm() function. The value to the variable 'count' get reassigned to 0 as it is global.
let count=0;
var add=document.querySelector('.fa-plus');
add.addEventListener('click', () =>{
//Product Label
count=count+1;
}
//to check if the variable has the computed result
console.log(count);
function submitForm(e){
for(i=0; i <= count; i++){
const prod[i] = document.querySelector('#prod-'+i).value;
ipcRenderer.send('item:add', item);
}
}
add.addEventListener('click', function(){
//+= is just a shortcut. You can also use count++
count+=1;
});
You’re also probably better off using var instead of let since trying to change a let usually results in a syntax error.
Based off of https://www.w3schools.com/jsref/met_element_addeventlistener.asp
(Also, unless you want the for loop to loop count+1, have it be i < count. Remember i starts at 0, not 1.)

Why does this return statement in JavaScript return nothing?

Before you mark this question as a duplicate please understand that I'm new to JS and always feared asking a question of stackoverflow.
I dont understand why calling this function returns nothing unless I enclose the function call in a console.log.
If I enclose the function call in a console.log I get the expected output "There are 3 elements in this array", however without the console.log, I dont get anything.
var counter = function (arr) {
return 'There are ' + arr.length + ' elements in this array';
};
counter(["shaun", "sara", "jessica"])
What I want to know is how I can get the output of this function without using console,.log and the reason why it does not output anything without the console.log.
console.log() is a function used to print information to the
console. return on the other hand is a call to pass some value back
up to where the call was made.
Via - CodeCademy Forum
return terminates a function and possibly returns a value to the caller of that function (whereas) console.log() will not influence the flow of your code.
Via - Difference between console.log and return in javascript?
Check and run the following Code Snippet for a practical example of how the two works:
var x = document.getElementById("first");
var y = document.getElementById("last");
var z = document.getElementById("output");
function printName(){
z.innerText = fullName();
}
function fullName(){
console.log(x.value + " " + y.value); // this wont push the concatenated name to printName()
return x.value + " " + y.value; // this will push the concatenated name to printName()
alert("y u do dis?"); // this won't run anymore since the return statement above prevents the function from invoking anything else
}
document.getElementById("btn").addEventListener("click", printName)
<input type="text" id ="first" />
<input type="text" id ="last" />
<button id="btn">Click Me</button>
<br/>
<div id="full">Hello <span id="output"></span>!!</div>
If the return statement above is removed, the console.log() alone won't return anything to printName() except display the concatenated name in your console.
var counter = function (arr) {
return 'There are ' + arr.length + ' elements in this array';
};
let functionResult = counter(["shaun", "sara", "jessica"]);
You need to return the result to a variable.
Then you can use it as you want.
So, you are actually returning something, you just have no way to view it without console.log() if you're wanting to use the returns of this function in another function, or somewhere else, you can assign it to a variable like
const myCounter = counter(["shaun", "sara", "jessica"])
console.log(myCounter)
All return is doing is making the results of the function available to be used elsewhere. If you aren't displaying it via console.log, or some other method (putting it into an HTML element or something) then you'll never "see" it anywhere, and it'll looks like the function isn't doing anything, even though it is.

Getting the total of multiple functions outputs in Javascript, node.js

I have this function called numFunc(), which produces a numeric output.
I want to run this function 5 times and get the sum of all 5 outputs.
Here's what I've tried
function total(){
for (itr=1; itr<=5; itr++) //run the function 5 times
{
var numF = numFunc(); //store the output from the function in a variable
var sum = sum+numF; //Get the sum of all 5 variables
}
console.log(sum);
}
total();
But, what I get is the following output
3
3
3
3
3
NaN
What I want is the sum as a single value. How do I achieve this?
You need to declare your variabble outside of the loop and set it to a number value otherwise you are adding an undefined to an integer. Thanks #jfriend00 for the clarification
function total(){
var sum = 0;
for (itr=1; itr<=5; itr++) //run the function 5 times
{
var numF = numFunc(); //store the output from the function in a variable
sum = sum + numF; //Get the sum of all 5 variables
}
console.log(sum);
}
total();
In the statement:
var sum = sum + numF;
You are trying to add something that does not yet exist, because you just declared it there with the var
With your statement, you should be declaring the vars above the loop:
function total(){
// declaring the variables before you use them.
// I will set them to 0 so I know they're supposed to be numbers, and 0 wont affect the outcome of the function
var numF = 0;
var sum = 0;
for (itr=1; itr<=5; itr++) //run the function 5 times
{
numF = numFunc(); //store the output from the function in a variable
sum = sum+numF; //Get the sum of all 5 variables
}
console.log(sum);
}
total();
What about trying an array, and then adding that array values externally after the function fires like this?
EDIT: Used the repl.it code editor to test this theory out. I had to change the code a bit but remained under the same premise. Used separate the functions and then fed the array builder function into the calculator function to properly calculate the array variables. Repl link here: (https://repl.it/B128/1)
function numFunc(){
return 3;
};
function total(){
var toBeSummed = []; //set up an array to put your sum variables into as a more versatile variable type to perform this in.
for (var itr=0; itr<5; itr++){ //runs the function 5 times
var numF = numFunc(); //store the output from the function
var arrayItr = itr; //uses "itr" variable to iterate a 0 based index 5 times
toBeSummed[arrayItr] = numF; //for each arrayItr 0-5 makes the array value equal to the numF value.
};
return toBeSummed;
};
var sum = 0;
function counter(totals){
for(sums in totals){ //iterates the x array elements(5 in this case)
sum = sum + totals[sums]; // Adds the current value of sum, plus the values at each existing array point(at this point values in array index 0-5)
//console.log(sum); //Should now log the correct set of sums "browser"
};
console.log(sum);
};
counter(total());
Thank you all for your help.
I think I found the issue. The original numFunc() function seemed to have a console.log() statement that's why I kept on getting the list of 3's all the time, replacing that with a return resolved that.
And as you guys suggested declaring the sum variable outside the loop prevented the display of 'NaN'

Changing global Variable from within function

Here im having a bit of an issue with this very simple script Ive written up. The aim for this script is to simply reduce the given number by one each time the button is clicked. I cannot appear to do this.. My global variable being the Number=100 doesnt appear to change, or change more than once.. Apologies for not being able to explain this well.
Here is the part im working on..:
<script>
var Number = 100; // Number i want changed and to keep changing each button click
function outcome() { // Button calls this function
Number = Number - 1; // Tries to change Global Number.. :/
}
document.write(Number); // Has the Number written in the document
</script>
Yes, conceptually this is right. Only you are not calling the function, at least not before writing Number to the document.
Btw, Number is the global reference to the Number constructor so you should use another variable name, lowercase at best.
var num = 100;
function outcome() {
num--;
}
outcome();
document.write(num); // 99
or
<script>
var num = 100;
function outcome() {
num--;
alert(num);
}
</script>
<button onclick="outcome()">Decrease!</button>
(Demo at jsfiddle.net)
You have to call your function:
<script>
var Number=100
function outcome(){
Number=Number-1
}
outcome(); // call the function here
document.write(Number)
</script>
or don't use a function in the first place:
<script>
var Number=100
Number=Number-1
document.write(Number)
</script>

Unable to pass values to a function

I have a function draw_integer(n,s,x,y,plotx) , which draws a integer ,n on HTML5 canvas of size s in the coordinates (x,y), I am calling this function inside another function draw_num() as follows,
(plot0, number and size are the respective id's of canvas, number & size input fields,
function drawnum() is being triggered with an onclick event.)
function drawnum() {
var n = document.getElementById('number').value;
var s = document.getElementById('size').value;
console.debug(n,s);
draw_integer(n,s,100,100,plot0); // this doesn't get executed
}
function draw_integer(n,s,x,y,plotx){ //lots of code }
The draw_integer function being called under drawnum doesnt get executed, what is the problem I am unable to identify.
using console.debug() returns the appropriate values of number and size as entered by user, also if i use draw_integer(3,100,100,100,plot0) (draw number 3 of size 100) instead of draw_integer(n,s,100,100,plot0) it works .
So that means that there is some error occuring while passing the varaible n and s from drawnum() to draw_integer().
Thinking that this might be due to to the local scope of the variables , I tried this.
var n = document.getElementById('number').value;
var s = document.getElementById('size').value;
function drawnum() {
console.debug(n,s);
draw_integer(n,s,100,100,plot0); // this doesn't get executed
}
function draw_integer(n,s,x,y,plotx){ //lots of code }
But that didn't work either.
can you help me out or suggest a better way to solve this problem .
var n = document.getElementById('number').value;
var s = document.getElementById('size').value;
The variables n and s above are Strings and not Numbers. You need to either use parseFloat or parseInt to convert it.
var n = parseInt(document.getElementById('number').value, 10);
var s = parseInt(document.getElementById('size').value, 10);

Categories

Resources