Javascript Programming

Q: What are the features of the Javascript language?

A: functions, loose typing, dynamic objects, prototypal inheritance, and object literal notation (comma-separated name/value pairs inside curly brace). The bad ideas include a programming model based on global variables. It is one of the only lambda languages (along with LISP).

Q: What makes Javascript a “functional language”?

A: (1) it supports passing functions as arguments to other functions, returning them as the values from other functions, see  assigning them to variables or storing them in data structures. (2) It is a lambda language, which means it supports anonymous functions.

Q: What datatypes are supported in Javascript?

A: Number, String, Boolean, Object, Array, undefined

Q: Explain how threading works in JavaScript.

A: JavaScript is single threaded. Unlike Java where one can use interrupts and yields to pop in and out of code blocks, any method that is running will run until completion. User click events, or setTimeout/setInterval calls that trigger callbacks, pushes those callbacks onto a queue. So if a user clicks while some insanely long method is already executing, there will be a delay before the queued callback gets reached. Also if event bubbling results in single clicks propagating multiple callbacks, they too will be called in order rather than producing a simultaneity that one might erroneously expect.

Objects

Q: Why can an object be created by either "myObj = {}" or "function myObj()"?

A: The first creates an object, the second is a constructor, i.e. the recipe for making an object with new myObj()

Q: Show two ways of writing a constructor.

A: function Bar() { this.method = function() {}; }, which would be call with var bar = new Bar()

Or, factory style: function Animal(name) { return { run: function() {  alert(name + " is running!") }

  }}, then create with var animal = Animal(‘fox’) then animal.run()

Q: Give an example of inheritance.

A:  create an instance, mutate it, create a factory constructor that returns it.
function Rabbit(name) {

      var rabbit = Animal(name); // make animal

      rabbit.bounce = function() { // mutate

          this.run()

          alert(name + " bounces to the skies! :)")

      }

      return rabbit // return the result

   };

var rabbit = Rabbit("rab")

rabbit.bounce()

Q: How do you create a private/protected method?

A: Any methods not returned by the constructor remain private to the constructor.

Q: Explain the purpose of the Object.hasOwnProperty() method.

A: Any instance of an object has its own fields plus any of the fields inherited from its prototype. When looping through an object's fields, often we are only interested in the instance fields, not the prototype members. So inside a for (key in myObj) loop, we want to act only on the fields that pass the myObj.hasOwnProperty(key) test.

Q: How do you accomplish object inheritance in Javascript?

A: Use Object.create(), passing the parent object as an argument.  (Note: ie8 does not support.)

Q: What does every object inherit?

A: When you say var foo = {} you are actually executing var foo = Object.create(Object.prototype). You have created an object that inherits from prototype, which has the functions toString(), toLocaleString(), valueOf(), hasOwnProperty(), isPrototypeOf() and isPropertyEnumerable(). It also has the property constructor, which is an object. The prototype of prototype is null.

You can actually create an object which does not inherit from prototype with var foo = Object.create(null). It will not have a toString() function, for example.

Note: IE does not have Object.create().

Q: What are Javascript closures? How are they useful?

A: A closure is (1) a stack-frame which is not deallocated when the function returns and (2) a kind of object that combines a function along with any local variables that were in-scope at the time that the closure was created.

Closures reduce the need to pass state around the application. The inner function has access to the variables in the outer function so there is no need to store the information somewhere that the inner function can get it.

this

Definition:  “when a function executes, it gets the this property—a variable with the value of the object that invokes the function where this is used”

this is used inside a function (let’s say function A) and it contains the value of the object that invokes function A.”

this is really just a shortcut reference for the invoking object.”

Closures are not objects:  don’t confuse an invoking object with a closure.  “closures cannot access the outer function’s this variable by using the this keyword because the this variable is accessible only by the function itself, not by inner functions.

var myObj = {

    foo: 'bar',

    wow: function() {

      console.log('foo is ' + this.foo);  // prints ‘bar’...myObj is the “invoking object”

      this.foo = ‘changed’;  // exists only in wow function

      function hmm() {    // The closure is not the invoker.

                                                   // myObj.foo not available in inner function

         console.log('foo is ' + this.foo);  // prints undefined

      }

      hmm();

    }

};

