Top Stories

Ankaj Gupta
March 22, 2019
Boolean datatype in javascript

JavaScript Boolean Datatype

Boolean data-type represents a logical truth value, either true or false, that are associated with the logic branch of mathematics. You can assume the values as "on or off", "yes or no", or "correct or incorrect" or "1 or 0".

It is used to represent the truth values that are associated with the logic branch of mathematics, which informs algorithms in computer science.

Note : Boolean values are very commonly are used when testing conditions, like condition and looping statements.

let's see an example of Boolean datatype :

 ➤ Example :

<script>
    var a =10, b =25, c = 15;
    document.write(b > a);  // Output: true
    document.write(b < c);  // Output: false
</script>
JavaScript
Read more
Ankaj Gupta
March 17, 2019
What are the Different Data Types in JavaScript

Basically data types are used to classify one particular type of value(data), that can be represented and manipulated data in a programming language.

Introduction of datatype

A datatypes is the specific category of information that a variable contain. It classify types of data such as string, boolean or numbers etc. So that, It determines the possible values for that particular type.

The data-type type also governs the kinds of operations that can be performed on a variable. This is important because the specific data-type you use will determine what values you can assign to it and what you can do to it.

Note : Datatypes in javascript means the type of data stored in variable.

Why data-type is used in programming language ?

The conscept of data-types is often difficult for beginning programmers to grasp because in real life you don't often distinguish among different types of information. If someone asks you for your name, your age or the current time, you dont't usually stop to consider that your name is a text string and that your age and current times are numbers.

  • However, a variables specific data-type is very important in programming because the data-type helps determine how much memory the computer allocates for the data stored in the variable.

  • JavaScript classifies data-type into 3-section :

    1.) Primitive Datatype : Following are the primitive data-type that JavaScript supports.

    • Numbers(Numerical Data).

    • String(Text Data).

    • Boolean.

    • Symbol.

    2.) Special Datatype : Following are the Special data-type that JavaScript supports.

    • Undefined

    • Null

    3.) Non-Primitive Datatype : Following are the non-primitive data-type that JavaScript supports.

    • Array

    • Function, Object and Properties.


1.) Primitive Datatypes :

  • Datatype's that can be assigned only a single value with no additional properties and methods are called primitive types.

  • Primitive defines immutable values and was introduced recently by ECMAScript standard, It can be stored in the fixed amount of memory available.

Let's see an example of primitive data-type :

 ➤ Example : Copying a primitive.

    In this example, The original was not changed, we can only change the copy.

<script>
    var a = 20;  // assign `20` to `a`
    var b = a;   //copy the value of `a` to `b`
    b = 25;      //assign `25` to `b`
    console.log(a)  // =>20
</script>

Note : Primitive types are also known as simple types or scalar types.

JavaScript supports 4-types of primitive data types described in table :

 Datatype Description Example value
Number Represents numeric(Positive or negative numbers with or without decimal places, or number written using exponential notation) values. 9, 9.5 etc.
String A string (or a text string) is a series of characters. "Hello" “Hello Coder” etc.
Boolean A logical value of true or false. true, false.
Symbol (ECMAScript 6)

2.) Special Datatype :

  • Special data-type are also known as Primitive types.

  • Javascript has 2-more literals, null and undefined, that is considered to be objects.

Following are the Special data-type that JavaScript supports, described in table:

 Datatype Description Example value
Undefined represents undefined value(A variable that has never had a value assigned to it, has not been declared, or does not exits). Undefined value
Null represents numeric values(An empty value). Null value

3.) Non-Primitive Datatypes :

  • Datatype's that Objects can contain multiple values are called non-primitive types. It is same as object in the class. We can define attributes and methods to composite data-types.

  • A Non-Primitive datatypes can contain other values. Since the contents of a reference type can't fit in the fixed amount of memory available for a variable, the in memory value of a reference type is the reference itself (a memory address).

  • For instance :

    • Array

    • RegExp

    • Function, Object and Properties.

Let's see an example of non-primitive data-type :

 ➤ Example : Copying a reference;

    The original was also changed, since the reference got copied.

<script>
    var data = {number: 22 };  //assign the reference of a new object to `data`.
    var b = data;   //copy the reference of the object inside `data` to new variable `b`.
    b.number = 75;  //modify the contents of the object `b` refers to.
    console.log(data);  //=> { number : 37 }
</script>

Note : Non-Primitive type are also known as : Reference types or Composite data-type or Complex types or container types.

JavaScript contain following non-primitive data types, described in table:

 Datatype Description
Array represents group of similar values.
RegExp represents regular expression.
Object represents instance through which we can access members.
JavaScript
Read more
Ankaj Gupta
March 16, 2019
Define dynamic typing in JavaScript

Javascript Dynamic Typing

JavaScript is a dynamically data typed language, this means that type checking is done at runtime rather than compile time.

Dynamic Typing means that, define a data-type of a variable does't need to be specified, any variable can be used to hold any/different data types. They can easily change from one data type to another data type.

  • For instance : Ruby, Python, JavaScript etc.

Let's see an example of Dynamic Typing in JavaScript :

 ➤ Example :

    In this example, the variable myName change from string to number and then boolean.

<script>
  let myName = 'Ankaj Gupta';  //Ankaj Gupta
  myName = 100;  //100 
  myName = true;  //true
