0

Declaring variables in a function

So I was looking at this example : function addNumbers(a, b) { var c = a+b; return c; } document.write( addNumbers(40, 2) ); //Outputs 42 The example is simple, and it works. Although the logic is not very straightforward for my brain lol. So I wanted to try and modify this example. Here's what I came up with: function addNumbers(a, b) { var c = a+b; } addNumbers(40, 2); document.write(c); But this doesn't work. When I call upon the function, it doesn't actually store any value in my variable "c" as I intended. So, I did more testing, and here's what I ended up with: var c = 5; //This is only for testing the variable "c" function addNumbers(a, b) { var c = a+b; alert ("the answer is " + c) } addNumbers(40, 2); document.write(c); The "alert" displays "42" as should be. When close the alert, I see my last line of code writing the output for "the other c", which is 5. So, if I understand correctly, variables declared inside a function only exist inside of that function, right? I find it really weird that two variables "c" could exist at the same time.

29th Feb 2020, 4:57 PM
Artorius Von Kouznetsoff
Artorius Von Kouznetsoff - avatar
1 Odpowiedź