JavaScript Variables

Variables in javaScript

Variable means anything that can be changed anytime. A JavaScript variable is the name of storage location. Variables can be used to store goodies, visitors, and other data. Every programming language use variables. We use variables as symbolic names for values in an application.

We can create variables using any of these keywords: ‘var’, ‘let’ and ‘const’. Don’t worry if many of these words are new to you. You will understand these terms later.

Local and Global Variables

There are two types of variables in JavaScript that can be represented and manipulated in a programming language: local and global.

A JavaScript local variables are declared inside function or block and accessible only within the function or block.

<script>  
  function localFunc(){  
  var x = 10;//local variable  
  alert(x);  //10  
  } 
 localFunc(); 
</script>

JavaScript global variables are accessible from any function: they can be declared outside the function or with window objects.

<script>      
      var globalVar = "some val"; //global variable           
      function globalFunc()
      {
         alert(globalVar); //global variable , result  is "some val"
      }  
globalFunc(); 
</script>

A local variable takes priority over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, it will hide the global variable. For instance:

<!DOCTYPE html>
<html>
  <body>
    <script type = "text/javascript">      
      var variable = "global variable";     
      function localVar( ) {
         var variable = "local variable";   
         console.log(variable);  //local variable

      }  
console.log(variable);   //global variable
      localVar();  
    </script>     
  </body>
</html>

The output in this function showVariables() shows that both global and local variables are available inside the function as we can console.log them.

<script>
      var globalVar = "global variable";    
      
      function showVariables() {

console.log(globalVar); //global variable

var localVar = "local variable";              		
console.log(localVar); //local variable
          };
      
      showVariables();
      
</script>

JavaScript variable names

You need to know about one very important thing when using variables. A variable name must have a clear and obvious meaning, when it describes stored data. Variable naming is one of the important and difficult skills in programming.

It’s much easier to find information, when the variables have good names, that’s why you should think about the right name for a variable.

Here are some good-to-follow rules for you:

  • Name must start with some letter (a to z or A to Z), underscore ( _ ), or dollar ( $ ) sign;
  • JavaScript variable names shouldn’t start with a numeral (0-9). We can use digits (0 to 9) after first letter or underscore character, for example value1 or _1value.
  • JavaScript variable names are case-sensitive. For instance, Name and name are two different variables.
  • Use human-readable names like firstName or lastName;
  • Escape abbreviations or short names like a, b, c, unless you really know what you’re doing;
  • Make names maximally descriptive and brief. The examples of bad names: data and value, because they don’t say nothing.

Examples of the correct JavaScript variables:

var x = 7;
alert(x); // 7  
var _value = "W3Docs";
alert(_value); // W3Docs

Examples of the incorrect JavaScript variables:

var  123 = 40;  //Unexpected number
var *aa = 250; //Unexpected token '*'

Datatypes in JavaScript

One of the important characteristics of a programming language is the set of data types it supports. That types can be represented and manipulated in a programming language. There are two main types of languages: statically typed language and dynamically typed language.

In statically typed language each variable and expression type is already known at assemble time. After declaring a variable in a determined data type, it can’t hold values of other data types. The examples of this type: C++, Java.

The other dynamically typed language, which can receive different data types over time. The examples are Ruby, Python, JavaScript etc.

JavaScript is dynamically typed scripting language, it also called loosely typed. So variables in javascript can receive different data types over time. Datatypes are the typed of data which can be used and manipulated in a program.

Types

The newest ECMAScript(ES6) standard defines 8 data types: 7 of them are Primitive.

  • Numbers: 10, 5.4, etc.
  • String: “Welcome to W3Docs” etc.
  • Boolean: Represents a logical operation and can have two values: true or false.
  • Symbol: This is for unique identifiers.
  • BigInt: It is for integer numbers of arbitrary length.
  • Null: Has only one value: null.
  • Undefined: A variable which hasn’t been assigned a value.

And one special type:

Object:The most important data-type for modern JavaScript.

We will learn about these data types in details in Data types.

Variable declaration in JavaScript

As we mentioned, there are 3 ways to declare a variable in JavaScript: let, const and var. Let’s explore them all in more detail:

Var

Var statement helps us to declare a variable, initializing it to a value. We can reset the values to the variables or redefine the variables as well. If you re-declare a variable, it won't lose its value. The syntax for this kind of declaration is:

var varName;  //without initializing
var varName = “Welcome to w3docs!”; //initialized with a string

You can declare multiple variables in a single line, separating them with commas.

Example of the var declare multiple variables:

var var1 = 20, var2 = “Welcome to W3Docs”,...;

// single variable
var varName;
//multiple variables
var name, title, num;

Example of the initialization of variables with var:

// initializing variables
var name = "Docs";
name = "W3Docs";

All the declarations in JavaScript are processed before program execution. So, declaring a variable anywhere is equal to declare it at the top of the code. It gives JavaScript a functionality to use the variables before their declarations in the code. This behavior of variables is called “var hoisting”.

But it is recommended in programming to declare the variables before we use them, as it will help you avoid unintended redeclaration of a variable.

Let

The let keyword has scope constraints. You can’t redeclare the let declared variables. If you try to do so, you will face a SyntaxError. The scope of these variables is the block they are defined in, it can be also any sub-blocks. In case you try to access these variables outside of their block, the browser will throw a ReferenceError.

let varName; //without initializing
let varName = “Welcome to W3Docs!” // initialized with a string

Example of the initialization of variables with let:

let user = 'Ann';
let age = 25;
let message = 'Welcome to W3Docs!';

Both var and let can be suitable in any given part of a program, depending on the circumstances.

Example of the var:

console.log(x);// undefined
var x=10;
console.log(x);// 5

Example of the let:

console.log(x); //Error
let x=5;
console.log(x);

Var instead of let

In older scripts you can meet another keyword: var instead of let:

var message = 'Welcome to W3Docs!';

In this case the var keyword is almost the same as let. It also declares a variable, but in another, old way.

There are fine differences between let and var, but we will talk about them in “var hoisting”.

Const

Const (constant) is block-scoped. It means that the const declaration creates a constant which scope can be either global or local to the declared block. The value of a constant is read-only. You can’t change it through reassignment and can’t redeclare it. A variable or a function in the same scope can’t have the same name as the variable.

It is a good practice for declaring your constants in uppercase, which will help programmers to separate the constants from other variables in the program.

const VARNAME = “Welcome to W3Docs”; // initialized with a string
const MYBIRTHDAY = '19.03.1986';
MYBIRTHDAY = '04.05.2003'; // error, can't reassign the constant!

Summary

There are two types of variables in JavaScript: local and global. They can be represented and manipulated in a programming language. Local variables are declared inside function or block. Global variables are accessible from any function.

We can declare variables by using the var, let, or const keywords.

  • let is a modern variable declaration.
  • var is an old variable declaration.
  • const is similar to let, but the value of the variable can’t be changed.

It’s important to name variables in a way that allows us to easily understand what’s inside them.

One more important characteristic of a programming language is the set of data types it supports. There are two main types of languages: statically typed language and dynamically typed language.




Do you find this helpful?

Related articles