</script>
Example explained :
  • In this example, the variable myName, defined as a variable by the let keyword, can be assigned to hold different data types, or can be initialized.

  • Each of the variables myName above can be set to any data type available in JavaScript. They do not need to be explicitly declared with a data type before they are used.

JavaScript
Read more
Ankaj Gupta
March 15, 2019
Web Hosting Deals (2019) Coupons, Offers, Promo codes & Promotion Codes

GREAT OFFER FOR YOU

Hostgator

55% Off

30% Off

35% Off

Coupons
Read more
Ankaj Gupta
March 01, 2019
var vs let vs const

JavaScript has 3-different keywords to declare a variable.

Example : var, let, and const

Let’s see the difference between var vs let vs const:

Keyword Scope Hoisting Can Be Reassigned Can Be Redeclared
var Function scope Yes Yes Yes
let Block scope No Yes No
const Block scope No No No
JavaScript
Read more
Ankaj Gupta
February 22, 2019
var vs let in Javascript | Difference between let and var

Difference between let and var in Javascript

There has been a lot of confusion about the use of var and let in Javascript. So here we will see difference between var and let , so that you can easily decide what to use where and when.

Let’s see the difference between var and let

# var let
1 var keyword was introduced with JavaScript. let keyword was introduced in ES 2015(ES6).
2 var statement is used to Create a function variable. let is similar to var scope, and it allows you to create a block-scoped variable.
3 Using var keyword to define variable globally (Global scope). let variables work the same as var when used in a Global scope.
4 var variables can be accessed in the window object. while let variables can't be accessed in the window object because they cannot be globally accessed.
5 Using var keyword to define variable locally (Function scope). let variables work the same as var when used in a function scope.
6 var keyword is not block scoped. let keyword is block scoped.
7 Variables declared with var is hoisted to the top. Variables declared with let is not hoisted to the top.
8 var variables can be redeclared in the same scope. let variables can't be re-declared in the same scope.

Let’s see the var vs let in details with examples :

1.) Global scope :

  • var and let variables work the same way when used in a global scope.

  ➤ Example 1: Global scope;

<script>
    var varVariable = “I am global variable.”;
    let letVariable = “I am also global variable.”;
</script>

2.) Global window object :

  • Global variables defined with let variable will not be added to the global window object like those defined with var.

  ➤ Example 2: Global window object;

  • Thus let variables can't be accessed in the window object because they cannot be globally accessed.

  1. <script>

  2. var varVariable = “I am var variable.”;

  3. let letVariable = “I am let variable.”;

  4. //Say, here we have two variables declared. let us see what output it actually gives you.

  5. console.log(window.varVariable); //=> I am var variable.

  6. console.log(window.letVariable); //=> undefined

  7. </script>

3.) Function scope :

  • var and let variables work the same way when used in a function scope.

  ➤ Example 3: Function scope;

<script>
    function display(){
       var varVariable = "I am var variable.";
       let letVariable = "I am let variable.";
    
       console.log(varVariable); //I am var variable.
       console.log(letVariable); //I am let variable.
    }  
    display();     
</script>

4.) Block scope :

  • Variable defined with var keyword is not block scoped.

  ➤ Example 4.1: For loop using var variable;

<script>
    for(var i=0; i<=5; i++){
       console.log(i); //i is visible here  
    }  
    console.log(i); //i is visible here    
</script>
  • Variable defined with let keyword is block scoped.

  ➤ Example 4.2: For loop using let variable;

<script>
    for(let i=0; i<=5; i++){
       console.log(i); //i is visible here  
    }  
    console.log(i); //Error     
</script>

5.) Variable hoisting :

  • Variables declared with var are hoisted to the top.

  ➤ Example 5.1: Variable hoisting with var;

<script>
    console.log(name); //undefined
    var name = "I am var variable";
</script>
  • Variables declared with let are not hoisted to the top.

  ➤ Example 5.2: Variable hoisting with let;

<script>
    console.log(name); //ReferenceError
    let name = "I am let variable";
</script>

6.) Re-declaration :

  • let variables cannot be re-declared while var variable can be re-declared in the same scope.

  ➤ Example 6.1: var variable re-declaration in same scope;

Variables defined with var keyword can be redeclared in the same scope.

<script>
    var a = 10; 
    var a = 20; //20
</script>

  ➤ Example 6.2: let variable re-declaration in same scope;

Variables defined with let keyword can't be redeclared in the same scope.

<script>
    let a = 10; 
    let a = 20; //SyntaxError: Identifier 'a' has already been declared
</script>
JavaScript
Read more
Ankaj Gupta
February 22, 2019
How to use 'const' keyword in JavaScript?

const is one of 3-keywords you can use to declare variables. There are 2-other keywords – let and var. All 3-keywords declare variables, but they’re slightly different from each other.

Const in JavaScript

The const keyword was introduced in ES6 to allow create a block scope variables, same as let. In JavaScript, const does not mean constant, it means one-time assignment.

It allow to create an immutable and mutable variables. Immutable variables means, variables whose values cannot be modified(change) in programming are known as immutable, while values that can be changed are known as mutable.

# Declaring JavaScript Const Variables:

Syntax :

Let’s see the syntax of const keyword :

 ➤ Syntax :

<script>
    const variable_name = value;
