Question: Ideally I want to be able to write something like:

```
function a( b ) {
    b.defaultVal( 1 );
    return b;
}

```

The intention of this is that if `b` is any defined value, `b` will remain as that value; but if `b` is undefined, then `b` will be set to the value specified in the parameter of `defaultVal()`, in this case `1`.

Is this even possible?

Ive been toying about with something like this:

```
String.prototype.defaultVal=function(valOnUndefined){
    if(typeof this==='undefined'){
        return valOnUndefined;
    }else{
        return this;
    }
};

```

But I'm not having any success applying this kind of logic to *any* variable, particularly undefined variables.

Does anyone have any thoughts on this? Can it be done? Or am I barking up the wrong tree?

Answer: 
Well the most important thing to learn here is if a variable is `undefined` you, by default, do not have any methods available on it. So you need to use a method that can operate on the variable, but is not a member/method *of* that variable.

Try something like:

```
function defaultValue(myVar, defaultVal){
    if(typeof myVar === "undefined") myVar = defaultVal;
    return myVar;
}

```

What you're trying to do is the equivalent of this:

```
undefined.prototype.defaultValue = function(val) { }

```

...Which for obvious reasons, doesn't work.
While the two answers already provided are correct, the language has progressed since then. If your target [browsers support](https://kangax.github.io/compat-table/es6/) it, you can use *default function parameters* like this:

```js
function greetMe(greeting = "Hello", name = "World") {
  console.log(greeting + ", " + name + "!");
}

greetMe(); // prints "Hello, World!"
greetMe("Howdy", "Tiger"); // prints "Howdy, Tiger!"
```

[Here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters) are the MDN docs on default function parameters.