What is the point of assigning classes and functions to variables?

what is the point of assign classes and functions to variables? to get what I mean check out the code below

const creature=class Animal {
  constructor(name) {
    this.name = name;
  }
}
const cat = new creature('Lilly');
console.log(cat.name);  // Lilly

const dog = new Animal('Boby');
console.log(dog.name);  //Error

const sum=(x,y)=>x+y;
console.log(sum(1,2));//3

function sum2(x,y) {
  return x+y;
}
console.log(sum2(2,1));//3

I mean in other languages like Java, functions are functions and classes are classes :thinking:
I feel it’s confusing to demonstrate between a function and a variable with more complex code

The main practical difference I can see is hoisting, which ironically is a key part to understand how the JS engine works.

Assigning a function (or a class, which is just a “fancy” function for JS) to a variable will make it follow its hoisting rules, according if is var, let or const.

// called before declared
sum(1,2) // TypeError: sum is not a function
sum2(1,2) // 3 function declaration are hoisted

function sum2(a,b) { return a + b };
const sum = (a,b) => a+b;

And here is where things get interesting, in a scenario like the following

function sum(a,b) {
  return a + b
}

function sum2(a,b) {
 // declare a local sum const - TRICK: it MULTIPLIES
  const sum = (a, b) => a * b;

  return sum(a,b)
}

sum(1,2)
sum2(1,2)

Can you guess what’s the output of the two function call? :smile:


I hope it’s not too confusing. To wrap it up I’d say the main difference is that, if assigned they follow the rules of var let and const otherwise the function declaration.

I’m sure this is an over-simplification but I hope it illustrate my point

1 Like

I guessed (correctly) 3 and 2. The second example doesn’t appear to have anything to do with hoisting, just lexical scope instead. Here’s a fun one though:

function foo() {
   var bar = () => "baz";   // only works with 'var'
   return bar();
   function bar() { return "xyzzy" }
}

Thankfully, even let won’t allow this kind of chicanery. Just another (contrived) reason to avoid var

Hey there! The primary reason is that JS has first-class functions (I didn’t make that up). Check this out for more info: https://developer.mozilla.org/en-US/docs/Glossary/First-class_Function. The closest equivalent of this in Java is lambdas, but it’s still not quite the same.

let x = class Y { ... } seems like an anti-pattern and isn’t something I’ve seen in a lot of code. Typically classes are defined with just class Y extends Z { ... }.

If you have follow-up questions, please feel free to ask!

3 Likes