</script>
Parameter :
  • const : JavaScript reserved keyword.

  • var_name : Name of constant variable

  • value : Required, Initializing constant value.

Note : A variable declared with const must be initialized.

# immutable and mutable variable in const

It does't define a constant value. It defines a constant reference to a value. Because of this, we can't change constant primitive values, but we can change the properties of constant objects or array.

Let's see an example of immutable variable in const :

 ➤ Example 1 : Immutable variable;

<script>
    const x=25; 
    x++; //ERROR, not allowed
    x= 20;//ERROR, not allowed
    x= x+5; //ERROR, not allowed
</script>

Let's see an example of mutable variable in const :

 ➤ Example 2 : Mutable variable;

<script>
    //You can create a const object
    const student = {name:"Ankaj", branch:"CS"};

    //You can change a property
    student.name = "Ankaj Gupta";  //Allow

    //You can add a property
    student.rollno = "45"; //Allow
</script>

# Scope of const keyword :

1.) Global scope :

  • Using const keyword to define variable globally. Once you define globally, and access anywhere inside your code.

 ➤ Example : Variable scope globally;

<script type="application/javascript; version=1.7">
    const x=1; //'x' is gloabal variable;
     console.log("Start program :",x);
    function display()
     {
        if(true)
         {
          console.log("Inside block :",x); //x visible 
         }
         console.log("Inside function :",x); //x visible
     }
     display(); //calling JavaScript function
     console.log("End program :",x); //x visible
</script>

2.) Local scope :

  • Using const keyword to define variable locally (local scope). It can't be accessed outside the function declaration.

 ➤ Example : Variable scope within function;

<script type="application/javascript; version=1.7">
   function display()
     {
       const a =10;
       console.log("Inside function : "+a); //Inside function :10
     }
     display();
    //ReferenceError: a is not defined
     console.log("outside function : "+a);
</script>

3.) Block scope :

  • Variables declared with const keyword inside a block { } , can't be accessed from outside the block. When you try to access from outside of block, It will get a ReferenceError.

 ➤ Example : variable scope within block;

<script type="application/javascript; version=1.7">
  const age = 22;
  if (age > 21)
    {
      const message ="Hello";
      console.log("Inside block, message : ",message); //Hello!
    }
    //ReferenceError: message is not defined
    console.log("Outside block : ",message);
</script>

# Variable Hoisting :

Variable defined with ‘const’ keyword are not hoisted to the top. So if you try to accessed the variable before declaration it, javascript throw a Reference Error.

Note : Because you can not re-assign a const, you know it is not possible to hoist them.

Let's try to create an exaple :

 ➤ Example : Variable hoisting with const;

    Variables declared with const are not hoisted to the top.

<script>
    console.log(name); //ReferenceError
    const name = "Ankaj";
</script>

 ➤ Read more :

Read more about Variable Hoisting : Click Me


Important point's of const keyword in JavaScript :

  • Assigned when Declared : The const variable must be both declared and initialised. If you don't assign variables value at declaration time, It will give the SyntaxError.

 ➤ Syntax :

<script>
    const constant_name = value;
</script>

 ➤ Example Incorrect : Variable declared without initialization;

    You need to initialize it with a value when declaring otherwise will have the SyntaxError.

<script>
    const name;  //SyntaxError: Missing initializer in const declaration
</script>

 ➤ Example correct : Variable declared with initialization;

<script>
    const name= "Ankaj";
</script>
  • Block-scope : Variables declared with const keyword inside a block { } , can't be accessed from outside the block. When you try to access from outside of block, It will get a ReferenceError.

 ➤ Example :

    Variables declared with the const keyword have Block Scope.

<script>
    if(true)
    {
      const a=10;
      document.write(a); //Outpt : 10
    }
    document.write(a); //ReferenceError: a is not defined
</script>
  • Variable Re-declaration : Unlike var, Constant variable can't declare the same variable more than one time using ‘const’ keyword within the same scope. When we try to redefine, It will get a SyntaxError.

 ➤ Example : variable re-declaration in same scope;

    Re-declaring a variable with const, in same scope is allowed.

<script>
    const a = 10; 
    const a = 20; //SyntaxError: Identifier 'a' has already been declared
</script>

 ➤ Example : variable re-declaration in another scope;

    Re-declaring a variable with const, in another scope not allowed.

<script>
    const a = 10; //Global scope
    function display()
    {
      const a= 20; //Local scope
    }
    if(true)
    {
      const a= 25; //Block scope
      display();
    }
</script>
  • Variable value re-assigned : Variables declared with var or let can be changed later in the program. Once a const variable is initialized, its value can never be changed again, and it can’t be reassigned to a different value.

 ➤ Example : Re-assigned a new value;

    The code will throw an error when we try to re-assign the existing const variable.

<script>
    // Assign value to x variable
    const x=10;
    //Reassign variable with a new value
    x = 20; //TypeError: Assignment to constant variable.
</script>
  • Dynamic type : As you known, const variables can not be re-assign, that's why variables declared with const keyword are not dynamic type.

 ➤ Example : Dynamic type variables;

<script>
    consr myName = 'Ankaj Gupta';  //Ankaj Gupta
    myName= 100; //Error
    myName= true; //Error
</script>

