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: 
Why not use the default operator:

```
function someF(b)
{
    b = b || 1;
    return b;
}

```

Job done! Here's [more info](http://javascript.crockford.com/style2.html) about how it works.

Just as a side-note: your prototype won't work, because you're augmenting the `String` prototype, whereas if your variable is undefined, the `String` prototype doesn't exactly apply.

To be absolutely, super-duper-sure that you're only switching to the default value, when `b` really is undefined, you could do this:

```
var someF = (function(undefined)//get the real undefined value
{
    return function(b)
    {
        b = b === undefined ? 1 : b;
        return b;
    }
})(); // by not passing any arguments

```
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.