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
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
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
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
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
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
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
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
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
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
Ankaj Gupta
February 14, 2019

JavaScript Variables Hoisting in Details

Variable Hoisting in JavaScript

Variable hoisting is a default behavior in JavaScript where all variable declarations are moved to the top of the current scope (function scope or global scope). Understanding hoisting is crucial for writing bug-free JavaScript code.

Understanding Variable Creation

JavaScript variables are created in two stages: declaration and initialization.

Declaration Stage

Only variable reference is created without any value. Accessing it returns undefined.

Initialization Stage

Actual value is assigned to the variable.

var name;           // Declaration
name = 'Ankaj';    // Initialization
var message = 'Hello!';  // Declaration & Initialization in one step

1. Global Variable Hoisting

Example 1: Before Hoisting

In this example, x is used before declaration, which outputs 10:

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

After Hoisting

JavaScript compiler internally changes the code to:

var x;             // Declare x (Hoisted)
x = 10;           // Assign 10 to x
document.write(x);

Explanation: The declaration var x; is hoisted to the top, but the assignment stays in place.

Example 2: Undefined Output

Accessing a variable before it's initialized returns undefined:

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

After Hoisting

var name;           // Hoisted declaration
console.log(name);  // undefined
name = 'Ankaj';     // Assignment stays
console.log(name);  // Ankaj

Key Point: Only the declaration is hoisted, not the initialization. The assignment stays where it is.

2. Local Variable Hoisting

Hoisting also works within function scope:

Before Hoisting

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

After Hoisting

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

Note: Local variables are hoisted to the top of their function scope, shadowing outer scope variables.

3. Variable Hoisting with Blocks

Variables declared with var inside blocks are hoisted to the function scope:

Before Hoisting

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

After Hoisting

function display() {
    var message;           // Hoisted to function scope
    if(false) {
        message = 'hello';
    }
    console.log(message);  // undefined (no ReferenceError)
}
display();

Important: The variable message is visible outside the if block but within the function scope.

Hoisting with var, let, and const

Variables and constants declared with let or const are NOT hoisted in the same way:

var (Hoisted)

Variables are hoisted to the top of scope. Accessed before declaration returns undefined.

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

let (Not Hoisted)

Variables are NOT hoisted. Accessing before declaration throws ReferenceError.

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

const (Not Hoisted)

Constants are NOT hoisted. Accessing before declaration throws ReferenceError.

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

Quick Comparison Table

Keyword Hoisted Before Declaration Scope
var ✅ Yes undefined Function/Global
let ❌ No ReferenceError Block
const ❌ No ReferenceError Block

JavaScript Only Hoists Declarations, Not Initializations

The moving of var statements only applies to the declaration. If there's an initialization combined with the declaration, the initialization stays where it is.

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

Remember: Only var name; is hoisted, not the assignment name = "Ankaj".

Best Practices

✅ Do's

  • • Always declare variables at the top of their scope
  • • Use let and const instead of var for better behavior
  • • Initialize variables when declaring them
  • • Understand scope to avoid unexpected behavior

❌ Don'ts

  • • Don't rely on hoisting behavior
  • • Don't access variables before they're declared
  • • Avoid using var in modern JavaScript
  • • Don't redeclare variables with different keywords

Summary

Variable hoisting is JavaScript's behavior of moving declarations to the top of their scope. Only var declarations are hoisted, while let and const are not.

Remember: JavaScript hoists the declaration, not the initialization. Understanding hoisting helps prevent bugs and write cleaner, more predictable code. Modern best practices recommend using let and const for better block scope behavior.

JavaScript
Read
Ankaj Gupta
February 13, 2019

Javascript Hoisting

What is Hoisting in JavaScript?

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

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

Types of Hoisting: 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 behavior 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.

Example 1: Variable Declaration Before Hoisting

In this example, we use x before declaration. It will give 10 as expected output:

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

Example 2: After Hoisting (How JavaScript Interprets It)

JavaScript compiler internally changes Example 1 to Example 2. Here's how it looks after the hoisting process:

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

Explanation: JavaScript hoisting behavior moves var x; declaration before the initialization (x = 10;). Variable declarations are moved to the top.

2. Function Hoisting

Hoisting only applies to function declarations (not function expressions). This means you can call a function before it's declared in your code.

Example: Calling Function Before Declaration

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

Output:

Hello, I am hoisted!

Function Declaration vs Function Expression

✅ Function Declaration (Hoisted)

// Works - hoisted
sayHello();

function sayHello() {
    console.log("Hello!");
}

Can be called before declaration

❌ Function Expression (Not Hoisted)

// Error - not hoisted
sayHello(); 

var sayHello = function() {
    console.log("Hello!");
}

Cannot be called before declaration

Hoisting with let, const, and var

Different variable declaration keywords behave differently with hoisting:

Keyword Hoisting Initial Value Temporal Dead Zone
var ✅ Yes undefined ❌ No
let ✅ Yes uninitialized ✅ Yes
const ✅ Yes uninitialized ✅ Yes

Example: let and const Hoisting Behavior

// ReferenceError: Cannot access 'x' before initialization
console.log(x);
let x = 10;

// ReferenceError: Cannot access 'y' before initialization
console.log(y);
const y = 20;

Temporal Dead Zone (TDZ): let and const are hoisted but remain uninitialized until their declaration line, causing a ReferenceError if accessed.

Complete Example: Variable and Function Hoisting

<script>
    // Calling function before declaration (works!)
    greet();
    console.log(myVar);  // undefined
    console.log(myLet);  // ReferenceError
    
    function greet() {
        console.log("Hello!");
    }
    
    var myVar = "I'm hoisted";
    let myLet = "I'm in TDZ";
</script>

How JavaScript sees it:

function greet() {  // Function hoisted
    console.log("Hello!");
}

var myVar;           // Variable hoisted, undefined
let myLet;           // Variable hoisted, TDZ

greet();
console.log(myVar);  // undefined
console.log(myLet);  // ReferenceError

myVar = "I'm hoisted";
myLet = "I'm in TDZ";

Best Practices

✅ Do's

  • • Always declare variables at the top of their scope
  • • Initialize variables when you declare them
  • • Use let and const instead of var
  • • Understand TDZ for let and const

❌ Don'ts

  • • Don't rely on hoisting behavior
  • • Don't use var in new code
  • • Don't access let/const before declaration
  • • Don't use function expressions before declaration

Summary

Hoisting is JavaScript's behavior of moving declarations to the top of their scope. Understanding this mechanism is crucial for writing predictable code:

  • Variable Hoisting: var variables are hoisted and initialized to undefined
  • Function Hoisting: Function declarations are fully hoisted and can be called before declaration
  • let and const: Hoisted but remain in Temporal Dead Zone until initialization
  • Function Expressions: Not hoisted like function declarations

For better code quality, always declare and initialize variables at the top of their scope and use let or const instead of var.

JavaScript
Read