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();
Also, the textarea is slightly enhanced to make coding a bit more pleasant:
var counter = 3;
// Do some stuff
// .......
function count(){
for( counter = 1; counter < 6; counter++ ){
say( "Number " + counter );
}
}
count();
say( counter ); // => 6 not 3
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
Phew.
A = 1; var B = 2; say( window.A ); // => 1 say( window.B ); // => undefined
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;
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"
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();
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"
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
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();
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' );
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' );
JavaScript has a ternary operator; it returns a value.
var size = 57,
conclusion = size > 50 ? 'big' : 'normal';
say( size + " huh? That's " + conclusion );
function judge( size ){
say( size + " huh? That's " + (
size > 200 ? 'Humongous' :
size > 50 ? 'Big' :
size > 10 ? 'Normal' :
'tiny'
) + ', yo' );
};
judge( 394 );
judge( 7 );
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' : '' )
);
});
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() );
function hello(){
say( 'Hello.' );
}
hello.call();
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 );
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('/') );
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 ] );
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
function echo( foo ){
say( foo + arguments[0] );
}
echo( 'POW!' );
function echo2(){
say( arguments[0] + arguments[1] );
}
echo2( 'POW!', 'BOOM!' );
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!' );
Since arguments work kind of like arrays, you can use Array functions on them with call.
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();
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;
}
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();
Computationally expensive functions can be optimized by storing computed values instead of recaculating every time.
http://royowl.com
@nwah