ShibinRagh
ShibinRagh

Reputation: 6656

How to call the function from browser console?

I need to call the function from browser console for testing purpose ?

test is working as expected , but test2 is not working

function test() {
  alert(0);
}
(function(e, t) {
  var test2 = (function() {
    alert(2)
  })
})

Calling for browser console

test() // its working

test2() // Uncaught ReferenceError: test2 is not defined

Upvotes: 0

Views: 1418

Answers (2)

Quentin
Quentin

Reputation: 944175

There are two basic problems here:

test2 never exists

test2 is defined inside a function which is never called, so it is never defined.

The code would have to actually call the anonymous function it is inside.

However, assuming that is a side effect of you truncating the code for this question and in your real case that anonymous function does get called:

test2 isn't a global

So in order to access it, you need to be in the right scope.

The only way to do that for the console would be to:

  1. open up the sources tab of the browser's developer tools
  2. add a breakpoint inside the anonymous function
  3. run the code until your reach the breakpoint
  4. then use the console to access test2 which is now in scope.

Note that given the structure of that code you might have to put the breakpoint before test2 has a value assigned to it and then step through the code until after it is defined.

Upvotes: 1

0stone0
0stone0

Reputation: 44162

Since your test2 var is a function on it's own, no need to wrap them in ().

Copy/paste this into browser console to check;

var test2 = (function() {
    alert(2)
});
test2();

Advanced JavaScript: Why is this function wrapped in parentheses?


Should you really want those parentheses, you can call the existing function like so;

(function(e, t) {
  var test2 = (function() {
    alert(2)
  });
  test2(); // <-- Run function
})()
//^^ Extra parentheses to instantly run wrapper function

Upvotes: 0

Related Questions