JavaScript Variables

JavaScript Variables

JavaScript Variables


Variables in JavaScript

Variable means anything that can be changed anytime. A JavaScript variable is the name of the 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.

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

function localFunc() {

  var x = 10; //local variable  

  console.log(x); //10  

}

localFunc();

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

var globalVar = "some val"; //global variable           

function globalFunc() {

  console.log(globalVar); //global variable , result  is "some val"

}

globalFunc();

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:

var variable = "global variable";

function localVar() {

  var variable = "local variable";

  console.log(variable); //local variable

}

console.log(variable); //global variable

localVar();

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

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 the 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 first name or last name;
  • 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 anything.

Examples of the correct JavaScript variables:

var x = 7;

console.log(x); // 7  

var value = "W3Docs";

console.log(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 type 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. 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 typed of data that 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 that 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 detail in Datatypes.

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 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 = 5;
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, the 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 varlet, 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.


Reactions

Post a Comment

0 Comments

close