myObj.wow();

Output:

foo is bar

foo is undefined

Miscellaneous

Q: What is the difference between == and ===?

A: The == checks for value equality, but === checks for both type and value.

Q: Difference between window.onload and onDocumentReady?

A: The onload event does not fire until every last piece of the page is loaded, this includes css and images, which means there’s a huge delay before any code is executed. That isn’t what we want. We just want to wait until the DOM is loaded and is able to be manipulated. onDocumentReady allows the programmer to do that.

4. What is the difference between undefined value and null value?

A: undefined means a variable has been declared but has not yet been assigned a value. On the other hand, null is an assignment value and is an object. Also, undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.

Q: Explain Number/String coercing:

"1" + 2 + 4 = "124". 2 + 5 + "8" = 78. It goes from left to right, and String has the last word wherever it occurs.

Q: What is "this"?

TODO this fishy, correct it

A: This refers to the owner object of the function that we're executing. Otherwise, the function's owner is defined by any closure around that function. If there is no closure, then 'this' is the same as 'window'. This will also be true for a function defined with an inline event registration such as onClick=myFunc(2,3).

The rules change for HTML element with events registered by copying the function to the event property, such as onClick=someFunc. In this case, the owner of the function is the HTML element.

You can override the contents of this with:

onClick=myFunc(2,3).bind({foo: 10});

Q: What is event bubbling?

A: Event bubbling describes the behavior of events in child and parent nodes in the (DOM); that is, all child node events are automatically passed to its parent nodes. You can prevent event bubbling with event.stopPropagation()

Q: What is call() and what is apply()?

Both call() and apply() are methods that belong to every function. Both are a way of replacing the function's calling context (i.e. its this) with a different context.  Both take the calling context as the first argument, and the following arguments are for passing arguments to that function. With call() they are passed with a variable number of arguments, and with apply() they are passed as an array.  (Memory aid:  the “a” in apply stands for array!)

Q: Describe the “in” operator.

A. Checking presence of a field in an object. Use if ('foo' in myObj) instead of if (myObj.foo) (which would return false if foo is a zero).         

Q: Describe how you'd write a singleton

A.

