passing variables into functions javascript [duplicate] - javascript

This question already has answers here:
Why I'm Getting NaN? [closed]
(3 answers)
Closed 2 years ago.
I can't quite seem to figure out why the variables I created don't return the way I would like. Simple math problems here, multiplication and division. Creating the variable outside of the function returns NaN, but calling within the function returns what I suspect.
Snippets below:
var p = parseInt(document.getElementById('watts').value, 10);
var e = parseInt(document.getElementById('volts').value, 10);
function calcAmps(){
var p = parseInt(document.getElementById('watts').value, 10);
var e = parseInt(document.getElementById('volts').value, 10);
document.getElementById('answer').innerHTML = p/e;
};
Now, using the variable within the function work fine. The math executes without issue. But if I comment out the variables within the function and attempt to use the global variables, I get NaN.
Any thoughts? Should be a softball question.

When initialized outside the function, the values are only fetched from the DOM once, when the script first runs. Inside the function, the values are fetched at the point that the computation actually happens.
To be clear and explicit, the following:
var p = parseInt(document.getElementById('watts').value, 10);
does not mean that a permanent dynamic relationship is established between the variable p and the input field. Instead, it instructs the runtime to fetch the current value of the field at the time the code runs. After that point, nothing you type in the input field will be reflected as the value of p.

Related

How to access value returned from a function expression? [duplicate]

This question already has answers here:
javascript named function expressions - scope accessibility [duplicate]
(4 answers)
Closed 2 years ago.
I'm trying to return and access the value of a dynamic select from onchange event. I know how to work with function declarations but function expressions are unclear to me. A little help would be appreciated.
js
//create select
var select = document.createElement('select');
select.setAttribute('id','select_month');
//onchange
select.onchange = function changeMonth(selectedmonth){
selectedmonth = this.value;//works well here
return selectedmonth;
};
var selectedmonth = changeMonth();//undefined
changeMonth is a variable that is scoped only to the function itself, and is therefore not available to the rest of the script.
Even if it was available, then realise that when that function is called by the DOM (when the event fires), it calls it with this bound to the DOM element. When you call it explicitly in your code, you should do the same.
The good thing is that the reference to the function is available as select.onchange, so use that. That way you solve both issues at the same time:
var selectedmonth = select.onchange(select);

Javascript -What happens if a variable and a function have the same name? [duplicate]

This question already has answers here:
Function and variable with the same name
(2 answers)
Closed 5 years ago.
Might be a kind of easy question, but I have a question on the issue of having the same name for a variable and a function.
If there's a variable,
var add = 1;
and a function,
function add(x,y) {return x+y;}
and there're two console.log,
console.log(add)
console.log(add(1,2))
I've expected those 2 console.log would work properly since add contains the Number and add() is classified as a Function, but the second one prints an error. So they aren't considered the same.
But the result says I'm wrong.
Can anyone explain what's going on in my code?
Variables and function definitions(not expressions) are hoisted to up, it means that wherever in scope you wrote your function or variable they will be moved to the start of the scope. First goes functions definitions then variables. So it means that functions will be overwritten by variables.
var add = 1;
function add(x,y) {return x+y;}
console.log(add);
The order doesn't matter. Later will be the variable and will overwrite
function add(x,y) {return x+y;}
var add = 1;
console.log(add);

Javascript chained scope and context [duplicate]

This question already has answers here:
Execute JavaScript code stored as a string
(22 answers)
Closed 8 months ago.
Is it possible to define a function run that acts like this?
a = run('var x = 100;')
b = run('console.log(x);') // prints 100
c = run('y = 1;')
d = run('console.log(y);') // prints 1
I tried several ways, using apply and passing the same context, binding a context to a function, returning a closure with a recursive call etc. but I can't seem to get anything to work.
Yeah, as MyLibrary says, you probably want eval, if you really want to do this. So:
var run = eval;
a = run('var x = 100;')
b = run('console.log(x);') // prints 100
c = run('y = 1;')
d = run('console.log(y);') // prints 1
would seem to work.
JavaScript allows assigning functions to variables, so you can set the run variable to eval. As far as eval, you may want to learn about it and as you can see from comments, its use in normal function creation is often discouraged.
Are you referring to eval function?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

Add .change() to every variable in js Array(); [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
I'm trying to create "dynamic" cascading dropboxes, and I almost have it done. However, I'm running into an issue dealing with adding a .change() listener onto every variable inside of an array that contains the <select> field ids.
So if I use:
fields[0].change(function() {populateFields(1, 0, xml);});
fields[1].change(function() {populateFields(2, 1, xml);});
The code works perfectly. However, I would prefer to use something like this:
for (i=1; i<numberOfFields; i++){
p = i-1; current = i;
fields[p].change(function() {populateFields(current, p, xml);});
}
So that I can have a variable number of fields, because the current code is limited to three fields. The for loop currently works, but doesn't work after the second field is entered.
Any help would be appreciated.
NOTE: This is not a question about variables or passing variables into functions, but rather adding a event listener to an array. The marked answer was the correct answer.
You can use Array.prototype.forEach(), and in the function that you pass in you can put a guard for the case where you are processing the first element:
fields.forEach(attachChangeHandler);
function attachChangeHandler(field, i) {
if (i === 0) { return; }
field.change(function() {
populateFields(i + 1, i, xml);
});
}

Change variable through function in JavaScript [duplicate]

This question already has an answer here:
Changing variable in another function in JavaScript
(1 answer)
Closed 7 years ago.
I am trying to automate the changing of a variable through a function. However although it returns the right value, it doesn't change the actual value of the variable passed to it.
function change(one, two){
one = two;
return one;
}
var test = 1;
change(test, 5);
// returns 5;
console.log(test);
// still 1
Why does this happen and how can I solve this?
You can't pass variables. When you call change(test, 5); you are passing the value of test not the variable test.
That value is copied to the variable one.
You then assign a new value to one, but that doesn't touch test.
If you want to do anything like this, you need to pass an object and then modify the value of a property of the object.
function change(one, two){
one.test = two;
return one.test;
}
var myObject = {
test: 1
};
change(myObject, 5);
console.log(myObject.test);
You can't do this in JavaScript. Variables cannot be passed by reference, they are always passed by value.

Categories