Declaring function-scoped variables

The JavaScript variables that are declared using the var keyword are called function-scoped variables. Function-scoped variables are accessible globally to the script, that is, throughout the script, if declared outside a function. Similarly, if the function scoped variables are declared inside a function, then they become accessible throughout the function, but not outside the function. Let's take a look at an example:

 var a = 12; // accessible everywhere function myFunction() {   console.log(a); // alerts 12   var b = 13;   if(true) {     var c = 14; // this is also accessible throughout the function!     alert(b); // alerts 13   }   alert(c); // alerts 14 } myFunction(); alert(b); // alerts undefined

Clearly, variables ...

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.