0

Can I use variables from outside the function?

1st Feb 2017, 12:17 PM
Gyenes JĂłzsef ZoltĂĄn
3 Answers
+ 5
Yes that's because in your code 'Lastname' is a global variable.
1st Feb 2017, 12:27 PM
Alireza M
Alireza M - avatar
0
A good question, The scope of the variable matters. The variable can only be accessed within its scope. There are two types of variable scope in JavaScript: Global Scope and Local Scope. var a=10; //Global variable a function sum(number){ // Scope of variable b starts var b=8; // Loval variable b return number+b; } //scope of variable b ends alert(a); //10 alert(b); //undefined alert(sum(a)); //18
17th Feb 2017, 1:39 AM
[No Name]
[No Name] - avatar
- 1
YES, I tried it with the following code: var Lastname="Beckham"; function sayHello(name) { alert("Hi, " + name + " " + Lastname); } sayHello("David"); // In the popup window shows: Hi, David Beckham
1st Feb 2017, 12:19 PM
Gyenes JĂłzsef ZoltĂĄn