Helping ordinary people create extraordinary websites!
GET OUR NEWSLETTER
Your Email:
 

Essential Javascript -- A Javascript Tutorial

By Patrick Hunlock
2007-12-02


JavaScript Conditionals: Shorthand Assignment

Javascript supports more advanced constructs. Often you will see code like the following…

function doAddition(firstVar, secondVar) {
   
var first = firstVar  || 5;
   
var second= secondVar || 10;
   
return first+second;
}

doAddition
(12);

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


 | Bookmark
Related Tutorials:
» JavaScript Debugging Techniques with Firebug
» Striped Tables Using JavaScript
» Opening PDFs in a New Window with JavaScript
» Submit Forms Conditionally using JavaScript
» How to Setup a Randomising Function
» Introduction to JavaScript Tutorial

Advertise with Us!


Tutorials Scripts Web Hosting Developer Manuals
Resources