Skip to content
Related Articles

Related Articles

Improve Article

How to declare variables in different ways in JavaScript?

  • Difficulty Level : Medium
  • Last Updated : 21 Jun, 2021

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 keyword. Each keyword is used in some specific conditions.
var: This keyword is used to declare variable globally. If you used this keyword to declare 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. 
 

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

  • Syntax: 
     
var variableName = "Variable-Value;"
  • Code: 
     

javascript




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

let: This keyword is used to declare variable locally. If you used this keyword to declare 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;"
  • Code: 
     

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

const: This keyword is used to declare variable globally. If you used this keyword to declare variable then the variable can accessible globally and it is not changeable. 
 

  • Syntax: 
     
const variableName = "Variable-Value;"
  • Code: 
     

javascript




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

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :