What is a variable called that is only used in a function and have no meaning outside the function?

Find out the difference between global and local variables. Global variables are declared outside any function, and they can be accessed (used) on any function in the program. Local variables are declared inside a function, and can be used only inside that function. It is possible to have local variables with the same name in different functions. Even the name is the same, they are not the same. It's like two people with the same name. Even the name is the same, the persons are not. The scope of a variable refers to where is a variable visible or accesible. If a person asks what is the scope of a variable, she's asking whether it is local or global.

Tags: scope, global, local

Code editor

You can make changes to the code below. Then run this program (Ctrl+R)

Reference
float
println
setup
void

What is a variable called that is only used in a function and have no meaning outside the function?

Fun Programming by Abe Pazos is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

A scope is a region of the program and broadly speaking there are three places, where variables can be declared:

  • Inside a function or a block which is called local variables,
  • In the definition of function parameters which is called formal parameters.
  • Outside of all functions which is called global variables.
  • Here let us explain what local and global variables are.

    Local Variables

    Variables that are declared inside a function or block are local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. Following is the example using local variables:

    #include <iostream> using namespace std; int main () { // Local variable declaration: int a, b; int c; // actual initialization a = 10; b = 20; c = a + b; cout << c; return 0; }
    Global Variables

    Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their type throughout the life-time of your program.

    A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. Following is the example using global and local variables:

    #include <iostream> using namespace std; // Global variable declaration: int g; int main () { // Local variable declaration: int a, b; // actual initialization a = 10; b = 20; g = a + b; cout << g; return 0; }

    A program can have same name for local and global variables but value of local variable inside a function will take preference. For example:

    #include <iostream> using namespace std; // Global variable declaration: int g = 20; int main () { // Local variable declaration: int g = 10; cout << g; return 0; }

    When the above code is compiled and executed, it produces the following result:

    10

    This forum is now read-only. Please use our new forums!

    when i saw the definitions, i was clueless. can someone please give me a clearer definition of these 2 items? thanks in advance!

    Hm, I think what Leng wrote here is pretty clear:

    Variables defined outside a function are […] called global variables. Variables defined within a function are local variables.

    “Scope” is just a technical term for the parts of your code that have access to a variable.

    In the picture below, the scope of the local variable is highlighted blue – it’s the function where that var was defined. Any code inside that function can access (read and change) this variable. Any code outside it can’t. It’s local, so it’s invisible from outside.

    What is a variable called that is only used in a function and have no meaning outside the function?

    Variables defined in the white area are global. Their scope is the entire script. Which means that you can read and change them anywhere in your code.

    Here’s an example of nested scopes:

    var g = 100; function outer() { var x = 99; function inner() { var y = 77; } }

    Here the code inside the inner function has access to all three variables. The code inside outer can only access g and x, and the code outside of the outer function can only see g.

    Put in terms of scope, g is global, x is local to outer (or, equivalently, the scope of x is the outer function), and y is local to inner (i.e. its scope is inner).

    I’m learning too, but here’s how I think about it (someone correct me if I’m wrong):

    The inner function has access to all three variables because all three variables exist while the inner function is running.

    The reason the outer code cannot access variables inside inner functions is that those functions aren’t running (they don’t exist on the stack or whatever it is called) until these inner functions are called in the code. And then they exist only for the time necessary for the length of time necessary to do their work.

    If we assume that the example code is in a ‘main()’ function: While ‘main()’ is running, it’s the only code running. While ‘outer()’ is running, only outer() and the main() code exist. While ‘inner()’ is running, inner(), outer() and the main() code are in memory or running.

    The functions finish in the reverse order that they started. Last function to start is first to finish. In other words, as each function terminates, the ‘onion’ is unwrapped the the computer can ‘see’ the original values for X

    Even if we were to assume that the computer knew that the innermost variables were going to exist at some time in the future, it would be too confusing to sort out which variables were visible and which were not.

    Bottom line: Think of inner functions as being lazy –their default behavior is to use the outermost (global) variable if one exists by the same name. Functions only bother to create a new variable inside if prodded to do so by the “var” keyword, and then this inner function is too tired and worn out from making that new variable to look any further outside for any other variables by the same name. The inner function will just use whatever is closest to it.

    For example:

    var X = 100; function outer() { var X = 99; function inner() { var X = 98; } }

    At the start of the code block above, X === 100 While outer() function is running, a different X === 99 // unless we omit the ‘var’ While inner() function is running, yet another X === 98 // unless we omit the ‘var’ After inner() function finishes, the outer() function sees the second X === 99 After outer() function finishes, the global X === 100

    If we had forgotten to use the ‘var’ keyword in either outer() or inner() functions, we would have accidentally (or on purpose) overwritten the value of X in the layer of the function onion immediately outside. That’s called a ‘side effect’.

    var my_number = 7; //this has global scope

    var timesTwo = function(number) { var mynumber = number * 2; console.log(“Inside the function mynumber is: “); console.log(mynumber); };

    timesTwo(7);

    console.log(“Outside the function mynumber is: “) console.log(my_number);

    Yes, very nice explanation, but the excercise went a long, long, long way to explain what global and local scope means. It was a very confusing exercise and could have been done in a lot less time. I’m still kind of confused as to what Leng was trying to illustrate..

    var my_number = 7; //this has global scope

    var timesTwo = function(number) { keyword = number * 2; console.log(“Inside the function my_number is: “); console.log(keyword); };

    timesTwo(7);

    console.log(“Outside the function my_number is: “) console.log(my_number);

    the question isn’t clear, because they named as my_number like the same function but it isn’t. One is a global fonction (my_number), because it’s defined outside of a function -it’s free- and the other is a local function (keyword) because it’s defined and used into the function timesTwo.

    Am I right?

    Thank you!

    var my_number = 7; //this has global scope

    var timesTwo = function(number) { keyword = number * 2; console.log(“Inside the function my_number is: “); console.log(keyword); };

    timesTwo(7);

    console.log(“Outside the function mynumber is: “) console.log(my_number);

    For me was the same as Karen Santos. Did not get why the results are “inside 14” and “outside 14” when we do not put “var” in front of “my_number”. After a short recap, I saw on lesson 26 from the chapter “Getting started with programming” how easy it is to change the value of a variable already defined. var myAge = “Thirty”; myAge = “Thirty-one”; So in this case the function “timesTwo” actually change the value of the variable “my_number” and that is way we have both results (inside & outside) 14. In case we put “var” in front of “my_number”, even it has the same name as the global one, we practically define a new variable that has a local scope (it does not get outside the function). Only the return value of the function goes outside and that’s why we have in this case the results: “inside 14” - the result of the function timesTwo(7) = 7 * 2 “outside 7” - the value given to the global variable var my_number = 7 This is how I see the logic and if I’m not right please correct me. Hope this helps.

    The first problem of the set is written horribly.

    var variable=14; var global=function(number){ var variable = number+1; console.log(variable); } //this is an example of a local variable”variable” as you call it only in the function global(variable); //and this is a example of a global variable you can use its value any whereconsole.log(variable); //this shouldn’t be an issue anyways since you can solve the problem of this ever happening by simply capitalizing the global s first letter and lower-casing the locals

    // ps the console will state 15,14

    ALEC

    var nameString = function (name) {

    return "Hi, I am" + " " + name;

    };

    console.log(nameString("Susie"));

    var my_number = 7; //this has global scope

    var timesTwo = function(number) { var my_number = number * 2; console.log(“Inside the function my_number is: “); console.log(my_number); };

    timesTwo(7);

    console.log(“Outside the function my_number is: “); console.log(my_number);

    Variables defined outside a function They are called global variables and their scope is global. Variables defined inside a function are local variables.

    Thankyou for all the useful tips everyone, I struggled on this one but now I understand it and not I feel like a complete idiot not figuring it out sooner.

    I was going to post the solution to this comment but I think you learn better when you have to research the problem. Goodluck (>^-^)>

    What I find very confusing is the line of code we are supposed to change, BEFORE we change it:

    var timesTwo = function(number) { my_number = number * 2; console.log("Inside the function my_number is: "); console.log(my_number);

    I get that changing it to “var my_number = number *2” specifies a new value for my_number within the function - however I don’t understand how/why anyone would use “my_number = number *2” and how that somehow the lack of “var” makes the definition of my_number be recognized globally (ie - override the previous my_number definition outside of the function).

    I don’t understand how/why anyone would use “mynumber = number *2”

    They might not, but the beautiful thing about programming is that it allows the flexibility needed for unique situations where you might want to modify a global variable using a function for example.

    how that somehow the lack of “var” makes the definition of mynumber be recognized globally

    It’s just a convention, the grammar of the language. There are probably other ways the syntax could have been designed, but that’s just the way the language developers chose. We have to accept it. Personally, I think it is the simplest and most elegant way to clearly minimize confusion, but others might not agree. For example, there could have been a rule that the same variable name ALWAYS referred to the same data and you could never use that name within a function. That would be maximally clear, but it would limit your flexibility in naming things within functions in a large program…You might run out of variable names.

    this might help you to understand if you can see the result of what the global and local variables are doing.

    var multiplied = 5 var timesTwo = function(number) { var multiplied = number * 2; console.log('function answer, or local variable ' + multiplied); }; timesTwo(4); console.log('global variable ' + multiplied);