# How to change const values in javascript ?

  • As you known, Variable declare with const keyword you can not change later in program, but this condition is apply only for constant primitive values not for constant object or array.

  • If you declare constant object or array value with const keyword, You can change or add the properties of const variables.

Let's see the examples :

 ➤ Example i : constant primitive values;

    If we assign a primitive value to a constant, we can't change the primitive value.

<script>
    const x=25; 
    x++; //ERROR, not allowed
    x= 20;//ERROR, not allowed
    x= x+5; //ERROR, not allowed
</script>

 ➤ Example ii : constant objects values;

    You can change the properties of a constant object.

<script>
    //You can create a const object
    const student = {name:"Ankaj", branch:"CS"};

    //You can change a property
    student.name = "Ankaj Gupta";  //Allow

    //You can add a property
    student.rollno = "45"; //Allow

    //Note : But you can't re-assign a constant object.
    student = {name:"Anmol", branch:"ECE"};  //ERROR, not allowed
</script>

 ➤ Example iii : constant array values;

    You can change the elements of a constant array.

<script>
    //You can create a constant array.
    const student = ["Name", "Branch", "Rollno"];

    //You can change an element.
    student[2] = "Enroll_No"; //Allow

    //You can add an element.
    student.push("Gender"); //Allow

    //Note : But you can't reassign a constant array.
    student = ["Name", "Branch", "Enroll_No", "Gender"];  //ERROR, not allowed
</script>
JavaScript
Read more
Ankaj Gupta
February 16, 2019
let keyword in javascript

let keyword is introduced in 2015(ES6). It is similar to var scope, and it allows the variable’s value to be changed during the course of the program execution.

Let in JavaScript

The let statement allows you to create/declared a block-scoped variable. Block-scoped means whenever a variable is created with let, it will only exist within its block(pair of curly braces).

It is similar to the variable we declare in other languages like : .NET, Java, etc.

# Declaring JavaScript let Variables:

Syntax :

Let’s see the syntax of let keyword :

 ➤ Syntax :

<script>
    let variable_name = value;
</script>
Parameter :
  • let : JavaScript reserved keyword.

  • var_name : Name of constant variable

  • value : ptional, Initial value assign at the time of declaration.


Let’s see an example of let keyword in JavaScript :

 ➤ Example :

<script>
    function display() {
       let a =10;
       console.log(a);   //Output : 10
       if(true) {
          let a=20;
          console.log(a); //Output : 20
        }
        console.log(a);  //Output : 10
     }  
    display();     
</script>

# Scope of let keyword :

1.) Global scope :

  • Using let keyword to define variable globally. Once you define globally, and access anywhere inside your code.

 ➤ Example : Variable scope globally;

<script type="application/javascript; version=1.7">
    let x=1; //'x' is gloabal variable;
     console.log("Start program :",x);
    function display()
     {
        for(x= 1; x< 5; x++) {
          console.log("Looping time :",x); //x visible 
         }
         console.log("Inside function :",x); //x visible
     }
     display(); //calling JavaScript function
     console.log("End program :",x); //x visible
</script>

2.) Local scope :

  • Using let keyword to define variable locally (local scope). It can't be accessed or modified outside the function declaration.

 ➤ Example : Variable scope within function;

<script type="application/javascript; version=1.7">
   function display()
     {
       let a =10;
       console.log("Inside function : "+a); //Inside function :10
     }
     display();
    //ReferenceError: a is not defined
     console.log("outside function : "+a);
</script>

3.) Block scope :

  • Variables declared with let keyword inside a block { } , can't be accessed from outside the block. When you try to access from outside of block, It will get a ReferenceError.

 ➤ Example : variable scope within block;

<script type="application/javascript; version=1.7">
  let age = 22;
  if (age > 21)
    {
      let message ="Hello";
      console.log("Inside block, message : ",message); //Hello!
    }
    //ReferenceError: message is not defined
    console.log("Outside block : ",message);
</script>

# Variable Hoisting :

Unlike var keyword, The variable declared using ‘let’ keyword is not hoisted. So if you try to use the variable before declaring it, javascript throw a Reference Error.

Let's try to create an exaple :

 ➤ Example :Variable hoisting with let;

    Variables declared with let are not hoisted to the top.

<script>
    console.log(name); //ReferenceError
    let name = "Ankaj";
</script>

 ➤ Read more :

Read more about Variable Hoisting : Click Me



Important point's of let keyword in JavaScript :

  • Variable access befor declaration : let variables are registered at the top of the block, But when the variable is accessed before declaration, JavaScript throws a ReferenceError.

 ➤ Example:

    let can't use variable before the declaration otherwise gives an error.

<script>
    document.write(x); //ReferenceError: x is not defined
</script>
  • Variable use without initialization : The let statement creates and initializes variables inside the block scope. If you don't assign variables value at declaration time, By default JavaScript automatically a declared assigns the undefined value.

 ➤ Example:

    A variable declared without a value will have the value undefined.

<script>
    let name;
    document.write(name); //undefined
</script>
  • Block-scope : Variables declared with let keyword inside a block { } , can't be accessed from outside the block. When you try to access from outside of block, It will get a ReferenceError.

 ➤ Example :

    Variables declared with the let keyword have Block Scope.

<script>
    for(let i=0; i<=5; i++ )
    {
      //write something
    }
    document.write(i); //ReferenceError: i is not defined
