Variable scope in JavaScript
by danielkwood
HTML
<html>
<head>
<title>Variable scope</title>
<script src="script.js"></script>
</head>
<body>
</body>
</html>
JavaScript
var userGlobal = "Joe"; // this is a global variable
function displayUser(){
console.log(userGlobal + " accessed inside function");
}
displayUser();
console.log(userGlobal + " accessed outside function");
function displayOtherUser(){
var userLocal = "Sally"; // this is a local variable
console.log(userLocal + " accessed inside function");
}
displayOtherUser();
// the line below will cause an error because we are trying to access the 'userLocal' variable outside its scope
console.log(userLocal + " accessed outside function");