Hurricane Development Hurricane Development - 1 month ago 13
Javascript Question

UncaughtType error only in anonymous function

I have the following code to animate a div. It works perfectly:

function fadeAndSlideIn(el,m,t) {
el.style.opacity = 0;
el.style.marginTop = 0;

var oi = 1 / (t * 60);
var mi = m / (t * 60);

var tick = function() {
el.style.opacity = +el.style.opacity + oi;
el.style.marginTop = (parseInt(el.style.marginTop) + mi) + 'px';

if (+el.style.opacity < 1)
(window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
}

tick();
}

(function() {
fadeAndSlideIn(document.getElementById('pan1'),125,1);
setTimeout(function() {
fadeAndSlideIn(document.getElementById('pan2'),125,1);
},500);
setTimeout(function() {
fadeAndSlideIn(document.getElementById('pan3'),125,1);
},1000);
})();


However when I change the
fadeAndSlideIn
function to an anonymous function like this:

var fadeAndSlideIn = function(el,m,t) {


my program does not work and I get the following error


Uncaught TypeError: Cannot set property 'opacity' of undefined


Why does the function decleration change the performance? All the code is in a
<script
> tag at the end of the body.

Answer

JS has got automatic semicolon insertion. This is not clever because sometimes the engine fails to do so and youre producing errors. So always use semicolons:

var a=function(){} //bad
var a=function(){}; //good

In your code the engine fails because as Felix Kling said, it thinks its an IIFE:

var a=function(){}
 (some other code);

So actually it passes your IIFE to the fadeInSlide as el, and el.style of your function is undefined...