</script>
  • Variable Re-declaration : Unlike var, You can't declare the same variable more than one time using ‘let’ keyword within the same scope. When we try to redefine, It will get a SyntaxError.

 ➤ Example : variable re-declaration in same scope;

    Variables defined with let keywords can't be redeclared in the same scope.

<script>
    let a = 10; 
    let a = 20; //SyntaxError: Identifier 'a' has already been declared
</script>

 ➤ Example : variable re-declaration in separate scope;

    Variables defined with let keywords can be redeclared in the separate scope.

<script>
    let a = 10; //Global scope
    function display()
    {
      let a= 20; //Local scope
    }
    if(true)
    {
      let a= 25; //Block scope
      display();
    }
</script>
  • Variable value re-assigned : Variable data store in memory, which can later be accessed and modified (reassigned a new value).

 ➤ Example : Assigned a new value in given variable;

<script>
    // Assign value to x variable
    let x=10;
    //Reassign variable with a new value
    x = 20;
    console.log(x); //Output : 20
</script>
  • Dynamic type : Variables declared with let keyword are dynamic typing mean that, they can change from one data type to another data type.

 ➤ Example : Dynamic type variables;

    In this example, the variable myName change from string to number and then boolean.

<script>
    let myName = 'Ankaj Gupta';  //Ankaj Gupta
    myName= 100; //100
    myName= true; //true
</script>
JavaScript
Read more
Ankaj Gupta
February 14, 2019
Var in JavaScript

var keyword in JavaScript

The var statement is used to declare(Create) a variable. Until ES2015, var was the only only way to declare variable. Now there are two more options to declare variable: let and const.

Variables declared with var keyword have functional scope variable, This means whenever a variable is created with var in a function, it will only exist within the function.

# Declare variable

Let’s see the syntax of var keyword :

 ➤ Syntax :

<script>
    var variable_name = value;
</script>
Parameter :
  • var: JavaScript reserved keyword.

  • var_name : Name of variable.

  • value : Optional, Initial value assign at the time of declaration.

Note : let and const are block scoped variables. Block scope does not apply to var.

Let’s see the example of var keyword in JavaScript :

 ➤ Example :

    In this example, apple, mango, and totalFruits are variables.

<script>
    var apple = 8;
    var mango = 9;
          
    var totalFruits = apple + mango;
    document.write(totalFruits);
</script>
Output :

17



Scope of var keyword ?

1.) Global scope :

  • Using var keyword to define variable globally. Once you define globally, you can access anywhere inside your code.

 ➤ Example : Variable scope globally;

<script>
    var x=1; //'x' is gloabal variable
     console.log("Start program :",x);
    function display()
     {
        for(x= 1; x< 5; x++ )
         {
          console.log("Looping time :",x); // x visible on here
         }
         console.log("Inside function :",x); // x visible
     }
     display(); //calling JavaScript function
     console.log("End program :",x); // x visible
</script>

2.) Local scope :

  • Using var keyword to define variable locally (local scope). It can't be accessed or modified outside the function declaration, Function parameters are always local to that function

 ➤ Example : Variable scope within function;

<script>
   function display()
     {
       var a =10;
       console.log("Inside function : "+a);
     }
     display();
    // Uncaught ReferenceError: a is not defined
     console.log("outside function : "+a);
</script>

3.) Block scope :

  • Using var keyword, If you declare variable inside the block{ } statement, the variable can be accessed from outside the block.

 ➤ Example : Variable scope within block;

    Variables declared with the var keyword are not Block Scope.

<script>
  var age = 22;
  if (age > 21)
    {
      var name ="Ankaj Gupta";
      console.log("Inside block, name : ",name);
    }
    console.log("Outside block : ",name);   //name visible on here
</script>

# Variable Hoisting :

Variables declared with var are hoisted to the top of the enclosing function scope. If the variable is accessed before variable declaration, it evaluates to undefined.

Let's try to create an exaple :

 ➤ Example :

    Variables declared with var keyword are hoisted.

<script>
    console.log(name); //undefined
    var name = "Ankaj";
</script>

 ➤ Read more :

Read more about Variable Hoisting : Click Me


Important point's of var keyword in JavaScript :

  • Variable use without initialization : The var statement creates and initializes variables inside the scope. If you don't assign variables value at the declaration time, By default JavaScript automatically a assigns the undefined value.

 ➤ Example:

    A variable declared without a value will have the value undefined.

<script>
    var name;
    document.write(name); //undefined
</script>
  • Block-scope : Variables declared with the var keyword are not Block Scope.

 ➤ Example :

<script>
    for(var i=0; i<=5; i++ )
    {
      //write something
    }
    document.write(i); //Output :6
</script>
  • Variable Re-declaration : You can declare the same variable more than one time and also can be updated/modified.

 ➤ Example : Redeclaration of variable;

<script>
    var fruitsName = 'Apple';
    var fruitsName = 'Mango';
    console.log(fruitsName); //Output : Mango
</script>
  • Variable value Re-assigned : Variable data store in memory, which can later be accessed and modified (reassigned a new value).

 ➤ Example : Assigned a new value in given variable;

<script>
    // Assign value to x variable
    var x=10;
    //Reassign variable with a new value
    x = 20;
    console.log(x); //Output : 20
