Skip to main content

#2 Scope in JavaScript: Block or Function?

So, in JavaScript, do you have a function or block level scope? It's a function level. This brings the concept of global and local scopes.

By default when you start declaring variables (except in function()) in JavaScript, they are in global scope. For example:

<script>
var a = 10;
console.log(a); 
</script>

Output: 10

Here, a is a global variable. If you want to create a local scope then you need to put the variable in function(). For example:

<script>
function abc()
{
          var a = 10;
          console.log(a); 
}
abc(); // calling abc function
</script>

Output: 10

Here, a has a local variable because it can be accessed only in abc() function and not anywhere else.

Now, let's look at another scenario:

<script>
var a = 20;
console.log("Outside function " + a);
function abc()
{
          console.log("Inside function " + a); 
}
abc(); // calling abc function
</script>

Output:
Outside function 20
Inside function 20

In the above code, function abc() inherits the global scope variable a and thus prints the same value.

But, if we have same variable in function abc() then it will override the global variable. Look in the below example:

<script>
var a = 20;
console.log("Outside function " + a);
function abc()
{
          var a = 10;
          console.log("Inside function " + a); 
}
abc(); // calling abc function
</script>

Output:
Outside function 20
Inside function 10

However, if we try to use the variable outside function, then it will give an error:


<script>
console.log("Outside function " + a);
function abc()
{
          var a = 10;
          console.log("Inside function " + a); 
}
abc(); // calling abc function
</script>

Output: 
Uncaught ReferenceError: a is not defined

Take note that it gave an error because it could not find variable a in the current scope and also it didn't move ahead with next execution and it stopped when error occurred.

But I still want to access the variable declared inside abc() function. So the only way to do so is to make the variable present in function abc() global. How to do it? Just remove var keyword and immediately it becomes global.

<script>
function abc()
{
          a = 10; // Now the variable is global
          console.log("Inside function " + a); 
}
abc(); // calling abc function
console.log("Outside function " + a);
</script>

Output: 
Inside function 10
Outside function 10

But this is a bad practice. Don't declare variables without the keyword var.

As I said before, there is no block level scope in JavaScript. This implies that if the variable is declared in if ... else , for loops, switch statements, etc, JavaScript treats it a global variable. Look at the below example:


<script>
if (true)
{
         var a = 10;
}
console.log("Outside function " + a);
</script>

Output: 
Outside function 10


Comments

Popular posts from this blog

Characteristics of a Good Programming Language

Till now there are many high level languages which are very popular, and there are others, which could not become so popular in-spite of being very powerful. There might be many reasons for the success of a language, but one obvious reason is the characteristics of the language. Several characteristics believed to be important with respect to making a programming language good are briefly discussed below. Simplicity A good programming language must be simple and easy to learn and use. For example, BASIC is liked by many programmers only because of its simplicity. Thus, a good programming language should provide a programmer with a clear, simple and unified set of concepts which can be easily grasped. It is also easy to develop and implement a compiler or an interpreter for a programming language that is simple. However, the power needed for the language should not be sacrificed for simplicity. The overall simplicity of a programming language strongly affects the readability of the pr...

Angular 4 and Firebase Authentication: Setup

If you have come to this article, it means you are keen to learn new technology and that too Firebase. I love Firebase because it provides all basic but important features of any web application. Take for example, authentication, which is cumbersome and risky if not implemented with utmost care. And when we have the integration of Angular and Firebase, it becomes a lot easier for a developer to build such crucial modules in less time with minimal efforts. In this article we will create a simple Angular application using Firebase. I am going ahead with the understanding that you know the benefits of Firebase and have little knowledge about it. There are plenty of posts out on the web if you are behind. Step 1: Install Angular CLI (if not installed). npm install -g angular-cli Step 2: Create new Angular 4 project. By default now angular CLI will create Angular 4 project so you need not fret. ng new firebase-authentication Step 3: Check whether the ne...

Switch-case, simple calculator . . .

11.      Write a program to perform some mathematic functions with the help of “switch-case” statement. #include<stdio.h> #include<conio.h> void main() { int a,b,ans; char c; clrscr(); printf("\ Enter a and b:"); scanf("%d%d",&a,&b); printf("\n Enter operator:"); fflush(stdin); scanf("%c",&c); switch(c) { case'+':ans=a+b;       break; case'-':ans=a-b;       break; case'*':ans=a*b;       break; case'/':ans=a/b;       break; } printf("\n ans %d",ans); getch(); } 12.      Print the Fibonacci series #include<stdio.h> #include<conio.h> void main() { int a=1,b=1,s=3,c,ch; clrscr(); printf("how many steps="); scanf("%d",&ch); printf("%5d%5d",a,b); for(s=3;s<=ch;s++) {       c=a+b;       printf("%5d",c);       a=b;    ...