function Navtree() {

if (typeof Navtree.instance === 'object') {

return Navtree.instance;

}

Navtree.instance = this;

Q: What is strict mode?

A:  It is an ES5 feature.  It is triggered by “use strict;” (with the quotes).  It guards against: undeclared variables (accidental globals), duplicate argument names, using reserve words, duplicate keys in an object literal, deleting a prototype property, use of deprecated features like with.   Violations will result in thrown exceptions.

Q: How does javascript handle float precision

A: The number has ‘hidden precision’ out to 16 decimal points.  “.1 + .2” is not equal to .3, it may equal 0.30000000000000004.  So beware of == comparisons. Use an epsilon value for a safe comparison:  var isEqual = Math.abs((.1 + .2) - .3) < .0000001

Q:  What is the Asynchronous Loop problem?

A:  Contrary to expectation this will print ‘4’ five times:

for (var i=0; i<4; i++)

{

    var temp = i;

    setTimeout(function(){

        console.log(temp);        

    }, 1000);

}

There are several misleading solutions that look correct but fail to set ‘i’ to the correct scope.  This one works (prints 0,1,2,3,4):

for (var i=0; i<4; i++)

{

    (function(num){

        setTimeout(function(){

            console.log(num);

        }, 1000);

    })(i);

}

Q:  What is the difference between an undeclared variable, and a declared but unassigned variable?

A:  

var bar;

console.log(bar); //returns 'undefined'

console.log(baz) // Uncaught reference error: baz is not defined

Q:  What are some ES6 Features?

  • Array spread operator:  elipsis (…).  Example:  foo(...myArray) is same as calling foo(myArray[0], myArray[1], etc.)
  • Object spread operator: (ES7, actually) You can copy an object (shallow only) with var newObj = {...originalObj}.  
  • Destructured assignment: [a, b, c] = [1, 2, 3], a, b and c will be primitives with values 1, 2 and 3.
  • Rest parameters:  [a, b, ...theRest] = [1, 2, 3, 4, 5];  a and b will be single vars, theRest will be array [3,4,5]
  • Weird destructured assignment:  const {cls: extcls} = this.props means take this.props.cls and assign it to variable extcls.  I’ve seen this in ten-x code.
  • Another weird destructure assignment:  import {init as initUser} from '../client/actions/user'
  • Default arguments:  const foo = (state = 0) => { return state }
  • Template literals:  `here is my ${foo} string`.  Uses backticks.
  • Promises:  built-in now, no need to include a library
  • Block-Scoped Constructs Let and Const
  • Fat Arrow functions:  Special benefit, allows this to behave properly, i.e., this will have the same value as in the context of the function—it won’t mutate. Instead, typically each time you create a closure, this gets mutated.
  • Multi-line Strings:  no need to concatenate strings with + over multiple lines.  Contain everything in one set of quotes and no + sign.
  • Object.assign():  a way of cloning and/or merging objects.  Given:  foo = {wow: 'oldwow', sniff: 'oldSniff'}, then Object.assign({}, {wow: 'ignoredNewWow', sniff: 'newSniff'}, {wow: 'newWow'}) will result in {wow: "newWow", sniff: "newSniff"}.  Note how the “last assignment wins”
  • Classes:  Old way of creating a class involved creating a function that uses this assignments and then creating an instance with new myFunc(), aka the Factory Approach.  Classes do this as well as allow you to create constructors, and call super().
  • Native Modules:  No more AMD, RequireJS, or CommonJS.  Create myModule.js with this content:  module.exports = { ...stuff you want to expose…} and use var mymoduleVar = require(‘myModule’)
  • For-of loops
  • Enhanced Object Literals:  I don’t know this well; elements can be functions?
  • Using E6 in a transitional world:  use Babel as a polyfill for older browsers.
  • Double colon :: bind operator:  ::this.handleStuff does the following ES5 action:  this.handleStuff.bind(this)
  • Dynamic object keys.  You set var foo = ‘myField’ and then var myObj = {[foo]: ‘wow’} and now myObj.myField has value ‘wow’.  
  • async and await (ES7, actually): a new way of doing Promises

Q: What is the Virtual DOM in React?

A: React’s local and simplified copy of the HTML DOM.  a browser-independent DOM system for performance and cross-browser compatibility. You are creating a virtual DOM element when you create a ReactElement.  A ReactElement is a light, stateless, immutable, virtual representation of a DOM Element.  The call to ReactDOM.render() is the moment the virtual DOM code is inserted into the real DOM.

Q: How does asynchrony work in Javascript:

A:  JavaScript is always synchronous and single-threaded. If you're executing a JavaScript block of code on a page then no other JavaScript on that page will currently be executed.

JavaScript is only asynchronous in the sense that it can make, for example, Ajax calls. The code will stop executing until the call returns (successfully or otherwise), at which point the callback will run synchronously. No other code will be running at this point. It won't interrupt any other code that's currently running.

JavaScript timers operate with this same kind of callback.

Describing JavaScript as asynchronous is perhaps misleading. It's more accurate to say that JavaScript is synchronous and single-threaded with various callback mechanisms.

jQuery has an option on Ajax calls to make them synchronously (with the async: false option). Beginners might be tempted to use this incorrectly because it allows a more traditional programming model that one might be more used to. The reason it's problematic is that this option will block all JavaScript on the page until it finishes, including all event handlers and timers.

Rather than blocking the thread, async code gets pushed to an event queue that fires after all other code executes. It can, however, be difficult for beginners to follow async code.

The Event Loop is a queue of callback functions. When an async function executes, the callback function is pushed into the queue. The JavaScript engine doesn't start processing the event loop until the code after an async function has executed. This means that JavaScript code is not multi-threaded even though it appears to be so. The event loop is a first-in-first-out (FIFO) queue, meaning that callbacks execute in the order they were added onto the queue.

timer delay is not guaranteed. Since all JavaScript in a browser executes on a single thread asynchronous events (such as mouse clicks and timers) are only run when there’s been an opening in the execution.

Q: What does an Ajax request written like in core javascript?

A: Let’s translate this jQuery code into core javascript:

$.ajax({

    url: "some/url/1",

    success: function( data ) {

        console.log( data );

    }

})

Here we go:

var xhr = new XMLHttpRequest();   // note:  different solution needed for IE

xhr.open( "GET", "some/ur/1", true );  // doesn’t send it yet...

xhr.onreadystatechange = function( data ) {

    // fires every time readyState changes

    if ( xhr.readyState === 4 ) {

        console.log( data );   // callback code executed here

    }

};

xhr.send( null );  // now it sends.  If there is a payload, that replaces null.

Q:  Describe the difference between these Array methods:  .map, .reduce, and .filter

A: .map returns an array with as many elements as the input.  .filter will return only the elements that pass a boolean test.  .reduce is for cumulative actions such as summing.  Here is a .reduce example:

var numbers = [1, 2, 3, 4];

Var initialTotal = 0

var totalNumber = numbers.reduce(function(total, number){

    return total + number;

}, initialTotal);

// totalNumber will be 10

The second arg to .reduce is the initial value; the first arg to the function passed to .reduce is for passing the accumulating variable.

These three methods often appear in chains to get the result you want.  For example, if you want to transform the original data AND exclude values, you would run a .filter chained to a .map.  For example:

var numbers = [1, 2, 3, 4];

var newNumbers = numbers.filter(function(number){

    return (number % 2 !== 0);

}).map(function(number){

    return number * 2;

});

console.log("The doubled numbers are", newNumbers); // [2, 6]

Q:  What is the History of Javascript?

A: 

  • 1995: JavaScript is born as LiveScript
  • 1997: ECMAScript standard is established
  • 1999: ES3 comes out and IE5 is all the rage
  • 2000–2005: XMLHttpRequest, a.k.a. AJAX, gains popularity in app such as Outlook Web Access (2000) and Oddpost (2002), Gmail (2004) and Google Maps (2005).
  • 2009: ES5 comes out (this is what most of us use now) with forEach, Object.keys, Object.create, and standard JSON
  • 2015: ES6/ECMAScript2015 comes out; it has mostly syntactic sugar, because people weren’t able to agree on anything more ground breaking (ES7?)

Q: Write your own string reverse method, without using string.prototype.reverse()

A:

function reverseString(s) {

   return s.split(‘’).reverse().join(‘’);

}

Ha ha, I cheated by using Array.prototype.reverse()!

Q: No cheating from here on!  Write your own string reverse method, with an iterative approach.

A:

function reverseString(s) {

   var sBuff = [];

   for (var sBuff i = 0, j = s.length - 1; i < s.length; i++) {

            sBuff.push(s[j - i])

   }

   return sBuff.join('')

}

Q: Write your own string reverse method, with an iterative approach, but without for().

A:

function reverseString(s) {

   var sBuff = [];

   s.split('').forEach(function(c) {

            sBuff.unshift(c)

   })

   return sBuff.join('')

}

Q: Write your own string reverse method, without an iterative approach.

A:  Using reduce():

function reverseString(s) {

  return s.split('').reduce(function(accumulator, result) {

      return result + accumulator;

  }, accumulator);

}

(But this is a memory hog)

Q: Write your own string reverse method using reduce(), but without creating a new string on each callback.

A:  

function reverseString(s) {

  var accumulator = [];

  return s.split('').reduce(function(accumulator, result) {

      accumulator.unshift(result);

      return accumulator;

  }, accumulator).join('');

}

Q: Write reverseString() using recursion.

A:

function reverseString(s) {

  return (s === '') ? '' : reverseString(s.substr(1)) + s.charAt(0);

}

Tip


Links marked with arrow icons ( or ) will open in a new tab.

You will see this message only once.