Why there is no error?

I have two js file.

app.js
utility.js

I have same variable declared in these two files.

var person=“John” // in app.js

var person=“Sandy” // in utility.js

I imported these two js files in index.html

why I don’t get syntax error in index.html complaining that same variable person is declared twice ?

because it is only declared once (per scope) regardless of whether you specify var on the front of one reference or all references

these are either two references to one field if they are both in the same scope or are references to two completely different fields if they are not in the same scope.

The var statement lets you play fast and loose with variables.

The const statement however will complain when you attempt to reassign a variable:

const person="John";
const person="Sandy";
// Uncaught SyntaxError: Identifier 'person' has already been declared

If you do plan to change the variable at some stage, you can use the let statement instead. Or you can use const to assign an object, where the parts within that object can be changed too. For example:

const data = {start: new Date(), elapsedTime: 0};
for (let i = 0; i < Number.MAX_VALUE; i += 1) {
    data.elapsedTime = new Date().getTime() - data.start.getTime();
    // how much patience have you got?
}

const and let are recent improvements to JavaScript that gives us block-scoping for variables, instead of function-scoping which has been the defacto standard with var statements.

1 Like

what do you mean by declared once (per scope) here ?

I have declared twice in two files.

var person=“John” // in app.js

var person=“Sandy” // in utility.js

This is twice.

This is confusing compared to other languages…

In other language e.g java …if you write …
String person=“John”
String person=“Sandy”
This is wrong.

JavaScript was designed to be tolerant about some programming issues, in order to make the language more accessible to less-skilled programmers.

Those two script files that you mentioned, the browser treats them as if they are all run together.

One important thing to note is that JavaScript started off being called LiveScript, and was only changed to be called JavaScript for reasons of diplomacy. The language has more in common with Lisp and Scheme than other languages such as Java or C++

1 Like

Thanks. That was very much helpful

Not a problem. Certain practices have been formed to help make code maintenance easier. For example, the IIFE (immediately invoked function expression) acts as a wrapper around your code, protecting it from unwanted external influence, and protecting the global namespace from being affected by your code.

(function () {
    var person="John" // in app.js
    ...
}());
(function () {
    var person="Sandy" // in utility.js
    ...
}());
console.log(person); // reference error
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.