How to prevent duplicate JavaScript Variables Declaration?


In this tutorial, we will look at a few ways to prevent duplicate JavaScript variable declarations and comparison between them from understanding which one is suitable in a given context.

The best way to prevent duplicate variable declaration is to avoid creating global variables.

Let’s move forward to discuss this.

Wrapping Code Within a Function

Here, the variables declared inside the function are not accessible outside the function and vice versa. Users can follow the syntax below for using this method.

Syntax

(function(){
   var varNam = "test";
}())

Here varNam is wrapped inside a function.

Example

In this program, we have a test variable wrapped inside a function. We can access it within the function. When the user tries to access this variable outside the function, we get an error in the catch block.

<html> <head> <title>A program that prevents duplicate variable declaration by wrapping code within a function.</title> </head> <body> <p id="prevDupInp"></p> <div id="prevDupOpWrap"> <p>Click this button to access the same variable outside the function</p> <button id="prevDupBtn" onclick="doAccessVariable()">Click Here</button> </div> <p id="prevDupOut"></p> <script> function displayInput() { (function() { var prevDupInpEl = document.getElementById("prevDupInp"); var prevDupInpDat = "variableName inside the function - "; var variableName = "test"; prevDupInpEl.innerHTML = prevDupInpDat + variableName; }()) } displayInput(); function doAccessVariable() { var prevDupOutEl = document.getElementById("prevDupOut"); var prevDupOutDat = "variableName outside the function - "; var prevDupBtnEl = document.getElementById("prevDupBtn"); try { prevDupOutEl.innerHTML = prevDupOutDat + variableName; } catch (e) { prevDupOutEl.innerHTML = prevDupOutDat + e; } prevDupOpWrap.style.display = "none"; } </script> </body> </html>

Using JavaScript use strict Directive

The use strict directive says that the JavaScript code must run in the strict mode. The strict directive is not a statement but rather a constant expression. Earlier JavaScript versions ignored this expression.

We can’t use undeclared variables when writing the code in strict mode. Except for IE9 and lower versions, all modern browsers support this JavaScript directive. Strict mode allows us to write a cleaner code as it throws errors when we use undeclared variables in the program.

The “use strict” is a string. To enable strict mode, we need to write this string at the beginning of our script. Writing, in the beginning, means that this has a global scope.

The advantage of using this JavaScript directive is that we get a safe code. The wrong syntaxes were ignored earlier. Say, for example, an incorrectly typed variable name becomes a global variable before. In strict mode, it will give an error for this variable, and we can rectify it. Strict mode is also used with functions.

Users can follow the syntax below for using this method.

Syntax

'use strict';
const v = "Strict";

Here, the first line in the syntax is the directive, and v is a variable that follows strict mode.

Example 

In this program, we have an undeclared variable named p. Without strict mode, we can display it in the output. We cannot display its value when the user opts for the strict mode. Rather it throws an error in the catch block.

<html> <head> <title>JavaScript program that prevents duplicate variable declaration using the JavaScript strict mode.</title> </head> <body> <p>Prevents duplicate variable declaration using the JavaScript strict mode</p> <p id="useStrictInp"></p> <div id="useStrictOutWrap"> <p>Click this button to enter strict mode</p> <button id="useStrictBtn" onclick="getStrictMode();">Click Here</button> </div> <p id="useStrictOut"></p> <script> var useStrictEl; var useStrictData; var useStrictWrap = document.getElementById("useStrictOutWrap"); function getStrictMode(){ "use strict"; try{ x = 10; useStrictData = "Undeclared variable in strict mode -
"
+ p; } catch(e){ useStrictData = "Undeclared variable in strict mode -
"
+ e; } useStrictEl = document.getElementById("useStrictOut"); useStrictEl.innerHTML = useStrictData; useStrictWrap.style.display = "none"; } function noStrict(){ y = 10; useStrictEl = document.getElementById("useStrictInp"); useStrictData = "Undeclared variable in normal mode -
"
+ q; useStrictEl.innerHTML = useStrictData; } noStrict(); </script> </body> </html>

Using the let keyword to declare variables with block level scope

We can use this method to prevent duplicate JavaScript variable declarations inside loops

We get a declaration warning when the same variable is used in more than one loop. We can use the keyword let to declare the variables to prevent this. The variable declaration using let gives a block-level scope.

Users can follow the syntax below to use this method.

Syntax

for(let j=0;j<3;j++){ 
   //block1
   for(let j=0;j <4;j++){
      //block2
   }
}

Here, we have two separate code blocks with distinct scopes..

Example

In this example, we have an outer loop with 4 lengths and an inner loop with 5 lengths. First, we try to display the loop using the var variable declaration. Here we get the loop value displayed once. Next user requests for let declaration. Here we get the loop value display 4 times. This is the correct loop execution here.

<html> <body> <p id="letDeclInp"></p> <div id="letDeclWrap"> <p>Click this button to use the let keyword</p> <button id="letDeclBtn" onclick="blockScope(true)">Click Here</button> </div> <p id="letDeclOp"></p> <script> function blockScope(isLet){ var letDeclSel = isLet ? "letDeclOp" : "letDeclInp"; var letDeclEl = document.getElementById(letDeclSel); var letDeclBtn = document.getElementById("letDeclBtn"); var letDeclWrap = document.getElementById("letDeclWrap"); var letDeclDat = isLet? "Same loop variable: 4 times outer loop and 5 times inner loop using let declaration - " : "Same loop variable: 4 times outer loop and 5 times inner loop using var declaration - "; if(isLet){ for(let j=0;j<3;j++){ for(let j=0;j<4;j++){ letDeclDat+= j; } letDeclDat+= "
"
; } } else{ for(var j=0;j<3;j++){ for(var j=0;j<4;j++){ letDeclDat+= j; } letDeclDat+= "
"
; } } letDeclEl.innerHTML = letDeclDat; if(isLet) letDeclWrap.style.display = "none"; } blockScope(false); </script> </body> </html>

This article helped us to learn to prevent duplicate variable declarations. First, we wrap the variable inside a function to avoid accessing it from outside.

Second, we use a strict JavaScript directive to prevent duplicate variables by throwing an exception.

The final method is to use the let keyword variable declaration in loops.

We suggest the function wrap method as the best approach.

Updated on: 14-Sep-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements