Fizz Buzzkill... – Answering dreaded JS interview questions... – Me



Fizz Buzzkill... – Answering dreaded JS interview questions... – Me

0 0


nashjsslides


On Github vacas5 / nashjsslides

Why I'm not a JavaScript developer

The dreaded interview questions...

Created by Russ Anderson / @RealRealRuss

Don't linger here just get started.

Me

  • husband, father of ~2
  • Christian, member of Midtown Fellowship
  • Inglewood
  • terrible golfer
  • @RealRealRuss

Advocacy Marketing platform

provide ways for fans of your brand to help spread the word about what you're doing

Front-end Developer

  • I actually AM a JavaScript Developer
  • full time ~4 years
  • mostly self-taught / colleague-taught
  • no computer science background
  • mostly working within libraries and frameworks
Bait and switch! can mention jquery and backbone, but don't get ahead of yourself here talking about limited JS knowledge, wait for HTML5 boilerplate Where's the title come from?
describe without clicking the link, he wrote this post in january, his answers to... (next slide)

Front-end Job Interview Questions

https://github.com/h5bp/Front-end-Developer-Interview-Questions#js-questions

this list of interview questions compiled by the folks behind h5bp. for instance (next slide)

Why is it called a Ternary expression, what does the word "Ternary" indicate?

 

Ternary means it involves three things, and strings 'em all on one line so it's harder to read.

here's a question on that list

Create a for loop that iterates up to 100 while outputting "fizz" at multiples of 3, "buzz" at multiples of 5 and "fizzbuzz" at multiples of 3 and 5

 

That sounds hard, and for some strange reason I'm suddenly jonesing for a Dr. Pepper.

the infamous fizz buzz

Several basic JS questions that I couldn't simply answer

I'm probably not alone

  • I'll answer a few
  • succinct explanation
  • real world application
Reference again my use of frameworks libraries, etc. Goal is to provide some basic succinct explanation, some real world application. May be a bit rudimentary for some long time JS developers, but a good review nonetheless.

Aren't interview questions stupid?

 

We are not paid to use every feature of the language. We are paid to write programs that work well and are free of error — Douglas Crockford well, yes. Fizzbuzz brings up a lot of emotions for developers. show quote. What's more important is what you can build, how focused you can be, and that you want to learn. But try not to get hung up on the interview part. let's just learn!

1) Explain event delegation

JS events fire not only on a single DOM element but on all its descendants

Good example of one that I use all the time in practice but could not have just explained from memory. show definition, reverse of this is that they bubble up. If you're clicking on an 'a' tag inside an 'li', inside a 'u l', aren't you in reality clicking on all three?

2) Describe event bubbling.

Inverse of this. Also known as propogation, events on an element will "bubble up" and also fire on all parents

Example: live editing a form

<form id="form">

  <div class="input-group">
    <label class="control-label" for="Name">Name <i class="icon-asterisk"></i></label>
    <input type="text" id="Name" name="Name" placeholder="John Doe, e.g." required="" pattern="[A-Za-z-0-9]+\s[A-Za-z-'0-9]+" title="firstname lastname">
  </div>

  <div class="input-group">
    <label class="control-label" for="Email">Email Address <i class="icon-asterisk"></i></label>
    <input type="email" id="Email" name="Email" placeholder="example@yourdomain.com" required="">
  </div>

  <div class="input-group">
    <label class="control-label" for="Tel">Phone Number</label>
    <input type="tel" id="Tel" name="Tel" placeholder="(555) 555-5555" pattern="([0-9]{3}) [0-9]{3}-[0-9]{4}">
  </div>

  <div class="input-group">
    <label class="control-label" for="Message">How would you like to get involved?</label>
    <textarea id="Message" name="Message" rows="4"></textarea>
  </div>

  <div class="input-group">
    <label class="checkbox">
      <input name="News" type="checkbox"> Add me to your email newsletter
    </label>
  </div>

  <div class="input-group">
    <button type="submit" name="submit" class="btn">Submit</button>
  </div>

</form>

