Skip to Content
JavaScript for PHP Developers
book

JavaScript for PHP Developers

by Stoyan Stefanov
April 2013
Intermediate to advanced content levelIntermediate to advanced
160 pages
3h 2m
English
O'Reilly Media, Inc.
Content preview from JavaScript for PHP Developers

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP 7: Real World Application Development

PHP 7: Real World Application Development

Doug Bierer, Altaf Hussain, Branko Ajzele

Publisher Resources

ISBN: 9781449336059Errata Page