473,699 Members | 2,385 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can JavaScript use a function before it's defined?

As subject. By 'before' I mean before in the file, not in time.

Here's a file
===
$ cat wierd.js
f()
function f(){print('hi') }
f()
function f(){print('ho') }
f()
===

And when I run SpiderMonkey on it
$ js wierd.js
I get - well, what do you think I get?

OK. So I get
===
$ js wierd.js
ho
ho
ho
===

So it seems that SpiderMonkey is picking up the LAST definition of f()
and executing it three times. Not at all what I expected.

I didn't find any relevant information in
http://developer.mozilla.org/en/docs...ning_functions

I'd like to read about this. Any pointers? In particular, does anyone
know of a JavaScript book that documents this behaviour? And is it
reliably cross-platform?

--
Jonathan
Jun 27 '08 #1
3 1656
VK wrote:
Yes, this behavior is by design and cross-browser. Do not forget that
function declarations are not a part of the program execution flow.
Thanks for this. I guess there may be a difference between function
declaration and function definition. For example
f = function f(){print('hi') }
is not always equivalent to
function f(){print('hi') }

I was expecting the latter to have the actual meaning of the former!
I am not ready to give an exact reference. I assume you can find
relevant text in ECMA-262 3rd ed. in the description of parser and
tokenizer algorithms.
[explanation snipped]

I'd really appreciate a reference that gives all these not-so-obscure
gotchas in JavaScript language, so that I know where to look the next
time I come across a gotcha like this.
With a description of your actual intent a regular coding solution
could be suggested.
I wanted to understand why SpiderMonkey was not doing what I expected.

I wrote:

// Dummy definition
if (typeof fn == 'undefined') function fn(){}

// Lots of lines like ...
fn(123)

// Real definition of fn
function fn(){
print(arguments )
//...
}

I thought this would allow me to structure the code in the way I wanted
to, and was surprised that the dummy def'n of fn was never used.

Thank you for your help in understanding some of the intricacies of
JavaScript.

--
Jonathan
Jun 27 '08 #2
On Jun 21, 9:19 am, Jonathan Fine <jf...@pytex.or gwrote:
VK wrote:
Yes, this behavior is by design and cross-browser. Do not forget that
function declarations are not a part of the program execution flow.

Thanks for this. I guess there may be a difference between function
declaration and function definition. For example
f = function f(){print('hi') }
is not always equivalent to
function f(){print('hi') }

I was expecting the latter to have the actual meaning of the former!
They are essentially equivalent, the difference is that function (and
variable) declarations are processed before any code is executed.
Function expressions, e.g.

var foo = function() {}

are evaluated when the code is run. In the above, when execution
begins, foo has a value of undefined until the line assigning it the
anonymous function is executed.

>
I am not ready to give an exact reference. I assume you can find
relevant text in ECMA-262 3rd ed. in the description of parser and
tokenizer algorithms.

[explanation snipped]

I'd really appreciate a reference that gives all these not-so-obscure
gotchas in JavaScript language, so that I know where to look the next
time I come across a gotcha like this.
It's not a "gotcha", it is a well-known feature of the language and is
not unique to ECMAScript. Try section 10 Execution Contexts and more
specifically, section 10.1.3 Variable Instantiation.

>
With a description of your actual intent a regular coding solution
could be suggested.

I wanted to understand why SpiderMonkey was not doing what I expected.

I wrote:

// Dummy definition
if (typeof fn == 'undefined') function fn(){}

// Lots of lines like ...
fn(123)

// Real definition of fn
function fn(){
print(arguments )
//...
}

I thought this would allow me to structure the code in the way I wanted
to, and was surprised that the dummy def'n of fn was never used.
Because before the code was executed, the function declaration had
been processed as a component of variable instantiation and fn was a
function object.

To get the effect you expected:

var fn;

// Dummy definition
if (typeof fn == 'undefined') function fn(){}

// Lots of lines like ...
fn(123)

// Real definition of fn
fn = function (){
print(arguments )
//...
}

--
Rob
Jun 27 '08 #3
Jonathan Fine <jf***@pytex.or gwrites:
VK wrote:
>Yes, this behavior is by design and cross-browser. Do not forget that
function declarations are not a part of the program execution flow.

