DEV Community

Cover image for Hello World! Hoisting!
Jason Stewart
Jason Stewart

Posted on • Updated on

Hello World! Hoisting!

My Hello World!

Hello! My name is Jason Stewart. I'm currently beginning my adventure into learning full-stack programming. I'm part of a cohort at Flatiron School. There I'm going to be focusing on

  • JavaScript

  • ReactJS

  • Python

  • Flask

Currently, I'm focusing on learning JavaScript, yay!

Hoisting!

var = "boo! don't use 'var' as it can cause strange bugs"
Enter fullscreen mode Exit fullscreen mode
function hello() {
  return "Hello World!";
} 
Enter fullscreen mode Exit fullscreen mode

VS

hello = () => "Hello World!"; 
Enter fullscreen mode Exit fullscreen mode

What is hoisting?

According to GeeksforGeeks, hoisting is...

a concept that enables us to extract values of variables and functions even before initializing/assigning value without getting errors and this happens during the 1st phase (memory creation phase) of the Execution Context.

So in JavaScript, hoisting is moving declarations to the top of the scope, before execution. Hoisting is why, when we assign a variable with 'var', rather than 'let', or 'const', it can cause strange issues and make it hard to debug.

This is also why, when we use 'function' to make a function in JavaScript, it does not really matter where in the scope we put the function. In other words, writing a function at the end of your code and calling it at the beginning is not a problem. So doing is fine:

console.log(sayHello("Steve"));

function sayHello(name) {
  return "Hello World!";
} 
Enter fullscreen mode Exit fullscreen mode

However, the cool way to write functions is with the 'arrow' e.g. =>
The thing to keep in mind with using arrow is that, where it is placed in the scope is critical. For example, if you have:

console.log(sayHello("Steve"));

const sayHello = (name) => `Hello, ${name}!`;
Enter fullscreen mode Exit fullscreen mode

It throws an error

ReferenceError: Cannot access 'sayHello' before initialization

and will not run, as the function was made with =>, therefore not hoisted and it was called before it was defined. So to fix it, we would have to call the function after it was defined. That way it is in scope. For example:

const sayHello = (name) => `Hello, ${name}!`;

console.log(sayHello("Steve"));
Enter fullscreen mode Exit fullscreen mode

All that being said, which to use? IDK, I'm new here. hahah
Laughing smiley face
I have been told that most functions nowadays are being written with arrow notation. I will continue to play with them and see how I feel about it. Will update, once I have figured out my take on this.

Top comments (0)