Javascript cannot return values - javascript

I want to get the values a, b, c from these functions and use them in my total. I have tried to return the values but it doesn't work. When I create global variables, total always takes the original global variable instead of the one from the function.
function d1() {
var a = document.getElementById("s1").value;
document.getElementById("d1").innerHTML = (2 * a).toFixed(2);
return a;
}
function d2() {
var b = document.getElementById("s2").value;
document.getElementById("d2").innerHTML = (3 * b).toFixed(2);
return b;
}
function d3() {
var c = document.getElementById("s3").value;
document.getElementById("d3").innerHTML = (4 * c).toFixed(2);
return c;
}
var total = a + b + c;
document.getElementById("total").innerHTML = total.toFixed(2);

I think it should be
var total = d1() + d2() + d3();
Since variables a, b and c are local to the functions and they fall into those functions scope. However, the biggest problem is that you do not call the functions at all, so even with using global variables your a,b,c would be undefined.

a, b and c are local variables within d1, d2 and d3 respectively. So, you can't use them directly outside of their scope like you have tried to.
There are multiple ways of achieving your desired outcome. The easiest
function d1() {
var a = document.getElementById("s1").value;
document.getElementById("d1").innerHTML = (2*a).toFixed(2);
return a;
}
function d2() {
var b = document.getElementById("s2").value;
document.getElementById("d2").innerHTML = (3*b).toFixed(2);
return b;
}
function d3() {
var c = document.getElementById("s3").value;
document.getElementById("d3").innerHTML = (4*c).toFixed(2);
return c;
}
**var total = d1() + d2() + d3();**
document.getElementById("total").innerHTML = total.toFixed(2);

Related

I am trying to figure out where the c is coming from inside the function

var x = 2;
var y = 8;
var a = function(b) {
return function(c) {
var num = Math.abs(b);
return x + y + Math.abs(b) + c;
};
};
var fn = a(x);
x = 4;
console.log(fn( Math.random() * 10) );
ive tried to console log a, b, c and i still cant wrap my head on what is happening here
You have two functions, let's call them a and anonymous.
a is this:
var a = function(b) {
/* do stuff */
};
Which is equivalent to
function a(b) {
/* do stuff */
};
Now, let's define function anonymous:
function anonymous(c) {
var num = Math.abs(b); // note that 'b' is pulled in from the parent's scope
return x + y + Math.abs(b) + c; // note that 'x' and 'y' also pulled in from the parent's scope
};
In javascript, functions can be assigned to variables. That's exactly what your example code does with var a: sets it equal to function a.
Because of this ability to assign functions to variables, functions can actually return other functions as a value. This is also exactly what a does. It returns the function anonymous.
var a = function(b) {
return anonymous;
};
Now, in your code, the function anonymous doesn't have a name. But, the anonymous that I defined is equal to the unnamed function that your a returns. Let's substitute it in for anonymous from the previous code block.
var a = function(b) {
return function(c) {
var num = Math.abs(b);
return x + y + Math.abs(b) + c;
};
};
You could equivalently write:
var a = function(b) {
var anonymous = function(c) {
var num = Math.abs(b);
return x + y + Math.abs(b) + c;
};
return anonymous;
};
Thus, when you call var fn = a(x), fn = anonymous, the function. Recall that anonymous takes in an argument, and it names that argument c.
Thus, when we call fn(Math.random() * 10), fn is replaced with anonymous and since the argument to anonymous is Math.random() * 10, when anonymous executes, c = Math.random() * 10
Sorry, this is my first explanation, it might be hard to understand but I'm trying my best to explain:
I just want to break out the code:
your code:
var x = 2;
var y = 8;
var a = function(b) {
return function(c) {
var num = Math.abs(b);
return x + y + Math.abs(b) + c;
};
};
var fn = a(x);
x = 4;
console.log(fn( Math.random() * 10) );
It is totally confusing to have
console.log(fn( Math.random() * 10) )
instead of that line of code, I changed it to
console.log(fn(10) ) for simplitcity.
As you execute var fn = a(x), b value will be 2 and fn will be assigned to the return value of var a which is a function indeed
so here what fn becomes:
var fn = function(c) {
var num = Math.abs(b);
return x + y + Math.abs(b) + c;
};
x = 4;// x value was changed to 4 instead of 2 from the line 1
now he is passing c value through the last line of code which is :
console.log(fn( Math.random() * 10) );
or
for simplicity
console.log(fn(10) );
so finally the code will be looking like this:
var y = 8;
var fn = function(c) {
var num = Math.abs(b);
return x + y + Math.abs(b) + c;
};
x = 4;
console.log(fn(10) );
Hopefully, you understood by my explanation.

