Skip to content
Related Articles

Related Articles

How to declare variables in different ways in JavaScript?

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 24 Nov, 2022
Improve Article
Save Article

In JavaScript, we can declare a variable in different ways by using different keywords. Each keyword holds some specific reason or feature in JavaScript. Basically, we can declare variables in three different ways by using var, let and const keywords. Each keyword is used in some specific conditions.

 

 

 

JavaScript var

JavaScript let

JavaScript const

Can be redeclaredCannot be redeclaredCannot be redeclared
Can be reassigned a valueCan be reassigned a valueCannot reassign the value
Only have global and function scopeCan have a block scopeCan have a block scope
Variables are hoisted on top and can be used anywhereVariables must be initialized before useVariables must be initialized before use
Can be redeclared anywhere in the programCan be redeclared inside a blockCan never be redeclared

JavaScriptvar: This keyword is used to declare variables globally. If you used this keyword to declare a variable then the variable can accessible globally and changeable also. It is good for a short length of codes, if the codes get huge then you will get confused.

Syntax:

var variableName = "Variable-Value;"

Example:

javascript




<script>
    var geeks = "GeeksforGeeks";
    console.log(geeks);
</script>


Output:

GeeksforGeeks

JavaScriptlet: This keyword is used to declare variable locally. If you used this keyword to declare a variable then the variable can accessible locally and it is changeable as well. It is good if the code gets huge.

Syntax:

let variableName = "Variable-Value;"

Example:

javascript




<script>
if (true) {
    let geeks = "GeeksforGeeks";
    console.log(geeks);
    }
      
    /* This will be error and 
       show geeks is not defined */
    console.log(geeks);
</script>


Output:

GeeksforGeeks

JavaScript const: This keyword is used to declare variable locally. If you use this keyword to declare a variable then the variable will only be accessible within that block similar to the variable defined by using let and difference between let and const is that the variables declared using const values can’t be reassigned. So we should assign the value while declaring the variable.

Syntax:

const variableName = "Variable-Value;"

Example:

javascript




<script>
    const geeks = "GeeksforGeeks";
    console.log(geeks);
</script>


Output:

GeeksforGeeks

 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!