Tutorials Tonight's Logo

JAVASCRIPT VARIABLE


What is Variables Javascript

Variables are the base constructs of any programming language. Variables are like some container that can store data / values like text, number etc.

Variables can be defined, can be assigned value, value can be altered and can use stored value later by referring to the name of the variable.

In javascript, variable is defined by using var, but in the newer version of javascript (ES6) it has introduced two new keywords for defining variable let and const.

Lets see how to create variables in javascript.

var text; // defining variable
text = "Hello, World!"; // assigning value to variable

Variable Naming Convention

Variable names can be simple like x, y or can be more clear like bookName. Every variable name should be unique.

There are some rules that need to be followed while giving name to the variable.

  • Variable names can contain numbers and digits (A-Z,a-z).
  • Only two special characters are allowed in variable names $ and _ .
  • Reserved words can't be used as variable names like let, class, true etc.
  • letters can't start with numbers.

Note: Variable names are case sensitive. so the variable name "Bob" and "bob" are different.

var 1abc; // invalid
var $ = 5; // valid
var _ = "hello"; // valid
var cat123$ = "Some cats"; // valid
var dog@12 = "Some Dog"; // invalid
var abc = 10;
var Abc = 11;
// abc and Abc are different

Let and Const in Javascript

let and const are the new keyword in javascript that came with ES6. These two keywords are used to define variables in javascript.

scope of let and const are at block { } level. const is similar to let but it can't be reassigned once assigned a value. const is generally used to declare constant variables.

let a = 5;
let x = "hello";
const PI = Math.PI;
const b = 100;
b = 15; // will show error because it is const can't reassign value

Follow Us

Copyright © Tutorials Tonight. All Rights Are Reserved.