6

Every time a modal is opened I load via ajax some html + js, like this:

var loadModalJs = function() {
   ...
}

$(function() { loadModalJs(); });

It works with var, but if I replace var with let, when the modal is closed and then opened again I get Identifier 'loadTabJs' has already been declared

I tried something like this, without success:

if(typeof loadModalJs === 'undefined') {
    let loadModalJs = function() {
       ...
    };  
}
loadModalJs(); // ReferenceError: loadModalJs is not defined

I don't like using var because my IDE complains about "'var' used instead of 'let' or 'const'"... But none of them seems to work... How could I do?

5
  • Apparently, you're re-declaring let loadModalJs, hence the error. You probably want to only declare it once or at the very least just re-assign it. It's hard to see where the re-declaration is happening because it's not included in this code.
    – VLAZ
    Commented Mar 9, 2021 at 7:16
  • @VLAZ the redeclaration happens then this code is run a second time, how can I declare it only if it's not declared? Commented Mar 9, 2021 at 7:17
  • If the function does not change and should not be redefined, use const to find where you are trying to redefine it
    – mplungjan
    Commented Mar 9, 2021 at 7:18
  • @SofiaGrillo how is the code run a second time? Why does loadModalJs need to be declared again? Maybe it's as simple as making a single function that takes a parameter and calling it with a given value, instead of making a new function every time.
    – VLAZ
    Commented Mar 9, 2021 at 7:26
  • 1) use window.function if it realy need to be a global function (bad idea, keep the global scope as clean as possible), 2) let is block-scope spectifi. if you declare a function/variable inside a block ({...}) its only available in this specific block/scope.
    – Marc
    Commented Mar 9, 2021 at 7:26

4 Answers 4

4

The error you placed into the comment is correct: at no point do you define the variable in scope -- you define it within the the if clause, and it is not available outside of that clause, your reference to it in the if statement is to an undefined global variable.

Also, if your variable is only ever going to be undefined or a function, then no need to test its type, as undefined evaluates to false.

let loadModalJs;

// ...your other code here...


// This bit within the function/scope run multiple times:
if (!loadModalJs) {
    loadModalJs = function() {
       ...
    };  
}

if (loadModalJs) { 
  loadModalJs(); 
}
3
  • The fact is that the whole block can run multiple times, in this case it'd gave error on line 1 the second time, because it's already declared. Commented Mar 9, 2021 at 7:26
  • I think I got it, the if constructor is considered a scope in javascript, contrary to other languages... I could define it globally with window. Commented Mar 9, 2021 at 7:26
  • @SofiaGrillo: Yes...in JavaScript, anything withing {} curly braces is a scope. So define the var is I did, at the top of your outer-most scope. No need to touch the window object. Commented Mar 9, 2021 at 7:29
2

In addition to the current answer:

Your second snippet could work if you use var instead of let.

As if creates its own block {}:

  • let is limited to the immediate block {}.
  • var is limited to the immediate function block {} (or global if there are no functions).

E.g.:

if (true) {
  var x = "It'll work outside the if.";
}

console.log(x);


Edit:

As an additional tip, you might be careful with the way you 'create' functions in javascript:

  • Functions defined, e.g. let myFunction = function() { }, are under top-to-bottom flow of control (i.e. first define, then use).
  • Functions declared, e.g. function myFunction() { }, are hoisted (i.e. declare and use where you want, in the same scope).
0

In addition to Lee Goddard's answer. You may consider learning about the difference between let and var. The most key difference is:

let allows you to declare variables that are limited to the scope of a block statement or expression on which it is used, unlike the var keyword, which declares a variable globally, or locally to an entire function regardless of block scope. - MDN Docs

0

This looks like a good opportunity to use guard/default clauses:

let f = function(){
  console.log('f is defined');
}

let g;
g = f || function() {
    console.log('f was NOT defined');
}
g();
f = null;
g = f || function() {
  console.log('f was NOT defined');
}
g();

with a twist:

let f, g;



for (let i=0; i<8; i++){
  g = f || function() {
    console.log('f was NOT defined');
  }
  g();
  f = (f)?undefined:function(){console.log('f is defined');};
}

So in your case this would be:

let guardedModal = loadModalJs || function() {
        // your code here
}
guardedModal();
4
  • All these involve putting let loadModalJs in the parent page which is what I wanted to avoid... but as I see there are no alternatives Commented Mar 9, 2021 at 8:20
  • I want to do let something only if that something is not already let... Commented Mar 9, 2021 at 8:22
  • ... because if a single-page panel can run thousands of different actions, I'll need to declare thousands of variables Commented Mar 9, 2021 at 8:23
  • @SofiaGrillo if you give us the reason why you need to redeclare loadModuleJs then we could probably give you a better alternative than redeclaring it. Right now, it's very very hard to give a generic solution to an unknown problem.
    – VLAZ
    Commented Mar 9, 2021 at 9:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.