|
Helping ordinary people create extraordinary websites! |
Essential Javascript -- A Javascript TutorialBy Patrick Hunlock2007-12-02
JavaScript Conditionals: Shorthand Assignment Javascript supports more advanced constructs. Often you will see code like the following… function doAddition(firstVar, secondVar) { Here Javascript uses a logical OR (||) to determine if the passed variables actually have a value. In the example we call doAddition with a value of 12 but we neglect to pass a second argument. When we create the first variable firstVar is a non-falsey value (IE it's actually defined) so Javascript assigns firstVar to first. secondVar was never passed a value so it is undefined which evaluates to false so here the variable second will be assigned a default value of 10. You should note that zero evaluates as false so if you pass zero as either firstVar or secondVar the default values will be assigned and NOT zero. In our example above it is impossible for first or second to be assigned a zero. In psuedo code... var someVariable = (assign if this is truthy) || (assign this if first test evaluates false) Tutorial Pages: » Essential Javascript -- A Javascript Tutorial » Getting Started » In-Line Javascript » External Javascript » Javascript is case sensitive » Output (writeln) » Output (alert) » Output (getElementById) » Input (One Click To Rule Them All) » Input (User Input) » Javascript is an Event Driven Language » Comments » Variables » Variable Scope » Special Keywords » Arithmetic Operators » Logical and Comparison Operators » JavaScript Conditionals: IF » JavaScript Conditionals: SWITCH » JavaScript Conditionals: Shorthand Assignment » JavaScript Conditionals: Ternary Operators » JavaScript Loops: FOR » JavaScript Loops: FOR/IN » JavaScript Loops: WHILE » Bringing It All Together » DHTML: Dynamic HTML » Conclusion copyright © 2006, 2007 by Patrick Hunlock |
|