473,324 Members | 2,567 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

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 1631
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.orgwrote:
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.orgwrites:
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
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...
2
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"....
18
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...
1
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...
7
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...
6
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...
1
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...
1
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...
2
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...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.