How to run code in JavaScript, only when a variable is defined?

I'm writing a simple function in JavaScript:

function waitThenRun(objectToWaitFor, callback) {
   // logic to periodically check for objectToWaitFor to become something
   // then call the callback
}

And I intend to use it as:

waitThenRun(someObjectThatWillBeDefinedLater, function() {
    // Doing something with someObjectThatWillBeDefinedLater
});

Yet I get this error:

Uncaught ReferenceError: someObjectThatWillBeDefinedLater is not defined

How do you handle this?

In simpler terms, I want to run a piece of code only when a global JSON variable is defined, and I can't determine when and where it gets defined. Sometimes it gets defined after my code, sometimes before my code, sometimes a second later, sometimes 5 seconds later. It's non-deterministic.

You can dispatch an event on the window when you define your JSON Object and add an event listener for that event on the window. This way, you will not need to use a setInterval to continuously check if a global variable is defined.

function defineJSON(){
  window.JSONObj = {x: "something"};
  triggerEvent("JSONDefined", window, {JSONObjName: "JSONObj"});//fire a custom event on the window when you define the JSON Object
}
function triggerEvent(type, obj, data){
  var ev;
  if (document.createEvent) {
    ev = document.createEvent("HTMLEvents");
    ev.initEvent(type, true, true);
  } else {
    ev = document.createEventObject();
    ev.eventType = type;
  }
  ev.eventName = type;
  if(data){
   for(var key in data){
     if(data.hasOwnProperty(key)){
        ev[key] = data[key];
     }
   }
  }
  if (document.createEvent) {
    obj.dispatchEvent(ev);
  } else {
    obj.fireEvent("on" + ev.eventType, ev);//for < IE8
  }
}
window.addEventListener("JSONDefined", function(ev){
  //this event handler will be called when the JSON Object is defined
  console.log("JSON defined:", window[ev.JSONObjName]);
});
setTimeout(function(){
   defineJSON();
}, 2000);//define JSON Object after 2 seconds (just for this example)

javascript only run if variable is defined Code Example, Get code examples like "javascript only run if variable is defined" instantly right from your google search results with the Grepper Chrome Extension. A variable defined inside a scope is accessible only within that scope, but inaccessible outside. In JavaScript, scopes are created by code blocks, functions, modules. While const and let variables are scoped by code blocks, functions or modules, var variables are scoped only by functions or modules.

If it's a global variable, you can pass the variable name as a string. Since global variables become properties of the window object, the function can then check whether window[objectToWaitFor] is defined.