</script>
  • Dynamic type : Variables declared with var keyword are dynamic typing mean that, they can change from one data type to another data type.

 ➤ Example : Dynamic type variables;

    In this example, the variable myName change from string to number and then boolean.

<script>
    var myName = 'Ankaj Gupta';  //Ankaj Gupta
    myName= 100; //100
    myName= true; //true
</script>
  • When using var local scope is within a function, means that a variable with the same name can be used in two separate functions, because each is recognized only by the function in which it is declared.

 ➤ Example :

<script>
    function myFunction()
     {
       var data = "I am local scope";
       document.write(data); //Output: I am local scope
     }
    function display()
     {
       var data = "I am  also local scope";
       document.write(data); //Output: I am also local scope
     }
    myFunction();
    display();
</script>
JavaScript
Read more
Ankaj Gupta
February 14, 2019
Function hoisting in JavaScript

JavaScript Function Hoisting

Function hoisting means that functions are moved to the top of their scope, Which means you can call functions before they are declared in your code.

There are 2-ways of creating functions in JavaScript :

  1. Function declarations.

  2. Function expressions.

Let's see the following example of function hoisting :

1.) Function declarations :

As you can see, we called the message() function before it is defined, but the code still works. This is because the function declaration is moved to the top automatically behind the scenes.

 ➤ Example 1 : Function declaration before hoisting;

<script>
    //Calling function before declaration
    message(); //Outputs: Hello, I am hoisted!
    function message()
     {
       document.write("Hello, I am hoisted!");
     }
</script>

Behind the scenes, this is how the JavaScript interpreter looks at the above code, Javascript compiler change Example 1 to Example 2.

 ➤ Example 2 : Function declaration after hoisting;

<script>
    function message()
     {
       document.write("Hello, I am hoisted!");
     }
    message(); //Outputs: Hello, I am hoisted!
</script>

2.) Function expressions :

  • Function expressions, are not hoisted.

 ➤ Example :

<script>
    message(); //TypeError: message is not a function
    var message = function()
     {
       document.write("Hello, I not am hoisted!");
     };
</script>

Example explanation :

As we can see above, the variable declaration var message is hoisted but it's assignment to a function is not. Therefore, the intepreter throws a TypeError since it sees message as a variable and not a function.

Let's try the combination of a function declaration and expressions :

 ➤ Example :

<script>
    message(); //TypeError: message is not a function
    var message = function hoisting()
     {
       document.write("Hello, I not am hoisted!");
     };
</script>
JavaScript
Read more
Ankaj Gupta
February 14, 2019
JavaScript Variables Hoisting in Details

variable hoisting in JavaScript

Variable hoisting is a default behaviour in JavaScript where all variable declarations are moved to the top of the current scope (function scope or global scope) that the variable is defined within.

The typical JavaScript variable can be created in 2-stages : declaration and initialisation.

  • The declaration stage is where only variable reference is created, without any value. At this stage, if we try to access the variable value, we will get output undefined.

  • The initialisation stage is where the actual value is assigned to the variable.

Let’s see an example :

 ➤ Example :

    In this example, we can see the variable declaration stage, initialisation stage or both variable declaration & initialisation.

<script>
   var name; //Declaration
   name = 'Ankaj!’; //Initialisation
   var message = ‘Hello!’; //Declaration & Initialisation in one step
</script>



1.) Variable hoisting globally :

Let’s see an example of globally variable hoisting :

  • In this example, we can see in a normal scenario, when x is used before the declaration. In this case, it will give output 10 as excepted.

 ➤ Example 1 : Variable declaration before hoisting ;

<script>
   x=10; //Assign 10 to x;
   document.write(x); 
   var x; //Declare x
</script>

Let's take a look at how JavaScript interprets Example 1, how does it look after the hoisting process is finished. Javascript compiler change Example 1 to Example 2.

 ➤ Example 2 : Variable declaration after hoisting;

<script>
   var x; //Declare x, (Hoisted)
   x = 10; //Assign 10 to x
   document.write(x);
</script>

Example 2, Explanation :

In Example 2, we can see JavaScript hoisting behavior var x; is declared before the initialisation(x=10;). In this case, variable declarations are moved to the top.

Let’s see another example of variable hoisting :

 ➤ Example 3 :

<script>
   // ReferenceError: x is not defined
   console.log(x); 
</script>
  • At first in Example a, you may think that the sample code would throw a ReferenceError: on line 2 (console.log(name); because 'name' has not been declared yet.

 ➤ Example a : Variable declaration before hoisting;

<script>
   console.log(name); //undefined
    var name='Ankaj';
   console.log(name); //Ankaj
</script>

Let's take a look at how JavaScript interprets Example a, how does it look after the hoisting process is finished. Javascript compiler change Example a to Example b.

 ➤ Example b : Variable declaration after hoisting;

<script>
   var name; //Hoisted the declaration but not assignment
   console.log(name); //undefined
   name='Ankaj';
   console.log(name); //Ankaj
</script>

Example b, Explanation :

When the variable is hoisted, the declaration is moved to the top, but the initial value assignment remains in place, var name; is hoisted to the top of the scope, however the initial value assignment name = 'Ankaj'; is not affected.

2.) Variable hoisting locally :

 ➤ Example : Variable declaration before hoisting;

