DEV Community

Discussion on: What is the oddest JavaScript behavior?

Collapse
 
dwd profile image
Dave Cridland • Edited

Scoping rules with (or without) var are the weirdest:


// Prints the value of a.
function printA() {
  console.log(a);
}

// Prints '1'
function print1() {
  var a = 1;
  printA();
}

// Prints '2'
function print2() {
  var a = 2;
  printA();
}

// Prints whatever the value of b in the caller's scope is.
function printB() {
  a = b;
  printA();
}

// Prints 3.
function print3() {
  var b = 3;
  printB();
}

// Print 4, then 5.
function print45() {
  var b = 4;
  var a = 5;
  printB();
  printA();
  // Ha, no it doesn't, it prints 4 twice, and now:
  assert(a === 4);
}

Collapse
 
mellen profile image
Matt Ellen

you have just blown my tiny mind

Collapse
 
dwd profile image
Dave Cridland

Of course, I made a mistake on it (now corrected), but still. If you want to see something batshit insane with scoping and hoisting, you can try and get your head around this:

function fib(n) {
  if (n) {
    a = 1;
    b = 0;
    c = n + 1;
  }
  if (c === 1) {
    return a + b;
  }
  c = c - 1;
  let d = a + b;
  b = a;
  a = d;
  return fib();
}
Thread Thread
 
mellen profile image
Matt Ellen

😭

Collapse
 
johnylab profile image
João Ferreira

loved