var sharplesson = “ online tutorials”;
Here, we assigned the value online tutorials to the variable sharplesson.
sharplesson = “online tutorials”;
Here, we first declared the empty variable ‘sharplesson’, and in the second line we have assigned the value.
Points to remember
- Many declarations – You can declare more than one variable in a statement. For example, var sharp=’seo’, lesson=’web-tuts’ and sharplesson=’web-hosting’;.
- If you will not assign value at the time of declaration, then it is having undefined value.
- The arithmetic operations can be performed with variables.
If the variable ‘A’ is declared in the function, then the scope of the variable is for that function only. No other function can use ‘A’ variable and its information. For example, Strangers cannot use your personal telephone, because it is your property. It means it is not for public use, it is for person those are in your relation or reside in your house. Here you can say ‘House’ and ‘relation’ are the function, and anyone can access ‘ telephone’ as a variable.
If the variable ‘A’ is declared outside of the function, then the scope of the variable is global. It means, you can use the same variable throughout the program code either in the function or outside the function. Let’s take the same telephone example. If that telephone is in public telephone booths, then anyone can pay, and use that phone. It means it is a publicly available thing for every one.
If you are naming any variable, then try to remember few things:
- Never use reserved words – You can have any name except the reserved names. Let’s for example, if I will declare ‘var var’, here you can see ‘var’ is already a keyword. So it is not a valid variable.
- Start with alphabets – You should not start the variable name like ‘78sharp’. It means avoid using numbers at the beginning. You can use alphabets or underscore at the start. For example, ‘sharp’ or ‘_sharp’ is a legal declaration of the variable.
When you will run this code, then the output will be:
local <—this is local declaration.
global <—this is global declaration.
Do you still want an explanation? Well, for our fresh readers, let me explain things in steps.
Step 1 – We declared the global variable ‘SharpGlobal’ and assigned it a value ‘global’.
Step 2 – We called the function ‘sharpMyScope ()’ that will execute the statement in the function.
Step3 – In sharpMyScope () function, you will see that we have declared the local variable called ‘SharpLocal’.
Step 4 – Now it will show the globally declared variable result.
Step 5– That’s it.