How to store data into variable.?

var a=1800, b=10;
if (a == b) {
document.write(a - b) = c;
}
else if (a > b) {
document.write(a - b) = c;
}
else {
document.write("Everything is wrong.") = c;
}
var x = c * 100;
document.write(x);
Hello friends, Can i store result of variable into "c". if yes then why i am not able to use the data for arithmetic calculations further.
I am getting 1790 as answer from if else statement.
The variable should be on the left side of the equals sign. document.write doesn't return a value so you should do the assignment before that line.
else if (a > b) {
c = a - b;
document.write(c);
}
That isn't really even valid JavaScript.
You're calling a function (document.write()) and then using the assignment operator on it (which you can't do).
The end results would be equivalent of writing something like undefined = 7 since JavaScript will evaluated/execute the function first.
C is also never declared anywhere so you'll have a problem with that potentially as well.
Instead you'll want to do something like this:
let c; //declare C but don't assign it a value
const a = 1800;
const b = 10;
if(a === b || a > b){ //Since you're doing the same thing combine the conditions
c = a - b;
document.write(c);
} else {
document.write("Somethings wrong")
}
let x = c * 100; // If c is undefined you'll get NaN similar to above, otherwise you'll get a result
document.write(x);
Firstly you should initialize your variables, then else if statement doesn't make any sense because in if your are doing the same thing which you could do with || OR operator.
const a = 1800;
const b = 10;
let c = null;
if (a == b || a > b) {
c = (a - b) * 100;
} else {
c = "Everything is wrong.";
}
document.write(c);
Document.write does not return the result of the equation, and your assignments are incorrect. When assigning variables think of it this way:
"I have a variable C. I would like C to store the value of Y."
So C = Y. It's backwards from the way math does it. ( Equation = result. ) In programming, it tends to be StorageLocation = Equation.
Why do I say tends to be? There's got to be a language out there that doesn't hold up to that paradigm!
Here's your updated code:
var a=1800, b=10, c = 0; // Initializing c for document.write is a good practice.
if (a == b) {
c = a-b;
}
else if (a > b) {
c = a-b; /* As the other two posters noticed ... this does the same thing as the a == b. I am assuming you'd like to do something a little different with the two blocks. */
}
else {
c = "Everything is wrong.";
}
document.write(c); // "Don't Repeat Yourself" or "DRY" is good practice.
var x = c * 100; // Note - Multiplying your string by 100 is weird.
document.write(x);

Function in "natural language"

I've made a function "ADD" which modifies the value of a variable :
function ADD(xs, n)
{
var nom_variable = xs;
var XS = eval(xs);
nouvelle_valeur = eval(nom_variable + "=XS+n");
}
var x = 5 ;
ADD("x",5); // now x = 10
I would like that the first argument of the function ADD is x, not "x". Is this possible ?
I want my students to write algorithms in a way similar to natural language.
Thanks !
You can't pass x as if it were a reference, but you could construct a functional reference (or Lens) although you are still not passing x but a variable that is a reference of x.
var x = 5;
var xRef = {
get : function(){
return x;
},
set : function(val){
x = val;
}
}
function add(ref, n){
var oldVal = ref.get();
ref.set(oldVal+n);
}
add(xRef, 5);
console.log(x);
It's definitely not pretty though.

Two operation in one function

