In this article I will give a quick overview of JavaScript hoisting and explain why sometimes your variables are not doing what you expect them to.
In the following example we have a very simple variable declaration and function:
var msg = "hello world" function sayHi(){ alert(msg) } sayHi()
If you run this through firebug you get the expected message in the browser
However if you change the code slightly you do not get the initially expected response. When you run the following code you get ‘undefined’ as the answer when you would possibly expect to see “hello world”
var msg = "hello world" function sayHi(){ alert(msg) var msg = "hello galaxy" //<--- new line of code } sayHi()
This is due to what is called “JavaScript hoisting” and there is an excellent article on it here – http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html. What is basically happening is that although you did not write it, the function level scoping of var msg = “hello galaxy” is declaring the variable msg at the top of the function before anything else executes.
So what you are really doing is this:
var msg = "hello world" function sayHi(){ var msg alert(msg) msg = "hello galaxy" } sayHi()
I recommend you read the article I mentioned and understand how JavaScript scoping differs from other programming languages.
Hi Marky. Great tip. Thanks. Thanks to LotusScript I’ve always declared my variables prior to using them, so I’ve never really hit this issue, but very good to know
Very interesting — nice tip.
Reblogged this on Sutoprise Avenue, A SutoCom Source.
Marky, tried to put the $(‘.panelDemo’).shadow(‘raised’); in an afterpageload event wich gives me an error : Script interpreter error, line=1, col=1: [ReferenceError] ‘$’ not found
When I put it in a button everything works.
Guess must be a problem of load order ? How can I solve this ?
Marc,
‘$ not found’ means jQuery is not loaded yet. In my sample database I have jQuery loaded as a theme. If you want to add it to your XPage directly try adding this to the top of the XPage source. This is not ideal for production but will get you going
Add the following to your XPage at the bottom of the source code
$(document).ready(function(){
$(‘.panelDemo’).shadow(‘raised’)
})
hit me up on skype if you need any other help 🙂