A scope is what determines whether or not variables stored can be accessed, in other words it determines the accessibility of a variable. There are two known type of scope namely local scope and global scope.
- Local Scope: This scope is the one that can only be accessed within a block of enclosed code. For instance, a variable declared in a function or an if else statement can only be accessed in the block of code and any attempt to access the variable outside the block of code will return undefined.
- Global Scope: This scope can rather be accessed anywhere, it can be accessed at the last line of written codes even if it was declared at the first line of code.
Now lets examine some examples
In the above example, two different variables were declared in two different functions and are accessed inside and outside the functions.
In global scope we can always retrieve data that are stored in a variable anywhere. Also values assigned to undeclared variables automatically gives a global variable
In strict mode undeclared variables does not automatically give a global variable, how? Now this takes us to strict mode.
- Prohibits some syntax likely to be defined in future versions of ECMAScript.
- Using an object, without declaring it, is not allowed
- Deleting a variable (or object) is not allowed
- Deleting a function is not allowed
- Duplicating a parameter name is not allowed
- Octal numeric literals are not allowed
- Octal escape characters are not allowed
- Writing to a read-only property is not allowed
- Writing to a get-only property is not allowed
- Deleting an undeletable property is not allowed
- The word eval cannot be used as a variable
- The word
argumentscannot be used as a variable
withstatement is not allowed
You can try the above code snippet in your IDE, run in browser and and use the debug console (click F12 ) to check errors. These are just few examples make sure you try more examples on your own and see the errors they return. Example of errors from codes like this is seen below:
What is this about?