function test(a, b){
a = a + 2;
b = b + 5;
}
var a = 1;
var b = 2;
test(a, b);
console.log(a);
console.log(b);
This return 1 and 2, but i would like 3 and 7.
Is possible to make two operation in one function? This working if i use return, but how to use return to two operation?
live: http://jsfiddle.net/anCq6/
The reason you are getting 1 and 2 instead of 3 and 7 is because there are two different a and b variables. There's the a and b you declared outside the function, and there is the a and b which represent the values you passed into the function. (Basically, the parameters declared in the function's parentheses are newly declared variables.)
If you want to change the external a and b, change your test function to the following:
function test(x, y) {
a = x + 2;
b = y + 5;
}
Or, alternatively, don't pass a reference into the function, so that the a and b in the inner scope refer to the same a and b as the outer scope:
function test() {
a = a + 2;
b = b + 5;
}
Just send it back as an object...
function test(a, b){
a = a + 2;
b = b + 5;
return {a:a,b:b};
}
var a = 1;
var b = 2;
var test = test(a, b);
alert(test.a);
alert(test.b);
DEMO HERE
This doesn't work because since numbers are passed by value and not by reference, you're modifying the local copies of those variables, however the ones in the outer scope remain unmodified.
If you remove the a and b parameters from your function, you'll get the behavior that you want since the a and b parameters that are being modified will be the ones in the outer scope.
What are references?
Here's a pretty decent answer - Javascript by reference vs. by value
In short, only objects and arrays are passed by reference. Although in reality it's more complex than this depending on how functions are defined and syntax, at this point you can assume that anything that's defined by calling new or the syntactic shorthands [] ( array ) and {} ( object ) are passed by reference. Other types like numbers and strings are passed by value.
Another solution: because of how variable scope works in JavaScript, you can just remove the parameters of "test" function and it will work.
function test(){
a = a + 2;
b = b + 5;
}
function test(){
a = a + 2;
b = b + 5;
}
var a = 1;
var b = 2;
test();
console.log(a);
console.log(b);

javascript - where should I put "var" in order to get specifc values

That's a code fragment task - you should enter "var" (as many as want) in it in order to get 17 in the first, and 21 in the second alert. I thing that I have met this before, but still was not able to solve the issue.
a = 3;
b = 2;
function line(x) {
a = 5;
b = 4;
return a*x + b
}
//b should be 17
b = line( a ) - b;
alert( b );
//c should be 21
c = line ( a ) + b;
alert(c);
If you put "var" in the function in front of b, it will alert "17". The next alert gives us 46 because of the new value of b, return by the function.
function line(x) {
a = 5;
var b = 4;
return a*x + b
}
That's the source of the task:
http://www.codecademy.com/courses/javascript-for-jquery/1?curriculum_id=4fc3018f74258b0003001f0f/#!/exercises/3
Using exactly what's given, in exactly the way it's given is impossible.
What I mean by that is if the call:
c = line(a) + b;
is dependent upon the value of b which is the assignment at:
b = line(a) - b;
Then it's 100% impossible to either have made a a significantly-small number, or made b a significantly-large negative number to make the math work.
Therefore it's my belief that they're intended to be two separate checks.
Best-case scenario, if we're trying to have b=17 included:
a = 3;
3 * 5 = 15 + 4 = 19 + 4 = 23;
That's the smallest you're going to get, assuming you run the two back-to-back.
Even if you did it that way, you wouldn't get b = line(a) - b = 17 on the first run...
If it was written:
c = line(a) - b;
d = line(a) + b;
Then you could run both in succession and get the expected result.
Or you can run:
var a = 3,
b = 2;
function line (x) {
var a = 5,
b = 4;
return a*x + b;
}
b = line(a) - b;
and get 17.
Then you can run:
var a = 3,
b = 2;
function line (x) {
var a = 5,
b = 4;
return a*x + b;
}
c = line(a) + b;
(ie: the exact same setup with a different instigator, and without the saved b value from the return of the previous call), and get the desired result.
But it's not possible to run both of them one after the other, and expect to have them both work, without doing anything to the code but add a var or four.
Keep your function like this, if you want to maintain consisitency. Using "var" before a and b will make them local to the function block and that call. Otherwise they will refer to the global variable.
function line(x) {
var a = 5;
var b = 4;
return a*x + b
}

Categories

Resources