<script>
   var message="Document scope";
   function myMessage()
     {
       console.log(message); //undefined
       var message = 'Function scope';
       console.log(message); 
     }
     myMessage();
</script>

 ➤ Example : Variable declaration after hoisting;

<script>
   var message="Document scope";
   function myMessage()
     {
       var message; //This has been done by the javascript itself behind the scenes.
       console.log(message); //undefined
       message = 'Function scope';
       console.log(message); 
     }
     myMessage();
</script>

3.) Variable hoisting with block :

 ➤ Example : Variable declaration before hoisting;

<script>
    function display()
     {
       if(false)
        {
          var message = 'hello';
        }
        console.log(message); //undefined
     }
     display();
</script>

The variable message defined inside if block is visible to the outside block but within the function display() scope. This is because the JavaScript engine read the above code as following :

 ➤ Example : Variable declaration after hoisting;

<script>
    function display()
     {
       var message; //Hoisted the declaration but not assignment
       if(false)
        {
          message = 'hello';
        }
        console.log(message); //undefined but no reference error
     }
</script>

Javascript variables hoisting with var, let and const ?

Note : Variables and constants declared with let or const keyword are not hoisted.

Hoisting with var :

  • Variables declared with var are hoisted to the top of the enclosing function scope. If the variable is accessed before variable declaration, it evaluates to undefined.

 ➤ Example i : Variable hoisting with var;

<script>
    console.log(name); //undefined
    var name = "Ankaj";
</script>

In this example, name is accessed before declaration with var. In this situation the declaration is moved to the top.

Hoisting with let :

  • Variables declared with let are not hoisted.

 ➤ Example ii : Variable hoisting with let;

<script>
    console.log(name); //ReferenceError
    let name = "Ankaj";
</script>

Hoisting with const :

  • Variables declared with const are not hoisted.

 ➤ Example iii : Variable hoisting with const;

<script>
    console.log(name); //ReferenceError
    const name = "Ankaj";
</script>

JavaScript initialization are not Hoisted ?

  • The moving of var statements only applies to the declaration of a variable. If there's an initialization combined with the declaration, the initialization stays where it is, and declarations are moved to the top of the current scope.

JavaScript only hoists declarations not initializations, Let’s see an example :

 ➤ Example :

<script>
    console.log(name); //undefined
    var name = "Ankaj";
</script>
JavaScript
Read more
Ankaj Gupta
February 13, 2019
Javascript Hoisting

What is hoisting in JavaScript?

Hoisting is a mechanism in JavaScript, when the JavaScript interpreter moves all variable and function declarations to the top of the current scope.

It's important to keep in mind that only the javascript hoisting is applicable only for declaration not initialization. It is required to initialize the variables and functions before using their values.

There are 2-kinds of hoisting declaration in javascript.

  1. Variable hoisting.

  2. Function hoisting.

Note : Hoisting is done during the interpreter's first run through the code.

1.) Variable hoisting :

  • Variable hoisting is a default behaviour in JavaScript where all variable declarations are moved to the top of the current scope (function scope or global scope) that the variable is defined within.

Let’s see an example of variable hoisting :

In this example, we can see in a normal scenario, when x is used before the declaration. In this case, it will give output 10 as excepted.

 ➤ Example 1 : Variable declaration before hoisting ;

<script>
   x=10; //Assign 10 to x;
   document.write(x); 
   var x; //Declare x
</script>

Let's take a look at how JavaScript interprets Example 1, how does it look after the hoisting process is finished. Javascript compiler change Example 1 to Example 2.

 ➤ Example 2 : Variable declaration after hoisting;

<script>
   var x; //Declare x, (Hoisted)
   x = 10; //Assign 10 to x
   document.write(x);
</script>
Example 2, Explanation :

In Example 2, we can see JavaScript hoisting behavior var x; is declared before the initialisation(x=10;). In this case, variable declarations are moved to the top.

2.) Function hoisting :

  • Hoisting only applies to function declarations (not function expressions).

Let’s see an example of function hoisting :

 ➤ Example :

<script>
   //Calling function before declaration
    sayHello();
   function sayHello()
     {
       document.write("Hello, I am hoisted!");
     }
</script>
Output :

Hello, I am hoisted!

JavaScript
Read more
Ankaj Gupta
February 03, 2019
Variable Scope in JavaScript

What is Scope ?

Scope in JavaScript defines accessibility of variables, functions and objects.

It defines the lifetime and visibility of a variable, Every time we create a function or a block {} , we create a new scope.

Variable Scope :

Variable scope is the accessibility of variables, objects, and functions in some particular part of your code during runtime. In other words, scope determines the visibility of JavaScript variables and other resources in areas of your code.

Scope is how a computer keeps track of all the variables in a program, It refers to the specific environment where a JavaScript variable is accessible and can be used.

In JavaScript, there are 3-types of variable scope :

  1. Global variable - Global variable are those declared Globally(outside any function).

  2. Local variable - Local variable are those declared locally(Inside any function or Block).

  3. Lexical variable - Lexical scope is the ability of an inner function to access the scope of an outer function.

Note : Global variables can be accessed from anywhere in a JavaScript program.

