How To Set Default Arguments To JavaScript Function


First of all, if you are Turkish, you can read this article in Turkish.
Let say you’re creating a function that using parameter(s). What if you forget to write this parameter when you calling it? Answer is: “undefined”. Let’s solve this problem using default parameter.

So, I’m creating a simple function for example.

setTitle = function(what) {
document.write("<h2 class='title' rel='bookmark'>"+what+"</h2>");
setTitle("How To Set Default Arguments To JavaScript Function");

We can use this setTitle function with a string. But if we had a mistake or forget to write a parameter on our function, it returns “undefined“.
For solving this problem:

setTitle = function(what) {
what = typeof what !== 'undefined' ? what : "Y U NO ADDED A TITLE!";
document.write("<h2 class='title' rel='bookmark'>"+what+"</h2>");
setTitle(); // -> <h2 class='title' rel='bookmark'>Y U NO ADDED A TITLE!</h2>
setTitle("This is a kind of title"); // -> <h2 class='title' rel='bookmark'>This is a kind of title</h2>


This was just a default function parameter example. When you create complex functions that able to have more than 3 or more parameters, this default parameter trick might help you a lot. If you have questions or tips and tricks, please don’t be shy to add a comment.
By the way, this one is my first English article. Please warn me if I had grammer mistakes or misspellings.

How To Set Default Arguments To JavaScript Function” için 1 yorum

Bir Cevap Yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir