13

Very simple script:

function foo(){
    return "bar"
}

console.log( foo() );

console:

> bar // sanity test that proves everything's working
> foo(); // this guy is key!
> ReferenceError: foo is not defined

How should I call foo(); for debugging and experimentation purposes?

Is this not a practise? I love using IRB / Rails Console to verify my ruby code and want to do the same with JavaScript

http://jsfiddle.net/m2muL/

Starkers
  • 10,273
  • 21
  • 95
  • 158

2 Answers2

10

The problem is that your foo function is not part of the global scope. The console essentially has access to everything that window does. As a result, if it is undefined there, then it is undefined in the console. For example, this could be an example of foo not being available in the console.

(function(){
   function foo(){
     return "bar";
   } 
   console.log(foo()); //"bar"
})()

console.log(foo()); //ReferenceError: foo is not defined

Find a way to locate where this method is exposed. If it is inside of an object or method, make sure to reference that from your console.

var foobar = {
 foo: function(){ return "bar" ;}
};

console.log(foobar.foo()); //"bar"

If you cannot reference foo, then you cannot call it.

Travis J
  • 81,153
  • 41
  • 202
  • 273
  • I can do this. Is it a good practise to create objects in javascript/jquery and store related functions inside them anyway? Rather than have functions just floating around in the global scope? – Starkers May 13 '14 at 21:22
  • @Starkers - Best practice is to have only one global variable that holds the lifetime and definitions of all of your functions. This is why, to take jQuery for example, all of their API is under `$` or `jQuery` and that is the only entrance. Usually that is done by internalizing a prototype and returning a built instance. – Travis J May 13 '14 at 21:24
4

You're trying to do this in JSFiddle, which is "hiding" your javascript away from your console. It's not really in scope for you to execute. It's not working there like you are assuming it will...

If you created a simple HTML file and stuck your javascript in there between tags, you wouldn't have a problem running "foo()" in console.

Create test.html and put this inside:

<script>
function foo(){
    return "bar"
}
console.log( foo() );
</script>
Ralph N
  • 4,240
  • 8
  • 28
  • 36
  • I get `bar` `bar` like I'd expect, but upon running `foo();` I get the undefined error? – Starkers May 13 '14 at 21:20
  • Not sure if we're doing the same thing. Open notepad, paste in the code in my answer, save as test.Html. Then open test.html in chrome, open console, and type "foo();" – Ralph N May 13 '14 at 21:21
  • Your jsfiddle is wrapped with an onload event handler. – Travis J May 13 '14 at 21:23