Variables in JavaScript

In this JavaScript tutorial, we are going to learn about JavaScript variables.


What are Variables?

  • JavaScript variables act as a container that are used to store data.
  • In JavaScript let, var, and const are used to declare variables.


JavaScript Variable Naming Rules

JavaScript follows some rules to declare variables and these rules are:

  • JavaScript variable names can contain letters, digits, underscores, and dollar signs.
  • Variable names cannot start with a digit.
  • In JavaScript variable names are case-sensitive, which means that "GeeksHelp" and "geekshelp" are two different variables.

  • JavaScript variables must start with a letter, underscore, or dollar sign.

  • You cannot use reserved keywords as variable names, such as "var", "function", or "switch".

  • Variable names should not contain spaces or special characters (except for underscores and dollar signs).


JavaScript Variables

1). let

  • It is used to declare a block-scoped variable.
  • The 'let' keyword is introduced in ES6(ECMAScript2015). and it is an alternative to the 'var' keyword.

  • The value of let variable can be changed.

  • In different block, value can be different.

let x;

In this example the let is used to declare the variable and x is the variable name.


2). var

  • var keyword in JavaScript is also used to declare a variable.

  • Variables declared with var have function scope or global scope, depending on where they are declared.

  • Two variables name using var keyword cannot be the same.

var x;

In this example the var is used to declare the variable and x is the variable name.


3). const

  • const is used to declare a variable whose value will not be changed.

  • Variable using const must be initialized during the declaration.

  • The const keyword was also introduced in ES6. And const variables are block-scoped.

const x = 'Geeks Help';

In this example the const is used to declare the variable and x is the variable name and 'Geeks Help' is the value assigned to the x variable.


Difference Between let, var, and const in JavaScript

let

var

const

The scope of a let variable is block scope. Declare global scope variables. Declared with constant values.
Value can be changed. Value will be same in every block. It has global level scope.
Different block different value. Two variables name cannot be same. Declared using const keyword.


Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

Top Post Ad

Below Post Ad

Ads Section