O'Reilly logo

JavaScript for PHP Developers by Stoyan Stefanov

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 3. Functions

Functions are an important topic in JavaScript because the language has many uses for them. In their most basic form, they look like a PHP function:

// Works in both languages
function sum($a, $b) {
  return $a + $b;
}

sum(3, 5); // 8

Default Parameters

There’s no syntax that allows you to have a default value of a function parameter, as is often done in PHP. This is scheduled for a future version of ECMAScript, but for now you have to take care of this yourself inside the body of your function. Let’s say you want the second parameter to default to 2:

// PHP
function sum($a, $b = 2) {
  return $a + $b;
}
// JavaScript
function sum(a, b) {
  b = b || 2;
  // Also sometimes written as
  // b || (b = 2)
  return a + b;
}

This is a short syntax that works fine in many cases, but it’s a little naive in this particular example because b || 2 is a loose comparison for b. If you pass 0 as an argument, the comparison evaluates to false and b becomes 2:

sum(3);    // 5
sum(3, 0); // 5, not what you'd expect

A longer version is to use typeof:

function sum(a, b) {
  b = typeof b === "undefined" ? 2 : b;
  return a + b;
}

sum(3, 0); // 3
sum(3);    // 5

Any Number of Arguments

You don’t have to pass all the arguments that a function expects, and JavaScript won’t complain. In other words, there are no required parameters. If you need to make a parameter required, you need to enforce this in the body of your function.

You can also pass more arguments than a function expects, and these are happily ignored without ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required