0 / 0

Die Neue JavaScript Grotesk

Noah Burnery

DevChatt / March 2010



// Double click this code to play around
function whatsup(){
  // Use the `say` function to output stuff
  say( 'Hello' );
  say( 'and Welcome.' );
}
whatsup();

    How do I work this thing?

    1. Source code's on the left; Description on the right.
    2. Browse slides with the arrows at the bottom, or the arrow keys
    3. Click "Hack on this" to play with the JavaScript code, and run it.
    4. While hacking, click "Run" to run your code; "Reset" to set it back to the starting point.


    Also, the textarea is slightly enhanced to make coding a bit more pleasant:

    1. Select some code, and then use Cmd/Ctrl + ] or Cmd/Ctrl + [ to indent / outdent a chunk of code.
    2. With text selected, type ( or ' or " or [ or {, to wrap the selection in a pair of whichever character.
    3. Tab & Delete & Return line things up like you would expect them to in a normal code editor.

    Part One

    var counter = 3;
    // Do some stuff
    // .......
    function count(){
      for( counter = 1; counter < 6; counter++ ){
        say( "Number " + counter );
      }
    }
    count();
    say( counter ); // => 6 not 3
    

      Variable Declaration

      You should always use the var keyword, or else crazy things might happen.

      var counter = 3;
      // Do some stuff
      // .......
      function count(){
        for( var counter = 1; counter < 6; counter++ ){
          say( "Number " + counter );
        }
      }
      count();
      say( counter ); // => 3, untouched
      

        Variable Declaration

        Phew.

        A = 1;
        var B = 2;
        say( window.A ); // => 1
        say( window.B ); // => undefined
        

          Variable Declartion

          No var ? A property is added to the global window object.

          var A = 1;
          var B = 2;
          var C = 3;
          
          var A = 1,
              B = 2,
              C = 3;
          
          
          
          

            Variable Declaration

            Use commas to var a bunch of things at once.

            var obj = { 'A':11, B:22, C:{ D:33 } };
            say( obj.A ); // => 11
            say( obj['B'] ); // => 22
            say( obj['C'].D ); // => 33
            
            alert( 'Hello' ); // => "Hello"
            window.alert( 'Hello' ); // => "Hello"
            window[ 'alert' ]( 'Hello' ); // => "Hello"
            
            

              Object (Literal)s

              Access properties of objects with obj.something or obj['something'].

              All global functions are actually just properties on the window object.

              // Familiar function declaration style
              function english(){
                say( "Hello" );
              }
              english();
              
              // Familiar variable declaration & assignment
              var something = 'or another'; 
              
              // You can also define functions this way
              var japanese = function(){
                say( "Kon'nichiwa" );
              };
              japanese();

                Declaring Functions

                There are a couple of ways to define a function.

                var japanese = function(){
                  say( "Kon'nichiwa" );
                };
                
                japanese(); // => "Kon'nichiwa"
                ( japanese )();// => "Kon'nichiwa"
                
                (function(){
                  say( "Kon'nichiwa" );
                })(); // => "Kon'nichiwa"
                

                  Calling Functions

                  You can also call functions a few ways; the key is the set of parentheses.

                  // You can even mix and match styles
                  var korean = function hangukeo(){
                    say( "An'nyeong" );
                  };
                  korean(); // => "An'nyeong"
                  
                  var korean = function hangukeo( again ){
                    say( "An'nyeong" );
                    if( again )
                      hangukeo();
                  };
                  korean( true ); // => "An'nyeong" x 2
                  
                  
                  

                    Declaring Functions, con't…

                    You can even name a function, and assign it to a variable.

                    var num = 3, first = function(){}, second = first, third = second;
                    // Familiar If - Else If - Else
                    if( num === 1 ){
                      first();
                    } else if( num === 2 ){
                      second();
                    } else {
                      third();
                    }
                    
                    // Brackets optional for single lines
                    if( num === 1 )
                      first();
                    else if( num === 2 )
                      second();
                    else
                      third();
                    
                    

                      Control Structures

                      The Brackets are optional

                      // You can nest bracketlessly
                      for( var a = 1; a < 4; a++ )
                        for( var b = 1; b < 6; b ++ )
                          if( (b * a) % 2 === 0 )
                            say( a * b + 'is even.' );
                          else
                            say( 'odd' );
                      

                        Control Structures

                        You can drop brackets with any control structure.

                        var result;
                        if( false )
                          result = 'The Truth';
                        else
                          result = 'A Lie';
                        say( result );
                        
                        // OR
                        say( true ? 'The Truth' : 'A Lie' );
                        

                          Ternary Operator

                          JavaScript has a ternary operator; it returns a value.

                          var size = 57,
                              conclusion = size > 50 ? 'big' : 'normal';
                          say( size + " huh? That's " + conclusion );
                          
                          

                            Ternary Operator

                            function judge( size ){
                              say( size + " huh? That's " + (
                                size > 200 ? 'Humongous' :
                                size > 50 ? 'Big' :
                                size > 10 ? 'Normal' :
                                  'tiny'
                              ) + ', yo' );
                            };
                            
                            judge( 394 );
                            judge( 7 );
                            
                            
                            
                            

                              Ternary Operator

                              They can be nested too.

                              Number.prototype.times = function( fn ){
                                for( var n = 0; n < this; n++ )
                                  fn( n );
                              };
                              
                              ( 5 ).times( function( x ){
                                say(
                                  x + 1 + ' Hello' + ( x > 0 ? 's' : '' )
                                );
                              });
                              

                                Prototypes with Native Objects

                                Just like with your own objects, you can add to and modify the prototypes of Native objects, too.

                                Array.prototype.to_s = function(){
                                  return '[' +
                                    this.map( function( item ){
                                      return ( typeof item === 'string' ) ?
                                        '"' + item + '"' : item;
                                    }).join(', ') +
                                  ']';
                                };
                                
                                
                                var a = [1,2,'A',3,'foo'];
                                say( a.to_s() );

                                  Prototypes with Native Objects

                                  function hello(){
                                    say( 'Hello.' );
                                  }
                                  hello.call();
                                  

                                    Function.call & Function.apply

                                    All functions have a call method, which executes the function.

                                    var o = { name: 'Rufus' };
                                    function imposter(){
                                      say( 'My name is ' + this.name );
                                    }
                                    imposter.call( o );
                                    

                                      Function.call & Function.apply

                                      call can take arguments. The first argument is the context.

                                      function greet( greeting, name ){
                                        say( greeting + ', ' + name + '. ' );
                                      }
                                      greet.call( null, "Kon'nichwa", "Noah" );
                                      
                                      
                                      greet.apply( null, [ "Annyeong", "Noah" ] );
                                      greet.apply( null, "Whaddup/Breh".split('/') );
                                      
                                      

                                        Function.call & Function.apply

                                        Any other arguments passed to call get passed through to the function itself. Function.apply is similar to call, but takes an array for the function arguments.

                                        var list = [ 1, 2, 3 ];
                                        Array.prototype.push.call( list, 4, 5, 6 );
                                        say( list[ 4 ] );
                                        
                                        

                                          Using .call with prototypes

                                          You can use Native object methods on other objects by using call, and passing the object in as the context.

                                          function dummy(){
                                            say( '...........' );
                                          }
                                          say( dummy[1] );
                                          Array.prototype.push.call( dummy, 1, 2, 3 );
                                          say( dummy[1] );
                                          dummy(); // Still works
                                          

                                            Using .call with prototypes

                                            function echo( foo ){
                                              say( foo + arguments[0] );
                                            }
                                            echo( 'POW!' );
                                            
                                            function echo2(){
                                              say( arguments[0] + arguments[1] );
                                            }
                                            echo2( 'POW!', 'BOOM!' );
                                            
                                            
                                            
                                            

                                              The `arguments` variable

                                              Inside of a function call, there lives a magical, array-like arguments variable that contains all of the arguments passed to the function.

                                              function echo3(){
                                                say( Array.prototype.join.call( arguments, '...' ) );
                                              }
                                              echo3( 'POW!', 'BOOM!', 'BANG!' );
                                              
                                              function echo4(){
                                                var args = Array.prototype.slice.call( arguments );
                                                while( args.length )
                                                  say( args.shift() );
                                              }
                                              echo4( 'POP!', 'BLOW!', 'ZZZZ!' );
                                              
                                              
                                              
                                              
                                              
                                              

                                                The `arguments` variable

                                                Since arguments work kind of like arrays, you can use Array functions on them with call.

                                                Part Two

                                                function plug(){
                                                  for( var n = 0; n < 3000; n++ )
                                                    $('<div />').appendTo('body').remove();
                                                }
                                                
                                                function chug(){
                                                  for( var n = 0; n < 5000; n++ )
                                                    for( var o = 0; o < 8000; o++ )
                                                      n % o;
                                                }
                                                
                                                function loadup(){
                                                  plug(); say('1/4');
                                                  chug(); say('2/4');
                                                  plug(); say('3/4');
                                                  chug(); say('4/4');
                                                }
                                                loadup();
                                                
                                                
                                                
                                                
                                                

                                                  JavaScript Progress Bar

                                                  In a web browser, the page won't update/redraw until JavaScript execution completes.

                                                  var counter = 0,
                                                      total = 0;
                                                  
                                                  loadup( plug, chug, plug, function(){ alert("WEEEEE!"); }, chug, plug );
                                                  
                                                  function loadup(){
                                                    var fns = Array.prototype.slice.call( arguments );
                                                    if( typeof fns[0] === 'function' )
                                                      total = fns.length;
                                                    else
                                                      fns.shift();
                                                  
                                                    fns.shift().call();
                                                    fns.unshift( 'Not first' );
                                                  
                                                    if( fns.length > 1 )
                                                      setTimeout( function(){
                                                        loadup.apply( null, fns );
                                                      }, 0 );
                                                  
                                                    say( ++counter + '/' + total );
                                                  }
                                                  
                                                  function plug(){
                                                    for( var n = 0; n < 3000; n++ )
                                                      $('<div />').appendTo('body').remove();
                                                  }
                                                  
                                                  function chug(){
                                                    for( var n = 0; n < 5000; n++ )
                                                      for( var o = 0; o < 8000; o++ )
                                                        n % o;
                                                  }
                                                  
                                                  

                                                    JavaScript Progress Bar

                                                    Using setTimeouts give the browser a change to breathe.

                                                    // Ripped from John Resig's Secrets of the JavaScript ninja
                                                    Function.prototype.memoized = function( key ){
                                                      this._values = this._values || {};
                                                      return this._values[key] !== undefined ?
                                                        this._values[key] :
                                                        this._values[key] = this.apply(this,arguments);
                                                    };
                                                    
                                                    Function.prototype.memoize = function(){
                                                      var fn = this;
                                                      return function(){
                                                        return fn.memoized.apply( fn, arguments );
                                                      };
                                                    };
                                                    
                                                    var isPrime = function( num ) {
                                                      var prime = num != 1;
                                                      for ( var i = 2; i < num; i++ ) {
                                                        if ( num % i == 0 ) {
                                                          prime = false;
                                                          break;
                                                        }
                                                      }
                                                      return prime;
                                                    };
                                                    var isPrimeM = isPrime.memoize();
                                                    

                                                      Memoize Function

                                                      Computationally expensive functions can be optimized by storing computed values instead of recaculating every time.

                                                      Final Q&A

                                                      Danke Schoën!

                                                      http://royowl.com
                                                      @nwah