1.) Global variable :

  • A global variable has global scope. Which means, it can be defined anywhere in your code.

  • JavaScript global variable is declared outside the function or declared with window object and it can be accessed and modified from anywhere in code.

  • Global variable always stored in memory even function execution finish, it always keep in memory or always accessible from anywhere in JavaScript code.

Let’s see the example of global variable in JavaScript:

  ➤ Example 1: Variable defined outside any function;

In this example below, we will create a global variable.

<script>
    //Initialize a global variable
    var data=100; //'data' is global variable
    function myFunction(){
      document.writeln(data);  // here can use data
    }
    function display(){
      // can also use data
    }
    myFunction(); //calling JavaScript function
</script>

When you declare a javascript variable outside the function, it is added in the window object internally. You can access it through window object also.

  ➤ Example 1.2: Variable access with window object.

<script>
    var data=100; 
    function display()
     {
       document.writeln(data);
       document.writeln(window.data);
     }
    display(); //calling JavaScript function
</script>

Declaring JavaScript global variable within function / Internals of global variable in JavaScript

  • To declare global variables inside function, you need to use window object.

  • Now it can be declared global variables inside any function and can be accessed from any function.

  ➤ Example 1.3: Global variable defined inside any function;

<script>
   function myFunction(){
      //declaring global variable by window object 
      window.data=100;   
   }
   function display(){
      //accessing global variable from other function
      document.writeln(window.data);
   }  
   myFunction();  //calling JavaScript function
</script>

When you declare variables if you are not specify, like : var keyword, automatically variable can consider global scope.

  ➤ Example 1.4: Auto global scope.

<script>
   function display()
     {
       //variable declaring without specify keyword
       data=100;
       document.writeln(data);
     }
    display();
    document.writeln(data);  //data is accessible on here
</script>
Output :

100

100


2.) Local variable :

  • A variable declared inside function is a local variable.It is usable only in a specific part of your code are considered to be in a local scope.

  • Local variable have local scope, It can't be accessed or modified outside the function declaration, Function parameters are always local to that function.

  • Local variable store in stack frame within function, while function start execution and removed from memory once it done with execution.

  • In JavaScript, there are 2-kinds of local scope :-

      i.) Function scope

      ii.) Block scope

Note : Local variables are created when a function starts and deleted when the function ends.

i.) Function scope :

  • Variables declared inside a function is known as Function scope. In JavaScript, Each function creates a new scope.

  • When you declare a variable within a function, the variable can accessed within that function. When you exit the function the variable is destroyed, that means they can’t be accessed from the outside function code.

Let's see an examples of function scope :

  ➤ Example: function scope;

<script>
   function myFunction()
     {
       var data = "I am local scope";
       document.write(data);
     }
     myFunction();
     document.write(data); //Uncaught ReferenceError: data is not defined
</script>

Note : Javascript functions have their own scope, But blocks scope such as :(if and switch conditions or for and while loops) do not.

ii.) Block scope :

  • A block scope variable is similar to a function scope, but is limited to a block instead of a function. Block is separated by curly braces { and }.

  • ES6 introduced const and let variables, unlike var variables. Both keywords allow us to scope to a block of code, they can be scoped to the nearest pair of curly braces.

  • When you declare a variable between curly brackets {} with const or let, it can access this variable only within that curly brace. That means, block scope variable can’t be accessed from outside that pair of curly braces.

  • Block statements like : for and while loops or if and switch conditions unlike functions, don't create a new scope.

Let's see an examples of Block scope :

 ➤ Example :

<script>
  for(let i=0; i<=5; i++ )
    {
       //write something
    }
    document.write(i); //i can not be used here;
</script>

Note : let and const are block scoped variables. Block scope does not apply to var.

Important point of Block scope :

  • Before ES2015 JavaScript did not have Block Scope.

  • Variables declared inside a block {} can not be accessed from outside the block.

  ➤ Syntax:

<script>
    {
      let x= 2;
    }
    document.write(x);  //x can not be used here;
</script>
Output :

ReferenceError: x is not defined

  • variables declared with var keyword inside a block {} , can be accessed from outside the block.

  ➤ Syntax:

Variables declared with the var keyword can not have Block Scope.

<script>
    {
      var x= 2;
    }
    document.write(x);  //x can be used here;
</script>
Output :

2

3.) Lexical scope :

  • Lexical Scope also known as (Static scope or Nested scopes) literally means that scope is determined at the lexing time (generally referred to as compiling) rather than at runtime.

  • Static scope means When a function is defined in another function, the inner function has access to the outer function's variables. This behavior is called lexical scoping.

Syntax :

 ➤ syntax : Nested scopes;

<script>
   function myFunction()
     {
       //local function scope;
       function innerFunction()
        {
         //nested local function scope;
        }
     }
</script>
Let's see the examples of Lexical scope :

 ➤ Example :

<script>
   function myFunction()
     {
       const outer =I'm outer function!`;
       function innerFunction()
        {
         const inner =I'm  inner function!
         document.writeln(outer) 
        }
        innerFunction();
     }
    myFunction();
</script>
Output :

I'm outer function!

I'm inner function!

Why is Scope Important ?

  • The main benefit of scope is security.

  • The variables can be accessed from only a certain area of the code. Using the scope, we can avoid unintended modifications to the variables from other parts of the program.

  • It also reduces the namespace collisions occur when two or more variables share a common name.

JavaScript
Read more

Discover more amazing content below