-2

I am confused why foo2 works but foo1 not.

JS Fiddle: https://jsfiddle.net/474v3mfd/4/

html

<a onclick="foo1()">
  foo1
</a>
<a onclick="foo2()">
  foo2
</a>

Javascript

function foo1(){
  console.log("foo1 called..");
}

foo2 = function(){
  console.log("foo2 called..");
}

console log

(index):60 Uncaught ReferenceError: foo1 is not defined at HTMLAnchorElement.onclick ((index):60) onclick @ (index):60 (index):50 foo2 called..

Summary

The problem is specific to JSFiddle. When I put the code in HTML file it works fine.

Subir Kumar Sao
  • 8,171
  • 3
  • 26
  • 47
  • 1
    You'll have to show a more complete example, but my guess is that the code is inside a function (e.g. onload event) so `foo1` is local and `foo2` is global. – JJJ Jan 12 '17 at 07:34
  • **First:** make sure your script is loaded before `a` tags. Though its not advised. You should rather use `.addEventListener` to bind event. **Second:** declaring variable without `var` will make it global. – Rajesh Jan 12 '17 at 07:35
  • Added JS Fiddle. https://jsfiddle.net/474v3mfd/4/ – Subir Kumar Sao Jan 12 '17 at 07:36
  • JSFiddle places all your function declarations within the body of the `onload` function. As a result any of the declared functions and variables are out of scope for the rest of the program. Rajesh explained why the second statement does work; it is global. Placing var in front of your second statement, or `"use strict"` atop your file should make the second case fail as well. – Yemachu Jan 12 '17 at 07:44

1 Answers1

0

this is the issue about the scope where the functions has been declared. if you run this code in browser it will work all fine, as both function and function expression are declared in global scope.

but here in fiddle it's failing as function expression has been assigned to a global variable 'foo2' so it's accessible, but function foo1 is not available in the scope in fiddle.

if you do as below, by creating variable foo2 using var, it will get create into the different scope ( no more global) and that's why it will throw the same error as foo1.

var foo2 = function(){
  console.log("foo2 called..");
}

updated fiddle - https://jsfiddle.net/474v3mfd/6/

hope it helps.

MGA
  • 511
  • 2
  • 11