function waitThenRun(objectToWaitFor, callback) {
    var interval = setInterval(function() {
        if (window[objectToWaitFor] !== undefined) {
            clearInterval(interval);
            callback();
        }
    }            
}

waitThenRun("someObjectThatWillBeDefinedLater", function() {
    // do something with someObjectThatWillBeDefinedLater
});

How to Check If a Variable Exists or Defined in JavaScript, Try this code �. <script>; var x;; var y = 10;; if(typeof x !== 'undefined'){; // this statement will not execute; alert("Variable x is defined."); } if(typeof y !== ' undefined'){ Variable not declared foo.substring(1); // ReferenceError: foo is not defined The "foo" variable isn't defined anywhere. It needs to be some string, so that the String.prototype.substring() method will work. var foo = 'bar'; foo.substring(1); // "ar" Wrong scope. A variable needs to be available in the current context of execution.

All global variables are attached to the window object so can pass the variable name to your function as a string and check if it exists on the window and then run your callback if it does. Snippet:

setTimeout(function() {
  window.someObjectThatWillBeDefinedLater = {hello: 'world'};
}, 1000);

function waitThenRun(globalObj, callback) {
  let intervalId = setInterval(function() {
    if (window[globalObj] !== undefined) {
      callback(window[globalObj]);
      clearInterval(intervalId);
    }
  }, 200);
}

waitThenRun('someObjectThatWillBeDefinedLater', console.log.bind(console));

Variable scope, If a variable is declared inside a code block {} , it's only In JavaScript, every running function, code block {. We don't run it yet, only create. Function or a string of code to execute. Usually, that’s a function. For historical reasons, a string of code can be passed, but that’s not recommended. delay The delay before run, in milliseconds (1000 ms = 1 second), by default 0. arg1, arg2… Arguments for the function (not supported in IE9-) For instance, this code calls sayHi() after

you can do this by using

   var checkExist = setInterval(function() {
   if (JsonObject) {
//execute your method here
      console.log("Exists!");
      clearInterval(checkExist);
   }
}, 100); // check every 100ms

Functions, A variable declared inside a function is only visible inside that function. A function can return a value back into the calling code as the result. This is a beginner article which will help you to use JavaScript and jQuery library in Asp.Net MVC project. Calling JavaScript Function from Razor View. Assume, you have a list of employee displayed in HTML table and you want to call a javascript function on click of the employee name column.

You can try to use metaprogramming like JS proxies to intercept the set method of an objects property. Something like this:

function tracePropAccess(obj, propKeys) {
    const propKeySet = new Set(propKeys);
    return new Proxy(obj, {
        get(target, propKey, receiver) {
            if (propKeySet.has(propKey)) {
                console.log('GET '+propKey);
            }
            return Reflect.get(target, propKey, receiver);
        },
        set(target, propKey, value, receiver) {
            if (propKeySet.has(propKey)) {
                console.log('SET '+propKey+'='+value);
            }
            return Reflect.set(target, propKey, value, receiver);
        },
    });
}

the snippet was taken from here

In your example, when the set property gets called you can check if the value meets your expected value and do as you wish with it.

undefined, In the following code, the variable x is not initialized, and the if statement evaluates if ('x' in window) { // these statements execute only if x is defined globally }� Using the dollar sign is not very common in JavaScript, but professional programmers often use it as an alias for the main function in a JavaScript library. In the JavaScript library jQuery, for instance, the main function $ is used to select HTML elements.

Closures, Run the code using this JSFiddle link and notice that the alert() Nested functions have access to variables declared in their outer scope. a closure anywhere that you might normally use an object with only a single method. From the actions list, select this action: Execute JavaScript Code. The action appears in the designer and contains some default example code, including a return statement. In the Code box, delete the sample code, and enter the code that you want to run. Write code that you'd put inside a method, but without defining the method signature.

The Ultimate Guide to JavaScript Variables: var, let, and const , The message variable is declared and hold a special value undefined . In other words, it only exists inside the function. use the strict mode in your JavaScript code to eliminate some JavaScript silent errors and make your code run faster. React Hooks are a broad set of tools in the React front-end JavaScript library that run custom functions when a component's props change. Since this method of state management doesn't require you to use classes, developers can use Hooks to write shorter, more readable code that is easy to share and maintain.

JavaScript - Variables, JavaScript - Variables - One of the most fundamental characteristics of a JavaScript also defines two trivial data types, null and undefined, each of which defines only scope which means it can be defined anywhere in your JavaScript code. An expression is a single unit of JavaScript code that the JavaScript engine can evaluate, and return a value. Expressions can vary in complexity. We start from the very simple ones, called primary expressions: 2 0.02 'something' true false this //the current scope undefined i //where i is a variable or a constant

Comments
  • What do you mean you and I can't determine when it gets defined? Isn't it defined somewhere in your code?
  • I mean my code might run before its definition, or after its definition. It's non-deterministic.
  • Variables are passed by value, not by reference. There's no way for a function to test whether the variable is defined in the caller's scope.
  • @Barmar, then how do you make sure it's defined? It's somehow similar to jQuery's $(document).ready(), but for global JSON object.
  • You are fighting against the way things are done in javascript. Usually one would use a callback or an event listener to know when something has happened. You have code that is defining the variable — you should call your function or a callback there (this is how $(document).ready() works -- it takes a callback). Everything else with timers and polling will be a hack.
  • Have you tried it yourself? That if (JsonObject) is exactly where I get error. That's why I asked this question.