X

Learn to love default value in Javascript

javascript

Here is another quick tip on JavaScript, the default value in Javascript. If you are coming from the C# world you may have seen something along the line of

string str = person.FirstName ?? "Unknown";

The above code shows the ?? for null coalescing operator in C#, don’t confused it by the generic default value. In JavaScript, there is the double pipe operator ||, where the object is null or undefined.

var str = person.firstName || "Unknown";

function add(x, y) {
  x = x || 0;
  y = y || 0;

  return x + y;
}

alert(add(1));

alert(add('', 1));

alert(add(undefined, 1));

In the above code we have create a function call add and we have defined default values inside of the function. Learn it, love it, use it πŸ™‚ It comes in handy to define default values.

Taswar Bhatti:
Related Post