Thanks for this. I guess there may be a difference between function
declaration and function definition. For example
f = function f(){print('hi') }
is not always equivalent to
function f(){print('hi') }

I was expecting the latter to have the actual meaning of the former!
Well, javascript is kind of a hack - but then, many popular languages
are. In any case, as a rule of thumb, "function name() {}" is
evaluated at the earliest possible time, while "name = function(){}"
is evaluated at the latest possible time.

All of the above is a convenient lie.

--
Joost Diepenmaat | blog: http://joost.zeekat.nl/ | work: http://zeekat.nl/
Jun 27 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
2014
by: Alex Fitzpatrick | last post by:
Just by way of introduction, I'm currently the principal developer and maintainer of the a JavaScript editor plug-in for Eclipse. https://sourceforge.net/projects/jseditor/ The plug-in as it stands supports syntax highlighting and outlining of functions, classes and their methods.] When I took over the project in June it was for the purpose of adding outlining facilities for JavaScript written in an OO style with classes and so on. I...
2
3882
by: Bernhard Georg Enders | last post by:
Hi! Everything works fine with Opera and IE, but not with Mozilla 1.7.3 and Firefox 1.0 PR. When I call a function previously defined inside another function I've got "function is not defined". Why? TIA, Bernhard. -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/
18
2205
by: marcokrechting | last post by:
Hi All, I have a rather complicated problem. I use following function to display a hyperlink: a="<"+"a href='"; b3="<"+"a href='http://nww."; L="</"+'a><br>'; function h(a){document.writeln(a)}
1
17580
by: Sylaris | last post by:
hi, i have a problem which recursion fits perfectly, however; after working with the base function (which has no errors and works correctly) the recursions return a "function not defined" error in ff's js console. i tried a few things that came to mind but nothing has changed it... i found some interesting articles on the net regarding javascript's callbacks, and found out that due to callbacks recursion may end up eating a lot more memory than...
7
1806
by: Wm.M.Thompson | last post by:
For a computer programmer JavaScript is not difficult. It is pretty easy to look at some code for the first time and figure out what is going on. This is especially true if you have gratuated from an old-fashioned top-down programmer to an object oriented computer programmer. I mean, most Javascript has a look where things are sectioned off into functions. This is pretty much true until one gets into DHTML and a very cool
6
2526
by: den 2005 | last post by:
Hi everybody, Question 1: How do you set the values from server-side to a client-side control or how do you execute a javascript function without a button click event? Question 2: How do you get response from a Confirm() popup window to uncheck all server-side checkboxes placed in a panle of a web user control? I am using ASP.Net 2.0, Thanks. Need info...
1
3321
by: Brian Kendig | last post by:
I've got some questions about using an external javascript file, included via '<script type="text/javascript" src="mycode.js" ></ script>': (1) If I define a function "myFunction()" in the original HTML file, and reference it by "onMouseDown='myFunction();'" in a tag, it works. But if I move the myFunction() definition to an external javascript file, Firefox tells me "myFunction is not defined". Why is this, and how can I be able to...
1
25682
pbmods
by: pbmods | last post by:
VARIABLE SCOPE IN JAVASCRIPT LEVEL: BEGINNER/INTERMEDIATE (INTERMEDIATE STUFF IN ) PREREQS: VARIABLES First off, what the heck is 'scope' (the kind that doesn't help kill the germs that cause bad breath)? Scope describes the context in which a variable can be used. For example, if a variable's scope is a certain function, then that variable can only be used in that function. If you were to try to access that variable anywhere else in...
2
3153
by: sorobor | last post by:
dear sir .. i am using cakephp freamwork ..By the way i m begener in php and javascript .. My probs r bellow I made a javascript calender ..there is a close button ..when i press close button then the calender gone actually i want if i click outside off the calender then it should me removed ..How kan i do this ... Pls inform me as early as possible .. I am waiting for ur quick replay ...Here i attached the source code .... <!DOCTYPE...
0
8685
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9172
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9032
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8908
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8880
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6532
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4374
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4626
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2008
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.