0
Can I use variables from outside the function?
3 Answers
+ 5
Yes that's because in your code 'Lastname' is a global variable.
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
- 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