<script>

  function handleChange(event) {
    // track your change
    console.log(event.currentTarget);
  }

  var formEls = document.getElementsByTagName('input');

  for (var i = 0; i < formEls.length ; i++) {
    formEls[i].addEventListener('change', handleChange, false);
  }

  // easier with jQuery, but...
  $('input').change(handleChange);

</script>
Here's a form with a lot of different inputs. Could try and target all the elements individually.

Example: live editing a form

<script>

  function handleChange(event) {
    // track your change
    // this time on e.target
    console.log(event.target);
  }

  $('#form').change(handleChange);

</script>
so much easier to target the form alone

Example: binding to dynamic content

Propogation still occurs even though it's added later

<script>

  // I do this all the time!
  $('body').on('click', '#modalExit', function(e) {
	// exit the modal
  });

  // even better
  $('#modal').on('click', '#modalExit', function(e) {
  });

</script>
Super bonus, dynamic content. Let's say you have a super annoying modal that your client asked you to put in from jquery docs: Attaching many delegated event handlers near the top of the document tree can degrade performance No good translation, just say let's move on

3) Explain why the following doesn't work as an IIFE:

 

function foo(){
  // i pity this code
}();

Immediately invoked function expression

Firefox - SyntaxError: expected expression, got ')' literally had no idea what IIFE meant; it runs itself; what is wrong with this code?

Functions as expressions vs. definitions

function foo(){
  // i am known as
  // a definition or statement
}

var foo = function() {
  // i am an expression
  // i resolve to a value, even if just "undefined"
};
MDN - An expression is any valid unit of code that resolves to a value. functions can either be written as simple definitions, or as expressions. difference here is that JS expects a value from the latter.

Functions as expressions vs. definitions

// this thing here
function foo(){

}();

// is as if you
function foo(){

}

();
// wrote it on separate lines
writing it the first way would behave similarly to how JS would see an if statement.

3a) What needs to be changed to properly make it an IIFE?

 

(function foo(){ })();

 

behold the parentheses

parens here essentially turn this into an expression

Why would I ever use one?

Control variable scope

(function foo(){ })();

console.log(foo);
Firefox - ReferenceError: foo is not defined
foo can't be called outside, leads to another great question

4) Why is it, in general, a good idea to leave the global scope of a website as-is and never touch it?

You can't predict the future

 

  • Reduce conflicts
  • Maintain independence
  • Easier to write your own code
We all thought hoverboards would be made by a toy manufacturer and readily available. Instead they're made by lexus. Don't have to worry as much about namespacing variable names, etc. with large scale apps likely use a tool to help manage this, but useful to think about on small scale websites

5) Explain "hoisting".

 

all variables are declared at the top of any given function scope whether you like it or not

While we're on the subject of scope. Never heard this term in my life until a few weeks ago.

Example - how I write it

 

 1  function hoist(track) {
 2    if (track === 'Down With Disease') {
 3      var action = 'dance';
 4    }
 5    else {
 6      var action = 'skip':
 7    }
 8
 9    return action;
10  }

line 6 error: 'action' is already defined

Example - what JS does to it

 

 1  function hoist(track) {
 2    var action;
 3    if (track === 'Down With Disease') {
 4      action = 'dance';
 5    }
 6    else {
 7      var action = 'skip':
 8    }
 9
10    return action;
11  }

var declaration "hoisted" to top

So, yeah, technically, this works

 

 1  function hoist(track) {
 2    if (track === 'Down With Disease') {
 3      action = 'dance';
 4    }
 5    else {
 6      action = 'skip':
 7    }
 8
 9    var action;
10
11    return action;
12  }

cue collective moan

What do we do with this knowledge?

  • Many recommend declaring all variables at the top of the function
  • Makes it clearer which vars are scoped
  • Does it make the rest harder to read?
ask if anyone has ever gotten bit by hoisting. How people declare variables. Harder to see what vars have a value?

6) What's the difference between a variable that is: null, undefined or undeclared?

Speaking of variables, this one I knew, but maybe couldn't quite verbalize.

Undeclared

