In JavaScript, Variable is use to store data and allows operations as per data types. Data in a variable can be changed. Javascript is a loosely typed, weakly typed or untyped scripting language. It means no need to define data type for a variable, variable can directly be used.

Before 2015, var keyword is used to declare a variable, In 2015, as per ECMAScript 2015 (ES6) two new keyword were introduced, let and const. Now, javascript allows 4 different ways to declare a variable.

  1. var
  2. Automatically
  3. let
  4. const

Declaring a variable in javascript

Using var

Syntax

var variable_name;

Example

<script>
 var a;
</script>

To declare a variable using var keyword, Inside script tag, write var keyword and then space and then variable name, as given in above example.

using let

Syntax

let variable_name;

Example

<script>
 let a;
</script>

To declare a variable using let keyword, Inside script tag, write let keyword and then space and then variable name, as given in above example.

using const

Syntax

const variable_name = initializer or value;

Example

<script>
const a = 10;
</script>

Automatically

In javascript, a variable can be declared without var, let and const keyword, such variable become automatic variables.

<script>
q  = 30;
</script>

Declaring more than one variable in single line in javascript

using var

<script>
var a = 20, name="yourshala", age="30";
</script>

using let

<script>
let a =30, name="yourshala", age="20";
</script>

using const

<script>
const a =40, name="yourshala", age="10";
</script>

Assign a value to a variable.

To assign a value to a variable = (assignment operator) is used.

using var

<script>
var a = 20;
alert(a);
</script>

using let

<script>
let a = 20;
alert(a);
</script>

using const

<script>
const a = 20;
alert(a);
</script>

Assign a variables value to another variable in Javascript

In Javascript, a variable value can be assigned to another variable, not to a const variable.

<script>
var a = 20;
var b = a;
alert(a);
</script>