What is the reason for allowing var to declare duplicates, while const and let restrict duplicate declarations?

What is the reason behind var allowing duplicate declaration while const and let do not?

var allows for duplicate declarations:

xx=1;
xx=2;
console.log(xx+xx);//4

var xx=1;
var xx=2;
console.log(xx+xx);//4

 

However, let and const do not allow for duplicate declarations:

const yy=1;
const yy=2;
console.log(yy+yy);//Uncaught SyntaxError: Identifier 'yy' has already been declared",

let zz=1;
let zz=2;
console.log(zz+zz);//Uncaught SyntaxError: Identifier 'zz' has already been declared",

I came across an explanation on this page which states,

Assuming strict mode, var will let you re-declare the same variable in the same scope. On the other hand, let will not.

But why exactly do let and const not allow re-declaration? And why does var behave differently? How does JavaScript manage these three types of declarations?

Answer №1

Understanding Variable Declaration

Prior to 2016, the var keyword was used exclusively for defining variables.

When you use var x, the variable x is treated as if it were declared at the top of the enclosing scope (which is typically a function).

All declarations of the same variable within the same scope refer to the same variable due to hoisting.

An example illustrates this concept: within a function, declaring an inner variable with the same name as an outer variable does not affect the outer variable.

var name = 'Ramesh';

function myFunc() {
    var name;

    name = 'fenton';

    name = 'Fenton';

    alert(name);

}

myFunc();

alert(name);
  • Implicit declaration without using the var keyword adds variables to the global scope, leading to potential bugs.

The Introduction of let and const

The let and const keywords introduce block-scoped variables, offering clarity similar to other C-like languages.

These keywords promote disciplined programming by encouraging single declarations within blocks.

const prevents re-assignment after initialization, although the value itself can still mutate.

const x = [];

// Even though re-assignment is disallowed, mutation is possible
x.push('Fenton');

// x now contains ['Fenton']

Why Use let and const?

To avoid confusion with var's hoisted behavior and function-scope, embrace the advantages of const and let.

By default, prioritize const and only switch to let when re-assignment is necessary.

Answer №2

Contrary to var, the introduction of let was part of the ES2015 specification. According to the details outlined in the documentation:

If you attempt to redeclare the same variable within the same function or block scope, a SyntaxError will be thrown.

This change was implemented to enhance scoping compared to traditional var.

Answer №3

What is the reason behind const and let not allowing duplicate declarations?

There is a significant distinction in how c# or java handle duplicate variable names compared to an interpreted language like js. In these languages, name collision results in a compilation error, whereas in js it works differently. Take a look at the code snippet below: Is the value of i duplicated? Not exactly, as in the function and block context, the same variable name can refer to two different variables depending on where they are declared.

function checkLetDuplication() {
  let i = 'function scope';
  for ( let i = 0 ; i < 3 ; i++ )
  {
    console.log('(for statement scope): inside the for loop i, equals: ', i);
  }
  console.log('("checkLetDuplication" function scope): outside the for loop i , equals: ', i);
}
checkLetDuplication();

Answer №4

If you are curious about whether this behavior aligns with the specifications, refer to section 13.3.2

Under any VariableEnvironment scope, a single BindingIdentifier may be present in multiple VariableDeclaration statements, but these declarations collectively refer to a single variable.

let and const are newer additions, while var has been around since the early days of Javascript.

In the past, Javascript codebases were not typically large enough to worry about programming errors, with more focus on ensuring that JS engines handled variable re-declarations without reporting errors.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

`Is there a way for Javascript to retrieve information sent from Python Flask's render_template() method?`

Issue: I am facing difficulties in retrieving and displaying the data that I send from Javascript code when the user visits the site's landing page. The data in question is a dataframe. Backend Python Code: from flask import Flask, render_template, ...

Using a JSON file as a variable in JavaScript

Hello there everyone! I am looking to create a multilingual landing page. The idea is to have a language selection dropdown, and when a language is chosen, JavaScript will replace the text with the corresponding translation from a JSON file. However, I a ...

How to Efficiently Organize OpenAI AI Responses Using TypeScript/JavaScript and CSS

I'm using a Next.js framework to connect to the OpenAI API, and I've integrated it seamlessly with an AI npm package. The functionality is incredible, but I've encountered an issue regarding line breaks in the responses. You can find the AI ...

Is there a simple method to submit to a URL without relying on ajax?

When it comes to using jQuery, the $.ajax() function is typically used for POST requests to a URL. However, in my particular situation, I am unable to use this function. I need the client to send a POST request to a URL and have the server redirect the use ...

