Concept Of JavaScript Day 2

Lecture 2 : Concept Of JavaScript

Var for Declaration :

  • Declaration a variable in JavaScript has always traditionally been done with the for keyword.
  • Declaration: var=10
  • We just declared a variable named a with the value 10.
  • We can also declare a variable inside of a function:
          function f() 
          {
               var message="Hello world!";
               return message;
           }

Global Pollution :
  • If we do not declare variable with var keyword then the variable become global, so anyone can access the variable at any time.
  • Polluting the global means that you can define to many variables that are globally accessible it may leads to generate errors because access is not restricted.
Example :

Program-

<html>
<body>
<b>This is a first program</b>
<script>
function f1()
{
    X=0;
}
f1();
alert (X);
</script>
</body>
</html>

Output-

Hoisting :
  • Hoisting is JavaScript's default behaviour of moving declarations to the top.
  • JavaScript declarations are hoisted.
  • In JavaScript, a variable can be declared after it has been used.
  • Hoisting is JavaScript's default behaviour of moving declarations to the top of the current scope (to the top of the current script or the current function).
Example :

        var X;
        alert(X);
        X=10;

    In above example X is declared at the top but it is initialized at the end after the use of variable so it also shows the output is undefined.


Program-

<html>
<body>
<b>This is a first program</b>
<script>
var X;
alert (X);
X=10;
</script>
</body>
</html>

Output-

Undefined vs Referenced :
  • JavaScript variables start with the value of Undefined if they are not given a value when they are declared (or initialized) using var, let, or const.
  • Variables that have not been declared usually cannot be referenced, except by using the typeof keyword, which will not throw a ReferenceError.
Example :

Program- 

<html>
<body>
<script>
alert(X);
var X= 10;
alert(X);
</script>
</body>
</html>

Output-
              
                                                 

    As we see in above example the variables are declared but it is not defined then it gives undefined message but if we do not declare the reference error will occur as bellow. 

Program-

<html>
<body>
<script>
alert(X);
</script>
</body>
</html>

Output-

 

               

Comments

Popular posts from this blog

Basic Concept In C Sharp Day 16

Understanding C Sharp Day 18

Learn Garbage Collection Day 21