Variable, scope, and memory

When we describe a variable in JavaScript, there is no limit to how much data this variable holds. The maximum is described by the browser's capacity depending on how much data it can hold. Let's take a look the following code:

var abc="xyz";

We can define a variable in JavaScript using the var keyword. We can define the value of a variable immediately or later. A variable that we define outside the boundary of a function is a global variable.

Tip

Creating too many global variables in JavaScript is a very bad approach. The major reason why global variables are discouraged in JavaScript is because in JavaScript, all the code shares a single global namespace, also JavaScript has implied global variables, that is, variables that are not explicitly declared in local scope are automatically included with global namespaces. Relying too much on global variables can result in conflicts between various scripts on the same page.

Every function in a script can access a global variable. When you define a variable in a function, then its scope is inside that function. Let's take a look at the following code snippet:

Function abc() {
  var xyz="abc";
}

Note

The scope of a global variable never stops during the execution of the whole page even it is not needed.

If you fail to write var inside the function, then this variable is considered as a global variable. If you define a variable with the same global variable name, then it will be considered as a global variable.

JavaScript dynamically allocates memory to variables. When the scope of these variables is dereferenced or finished, it is automatically removed from the memory by the garbage collector. So, its disadvantage is that the unwanted variables remain in the memory.

There are two ways to save memory:

  • Using the function scope
  • Dereferencing these variables manually

The use of the function scope is more appropriate as variables get dereferenced when the function ends, thus saving memory:

(Function (window, document, undefined) {
  varabc="abc";
}
(window, document);

Variable declaration

JavaScript variables can be identified by unique names. These unique names are known as identifiers. Variables in JavaScript are used to store information. Identifiers can be of any length and size, for example, a, b, myName.

When you declare a variable in JavaScript, the machine will save it in the memory so that you can store or retrieve data from memory when needed. Variable names should be unique in the script.

The rules to declare variable names in JavaScript are the same as those for identifiers, as discussed previously.

When a code starts its execution, it first processes the variable declaration. These variables can be declared globally as well as within a function. We can declare multiple comma-separated variables, for example:

var myName,myAddress,myContact;

When we store data into a variable, this process is called variable initialization. We can initialize a variable at the time of its creation or later when we want to use it, for example:

var a=1;
var b=2;
var c;
c=a+b;

Here, in this example, the variable a stores the value 1, and b stores 2, and then we create the variable c and define its value later.

The variable scope

A variable scope is a frame where a variable exists in a program. We can define a scope of a variable in a program. Basically, the scope is a set of methods, functions, and objects that we have access to.

There are two scopes of variables in JavaScript:

  • Local scope variables
  • Global scope variables

Local scope variables

A variable when defined inside a function is called a local scope variable, as this variable can only be accessed into this function. Function variables will be local to this variable.

Description

For a variable, which is defined in the local scope, a variable of the same name can be used in a different function. When a function starts, the local variable is created and when the function ends, the local variable is deleted. In JavaScript, always declare variables before using them; failing to do this will throw some exceptions. In a function, if you have a local and a global variable with the same name, then the local variable will get priority over the global variable. So, avoid using the same variable name. Let's take a look at the following code snippet:

function xyz() {
  varabc="xyz";
  document.write(abc);
}

Global scope variables

A global variable can be declared anywhere in a JavaScript program. They can be accessed from everywhere. A global scope variable remains in the memory throughout the execution of scripts on the page. This results in memory depletion.

Description

Basically, global variables are window objects. Global variables are generally defined outside of the function and all functions in a webpage can access this global variable. If you give some value to a variable which is not declared, then this variable will be considered as a global variable. When you close a web page, the global variable will be deleted. For frontend developers in HTML, the window object is a global variable.

var abc="xyx";
functionmy Function() {
  //some code
}

Primitive and reference values

There are two types of values a variable can have:

  • Primitive type values
  • Reference type values

Primitive type values

Generally objects are aggregated from properties and those properties can be used to reference the object. Primitive (value, data type) is not an object and has no methods associated to it.

Description

In JavaScript, there are five types of the primitive type: string, number, null, undefined, and Boolean. A primitive value is stored directly in the stack. These values are stored in the same location from which they are accessed. Because of its fixed size, it can be easily manipulated.

Reference type values

Reference type values are specialized objects similar to arrays and functions stored in a heap. A pointer is used to locate their location into the memory.

Description

In JavaScript, a variable holding a reference type value is stored in the heap memory. These objects cannot be easily manipulated because they contain arbitrary elements and properties. When a reference value is passed to a function, the function modifies its values or contents, and that change can be seen by the object, which calls the function and other functions that have references to the object.

The execution context and scope

The scope and context are not the same things. Every function in JavaScript has a scope and a context. When we declare a function in JavaScript, this function can be accessed in different and various contexts and scopes. JavaScript follows design patterns for scopes and context.

The main difference between a scope and context is that scope is function based and context is object based. The scope is used to access a function when it is invoked. Whereas the context is used with the this keyword, so it is basically a reference type.

The scope is associated with the execution context when the execution context starts. There is a chain of scope with it, for example:

function first() {
  second();
  function second() {
    third();
    function third() {
      fourth();
      function fourth() {
        // do something
      }
    }
  }
}
first();

In JavaScript, the environment in which the code is executed is classified into the following:

  • Global code
  • Function code
  • Eval code

The global code

The global code is a default environment where the code is executed for the first time, that is, the external .js files and local inline code are loaded.

The function code

The function code is the environment in which flow control enters the function body during the code execution. Every return from the function exits the current execution context.

The eval code

The code is supplied to built-in eval functions. The eval code calls the context and creates an execution context.

For example:

var eval_context = { a: 10, b: 20, c: 30 };
function test() {
   console.log(this);
}
function evalInContext() {
   console.log(this);        // { a: 10, b: 20, c: 30 }
   eval("test()");      // { a: 10, b: 20, c: 30 } inside test()
}
evalInContext.call(eval_context);

In this example you call the function with the context you want and run eval within that function.

Garbage collection

There is no separate memory management in JavaScript. A browser decides when a cleanup is needed. Garbage collection is basically knowing if the variables are still being used or will be used in future throughout the program execution and if not collect and remove them. In simple words, the track of reference made to an object is kept in background. once it becomes idle or reaches zero it can be collected by the GC.

We can clean memory manually, but in some cases, there is no need for manual memory cleaning. We cannot force JavaScript to clean memory because this task is done on runtime by the garbage collector. Some heavy applications, such as computer games, require a lot of memory and slowdown your system; so, in this case, it only depends on your code and how you structured your application code for use of computer memory.

You can structure your code by following these steps:

Objects

When you declare an object, try to reuse that object by deleting its properties and restoring it to an empty object such as {}. This process is known as recycling the objects. When an object is created for the first time (new foo();), memory is allocated to it. So, if an object is already declared, we can reuse it in our script.

Arrays

When you use an array in your script, clear that array after using it. Assigning [] to an array is often used as a shorthand to clear it, but it actually creates a new empty array and garbages the old one. You can set the array length to 0, (arr.length = 0;); this will also clear the array but while reusing the same array object.

Functions

When you need to call a function more than one time, then you can optimize our code by assigning a permanent variable to the function rather than calling it again and again.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.107.229