DEV Community

Fictional Q&A about JavaScript Hoisting

HowToCodejs on May 28, 2018

Q: Here's a question I'd like answered. Why does this work? What is this Jedi nonsense? sayMyNameSayMyName('Morty'); // 'I said your name, M...
Collapse
 
jsn1nj4 profile image
Elliot Derhay

In seriousness, this raises a question in my mind: does choosing to assign instead of declare functions have to do with avoiding weirdness with hoisting or some related issues?

Collapse
 
howtocodejs profile image
HowToCodejs • Edited

To add on to what I wrote, you can also re-assign to a variable that contains an anonymous function. You can take advantage of this by writing an if statement that checks if we are in a certain mode


var strictMode = true;

var logNumber = function(num){
  return num;
}

if(strictMode){
  logNumber = function(num){     
    if(isNaN(num)){
      return; // do nothing
    }else {
      return num; // return number 
    }
  }
}

We would've had to have declared two separate functions if we hadn't created a function expression. Still, the difference is minimal.

Collapse
 
howtocodejs profile image
HowToCodejs • Edited

That's a good question. For one, the concept of hoisting doesn't seem to be something people write their programs around. It's a convenient side-effect that some don't even recognize.

The thing about initialization versus declaration comes down to convention and flexibility.

It is the convention to create a class with a function declaration:

function Bat{...}

But if I wanted to create a function prototype, I would use an assignment operator.

Bat.prototype.fly = function(){...}

Because functions are first order, I can assign them, return them, use them as parameters.

Whether to declare or assign might just come down to style for some, but the differences go beyond hoisting.

Collapse
 
jsn1nj4 profile image
Elliot Derhay

I was thinking in terms of assigning to variables, but thanks for pointing out those other ways of assigning. I don't normally think of it that way with prototype methods and callbacks, but that does make sense.

Collapse
 
jsn1nj4 profile image
Elliot Derhay

Giving it a Unicorn, since...you know...functions are unicorns. :)