Please login or register. Welcome to the Studio, guest!


Quick Links:


newBookmarkLockedFalling

Scorpian

Scorpian Avatar

******
[ Bracket Admin ]

2,457


April 2006
Alright, now in JavaScript, there are several ways to execute certain commands under certain circumstances. There's the classic if/else statement:

if(condtion){
code to be executed if true
}else{
code to be executed elsewise
}


There's also the switch/case function:

switch(variable){
case "value": code to be executed break;
case "value2": code to be executed break;
default: code to be executed if neither of above break;
}


However, what some people don't seem to realize is the use of one-line conditionals. But wait, what are "one-line conditionals"? Well, they're an if/else statement that's used to store a value on "one-line", so to say. For example, let's say that you are trying to calculate whether the value of the variable vamp is 20 or 30. In order to do this, we need to know the vaule of trip, which is 10 more then vamp needs to be. How could we do this? Well, we could use an if/else statement, like this:

if(trip == 30){
var vamp = 20;
}else{
var vamp = 30;
}


That's one way to do it, but that seems kind of long, doesn't it? Let's use a one-line conditional, also known as a ternary operator, instead:

var vamp = (trip == 30) ? 20 : 30;

Way shorter, isn't it? So, how did we do it? Here's what a one-line conditional looks like:

variable = (condition) ? what to store if true : what to store if not true;

Remember, you can also use this to store different vaules for object properties. For example:

theTable.style.display = (theTable.style.display == 'none') ? 'block' : 'none';

This can also be used in another way, don't forget.

var table = theTable[(x == 0 ? 1 : 0)];

That layout is slightly different from the one I showed you. It's the same, but you move the closing ) to after the "else" value, and before the ending semicolon. This is used to find variables in one small chunk right in the middle of another code, eliminating the need for an extra variable to store the vaule in.

In conclusion, the use of one-line conditionals can be used to seriously shorten then length of a code. It can get rid of unnecessary variables and loading time that will slow the user down. Overall, it's pretty useful.


Last Edit: Nov 19, 2006 22:29:22 GMT by Scorpian
wat

newBookmarkLockedFalling