Tips for integrating execute_script and WebDriverWait in Selenium automation

Is there a way to combine execute_script() and WebdriverWait? In my current code: network_list = driver.find_element_by_xpath('//*[@id="folder_box"]/div[1]/div/div[2]/div[1]') wait = WebDriverWait(driver, 4) try: wait_network_list = wait.unt ...

Sending a request to a server from my local machine is resulting in a preflight request for 'Access-Control-Allow-Origin'

Encountered complete error: Error message - XMLHttpRequest cannot load . The response to the preflight request does not pass the access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' ...

I need assistance from someone knowledgeable in HTML and CSS. I am trying to create a div that dynamically increases its width until it reaches a specific

Seeking assistance to create a dynamic div that continuously expands its width until it reaches a maximum of 540px. It should start at 75px. Below is the HTML and CSS code I've attempted: .Loading-Screen { background-color: black; color: alicebl ...

Separate the iframe sessions

I am working with 6 iframes from the same domain but with different URLs and subdirectories. Each iframe sets a cookie with the same name but a different value using the HTML header "set-cookie". To prevent interference between these cookies, I need to fin ...

New feature alert! Introducing the Mentio JS menu now available at the bottom of the webpage

I am currently working on creating a Twitter-style @mention feature using Angular JS and a library called MentioJS. One issue I encountered is that after dynamically adding content to the page, a mysterious menu appears at the bottom of the page. This pro ...

Blank page shown when routing with Angular in Rails

Hey there, I'm currently attempting to integrate Angular into my Rails application and unfortunately I'm encountering a problem where the HTML page shows up blank. Here's the code I have so far: app/views/index.html.erb <body> ...

Issue with Z-index and wmode when using YouTube embed code on IE10

I am currently working on developing a div element that will prevent a YouTube video embedded in an iframe from playing when clicked. Instead, I want to trigger a JavaScript function upon user interaction. I have added the wmode=opaque parameter to the src ...

issues with the functionality of bootstrap modal

I'm currently working on a project where I need to set up a modal popup using bootstrap. The website I'm working on is organized by departments, so the only part of the code that I have control over is the main body of the site. I have included t ...

Having trouble getting the Bootstrap tooltip to work on a Select option?

Is there a way to have a tooltip displayed for each option in the select box? <select ng-model="rightList" class="form-control" size="13" multiple> <option ng-repeat="item in selectedList" value="{{$ ...

React code to automatically scroll to the top of the page when the user clicks the

Whenever the URL changes or the page is reloaded in my project, I need it to scroll back to the top. While most scenarios work fine, I'm encountering an issue with the browser's back button. Despite a change in the pathname, the page fails to scr ...

Sequentially animate objects with a fade-out and fade-in effect

Attempting to achieve a fade-out, fade-in animation using JavaScript and CSS. Here is the CSS animation code: @keyframes fade-in{ 0%{ opacity: 0%; } 100%{ opacity: 100%; } } @keyframes fade-out{ 0%{ opacity: 100%; } 100%{ opacity: 0%; } } Impleme ...

What are the steps to add ngMapHilight to an Angular project that is already set up

I recently downloaded the angular-maphilight.js and angular-maphilight.min.js from a source repository and inserted them into my Angular project. However, I encountered issues as it did not function properly. Whenever I attempted to use ngMaphilight with ...

Exploring each list item within the specified unordered list

Here is a basic code snippet: var ulreq = $("#abc").children("ul.ghi"); var lists = ulreq.find("li"); for( var i = 0; i < lists.length; ++i){ alert(lists[i].text()); // Display the values in these li }<script src="https://ajax.googleapis.com/ajax ...

Unable to suppress error in AngularJS $http.get() call when using catch() method

Below is a simplified version of the code I'm working with, running in CodePen for example: var app = angular.module("httptest", []); app.controller("getjson", ["$scope", "$http", function($scope, $http) { $http.get("https://codepen.io/anon/pen/L ...

"Utilize jQuery to superimpose an image on top of

I'm attempting to create a feature where clicking on an image will reveal text underneath, similar to how retailmenot.com displays coupon codes. In addition, when the image is clicked, users should be directed to an external URL. Here is an example o ...

AWS Lambda applies quotes to create the event input

I'm encountering a problem with my Python 3.8 AWS Lambda function that is meant to handle form inputs from a web application. The data from the form inputs gets passed to the Lambda function and ends up in the event dictionary. However, lambda seems t ...