What is a variable?
In javascript, all values are stored at some memory location.
Now, a user can not directly access a memory location hence variables are used.

A variable is a user defined name that is used to access a memory location. Using a variable, you can store or modify a value at the memory location.
Example,
variables in javascriptAbove illustration declares two variables(digit and lang) pointing to different memory locations having different values.

How variables are declared?
Variables in javascript are declared using var keyword followed by the name of variable which can be any user defined name.
Example,

var digit = 5;
var lang = 'javascript';

ES6(or ECMAScript6) introduced a different way of declaring variable.
It suggests using let keyword in place of var.

Thus, above variable declarations can be modified as below.

let digit = 5;
let lang = 'javascript';

If the variable value will never change after initialized for the first time or you do not want it to be changed accidentally, then use const in place of let.

Javascript engine will not allow modification in variable values declared with const. Example,

const digit = 5;
digit = 10;   // Illegal

Variable naming rules
Though a variable can be a user defined name but there are few rules that should be followed while declaring a variable.

They are
1. A variable name can not begin with a number.
Thus, 12digit, 0lang are invalid variable declarations. Variable names should begin with a letter or underscore. Examples, _start, digit123, technology etc., are valid variables.

2. A variable name can not be a javascript keyword or a reserved word(explained below).

Variables in javascript are case-sensitive.
Thus, language, Language, languagE are three different variables.
Keywords
A keyword, also called reserved word, is a word which has some special meaning in the language syntax.
When a keyword is encountered, javascript engine performs some action that is specific to that keyword.
Example, break is a keyword.
When javascript engine finds this keyword, it terminates an executing loop.

A keyword cannot be used as a variable name, function or class name in javascript.
Following are the keywords in javascript.

abstract boolean break byte case catch
char class const continue debugger default
delete do double else enum export
extends false final finally float for
function goto if implements import in
instanceof int interface long native new
null package private protected public return
short static super switch synchronized this
throw throws transient true try typeof
var void volatile while with

Leave a Reply