This is the 1st HTML5 slant canvas

KIWY logo depicting a kiwi bird with a candle

k i w y

Need a light for your site?

This is the 2nd HTML5 slant canvas

JavaScript

  1. What you must know
  2. Alert Box and placement of JS on a page
  3. Show and Hide something by clicking another thing
  4. (jQuery) Enable touch on mobile

Scope of local/global variables functions


var i = 1; // global var

function kim(){

var j = i; // local var

var k = ++j; // what happens when ++i?

return k;

}

var a = kim(); // Local: 2 Global: 2

var b = kim(); // Local: 2 Global: 3

var c = kim(); // Local: 2 Global: 4

Scope of local/global variables functions


var input, output;

input = 1;

output = function(){return input;};

input = 2;

output(); // Pop Quiz: What is the result of this output?

Named function


function kim(){

   /* code */

}

kim(); // call me


Anonymous fuction


var kim = function(){

   /* code */

};

kim(); // call me


Function Declaration Error


function(){ // Error because it thinks it's a func declaration and expects a function name
 /* code */
}();


Unrelated Expression Error


function kim(){ // There. we have a name. NOW what's the problem?
 /* code */
}(); // The problem is (); because it seems like an unrelated expression

// see the above syntax for named expression for comparison


2 Ways to do Immediately Invoked Function Expression


(function(){

 /* code */

})();


(function(){
 /* code */
}());


Why is it incorrect to call it a self-invoked annonymous function?

 

It's not recursive (it doesn't call itself) and it doesn't have to be anonymous.

 

Example of where IIFE is needed


for ( var i = 0; i < 10; i++ ) {

var output = function(){return i;}; // BAD. It will always return the highest value of i

console.log(output); // 999999999

}

for ( var i = 0; i < 10; i++ ) {

var output = (function(x){return x;}(i)); // GOOD. It increments as expected

console.log(output); // 0123456789

}