Playing with the VAR statement ( Javascript )
JavaScript's VAR statement
Anytime you need to declare a variable in JavaScript, you need to use the VAR statement. Now it is most commonly used to create a variable, and usually to initially assign the newly created variable a value.
Because JavaScript assumes everything after the equal sign is an equation, you are able to do a couple really neat things while creating variables in JavaScript which would be much more difficult in another langauge.
Define a Variable ( Only if it Does not already exist )
This has to be, in my opinion, one of the more interesting things you can do in JavaScript. Since you can create your JavaScript in multiple files across a single website, it is possible for you to have a need to only create a variable after checking if it does not exist. And you can do that in 1 statement.
var settings = typeof(settings) == 'undefined' ? {} : settings;
This way guarantees that the variable will only be created if it is currently "undefined".
var settings = settings || {};
This is a shorter way as long as the value for variable "settings" is not something JavaScript would consider a false value. ( '', false, 0 ) This will work.
Setting a default parameter value in a function call ( Bonus )
If you are concerned that some of your function calls may be called with out all of the parameters being assigned a value, you can use the ternary operator to help you here as well.
function setBackgroundColor(newColor) {
newColor ? newColor : newColor = '#111";
}
0 comments :
Post a Comment