foo = 5;
Firefox - ReferenceError: foo is not defined

you forgot something

Besides being a short lived show on Fox, undeclared is simply that, you haven't declared it using var, and therefore it's as if it doesn't exist. Reference the earlier error when we tried to console the function name of the IIFE.

undefined

undefined is not a function. developer jokes you guys!

var foo;
var bar = {};
var baz = ['jonny', 'phil', 'ed'];
var qux = function() {
  // don't return anything
};

console.log(foo, bar.name, baz[4], qux());
// all print undefined
  • variable exists but no defined value (not initialized)
  • object exists but without that key
  • array exists but nothing at index
  • function exists but doesn't return anything
  • falsy
before researching I could tell you with full certainty that undefined is not a function.

null

var foo = null;

console.log(foo);
// prints null
  • null has a value. Its value is null.
  • null is a "nothing" value
  • not zero, not an empty string/object/array
  • falsy
Use case here might be working with data from a server. Let's say you set a var to equal the value of a specific key returned by a JSON object. If it comes back as undefined, that means it didn't exist on the object. If it returns null, then it exists but has no value assigned to it.

6a) How would you go about checking for any of these states?

Undeclared finds you. Except if you're writing in the global scope!

// global scope
foo = 5;

console.log(foo);
// prints 5!
// implied global, aka a reason people hate JS

check for undefined

var foo;

console.log(typeof foo); // "undefined" as a string
console.log(typeof bar): // undeclared, but also returns "undefined" AARGH

// preferred
console.log(foo === undefined); // true boolean

var baz = 'undefined';
console.log(baz === undefined); // false. Hooray! maybe?
typeof ignores undeclared variables

check for null

var foo = null;

console.log(typeof foo); // object    let that sink in for a minute

// preferred
console.log(foo === null); // true boolean
this is literally a bug in javascript

7) What is the difference between == and === ?

Might as well. the very first thing you learn but it bears repeating

check out this badness

var foo; // undefined
var bar = null; // null

// compare the two
console.log(foo == bar); // true boolean

remember these guys?

Double equals checks for equality

 

Triple equals checks for equality and type

 

Wield accordingly.

double actually converts both to the same type before comparing. Feel free to use double equals, but when appropriate. JSHint may bark at you.

8) What is the event loop?

8a) What is the difference between call stack and task queue?

story time

 

var markup = Handlebars.compile(template)(model);

this.$el.html(markup);

this.$el.foundation('reflow');

 

this would never work

best explained with this story. use foundation's form validation. have to reflow if you're adding to the dom. this would never work however

story time

var markup = Handlebars.compile(template)(model);

this.$el.html(markup);

var self = this;

setTimeout(function() {

  self.$el.foundation('reflow');

}, 0);
Defers invoking the function until the current call stack has cleared

(whatever that means)

best explained with this story. use foundation's form validation. have to reflow if you're adding to the dom. this would never work however

explained

  • Single-threaded
  • Call Stack
  • Task Queue
  • Event Loop
borrowed this image from MDN. JS is what is known as a �single threaded� which basically means one thing at a time. As your JS is run, it handles one function at a time in the order in which they are called. It creates a LIFO stack of these called the call stack. While it is processing these things in order, the browser is effectively blocked (repaints, etc). The task queue is another queue used by the browser to keep track of things that need to be executed. It is separate from the call stack. These are handled in the order in which they come in. Event loop waits on the stack to clear and then adds from the queue.

why this works

var markup = Handlebars.compile(template)(model);

this.$el.html(markup);

var self = this;

setTimeout(function() {

  self.$el.foundation('reflow');

}, 0);

setTimeout takes function from stack and puts in queue

setTimeout is part of the Web API, provided by your browser

Philip Roberts: What the heck is the event loop anyway?

You're hired!

just so topical

Loads more

many of which would require an hour on there own

Just keep building

that list can look pretty intimidating. reemphasize that it's not all about knowing every in and out of a language but building awesome things!
Why I'm not a JavaScript developer The dreaded interview questions... Created by Russ Anderson / @RealRealRuss Don't linger here just get started.