Skip to content

Instantly share code, notes, and snippets.

@johnborges
Last active December 11, 2020 20:40
Show Gist options
  • Save johnborges/2031e5632ddf2300c98ad2c2adbe9ed6 to your computer and use it in GitHub Desktop.
Save johnborges/2031e5632ddf2300c98ad2c2adbe9ed6 to your computer and use it in GitHub Desktop.
7 Tricky JavaScript Interview Questions

7 Tricky JavaScript Interview Questions

  1. Accidental Global
function foo() {
  let a;
  window.b = 0;
  a = window.b;
  a++;
  return a;
}

foo();
typeof a;        // => 'undefined'
typeof window.b; // => 'number'
  1. Array Length Property
const clothes = ['jacket', 't-shirt'];
clothes.length = 0;

clothes[0]; // => undefined since cloths is now empty
  1. Eagle Eye Test
const length = 4;
const numbers = [];
var i;
for (i = 0; i < length; i++) {
  // does nothing
}
{ 
  // a simple block
  numbers.push(i + 1);
}

numbers; // => [5]
  1. Automatic Semicolon Insertion
const length = 4;
const numbers = [];
var i;
for (i = 0; i < length; i++) {
  // does nothing
}
{ 
  // a simple block
  numbers.push(i + 1);
}

numbers; // => [5]
  1. Tricky Closure
let i;
for (i = 0; i < 3; i++) {
  const log = () => {
    console.log(i); // 3 3 3
  }
  setTimeout(log, 100);
}
  1. Floating Point Math
0.1 + 0.2 === 0.3 // => false

The sum of 0.1 and 0.2 numbers is not exactly 0.3, but slightly above 0.3. Due to how floating point numbers are encoded in binary, operations like addition of floating point numbers are subject to rounding errors.

  1. Hoisting
myVar;   // => undefined
myConst; // => ReferenceError

var myVar = 'value';
const myConst = 3.14;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment