-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy path09-varsLocalGlobal.html
More file actions
52 lines (42 loc) · 1.75 KB
/
Copy path09-varsLocalGlobal.html
File metadata and controls
52 lines (42 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Demo</title>
</head>
<body>
<script type="text/javascript">
// Local and Global variable scopes
/*
Understanding which variables are accessible in any given
part of your JS code is critical to avoiding bugs and writing
clear code. Here's the basics...
Functions act as a way of creating a new scope:
Global variable - a var that is accessible OUTSIDE all functions
Local variable - a var accessible only INSIDE a function
A local variable will not be accessible in any scope outside
of the scope in which it was defined.
*/
// This is a global var, accessilbe in every scope:
var wife = 'Jennifer';
function outPut() {
// This is a local var, accessible only in this function's scope:
var daughter = 'Zoe';
/*
WATCH OUT: With no "var" keyword, variables are created in the global scope. Always use var.
*/
son = 'Micah' // ANTIPATTERN
document.write(wife);
document.write(daughter);
document.write(son);
}
// Notice in the view how the var of `daughter` does not appear
// This is because `daughter` is scoped to the outPut function
outPut();
document.write(wife);
document.write(son);
document.write(daughter); // This causes an error, script halted.
</script>
</body>
</html>