Open In App

How to Declare a Variable in JavaScript ?

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Variables are the heart of any programming language. In JavaScript, there are multiple ways available to declare a variable using different keywords like let, const, and var.

  • var: Before ES6 or ES2015, it was the only way to declare variables in JavaScript. It declares variables in the global scope.
  • let: It was introduced in ES6, It is used to declare variables in block scope.
  • const: It was also introduced in ES6 to declare the constant variable whose values are not going to change throughout the code.

Example: The below code shows how you can declare variables using these keywords.

Javascript




var name = "GeeksforGeeks";
console.log(name);
var name = "Virat Kohli"; // Allowed
console.log(name);
 
let desc = "A Computer Science Portal.";
// let desc = "26000 International Runs."; // Not Allowed,
// Error: Identifier 'desc' has already been declared
console.log(desc);
 
const workForce = 200;
console.log(workForce);
// const workForce; // Not Allowed,
// Error: Missing initializer in const declaration


Output

GeeksforGeeks
Virat Kohli
A Computer Science Portal.
200


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads