JavaScript Functions: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
Line 3: Line 3:


=Overview=
=Overview=
=Function Syntax=
<syntaxhighlight lang='javascript'>
<syntaxhighlight lang='javascript'>
function name(parameter1, parameter2, parameter3) {
function name([parameter1[, parameter2, [...]]]) {
   // code to be executed
   // code to be executed
  [statements]
}
}
</syntaxhighlight>
</syntaxhighlight>

Latest revision as of 02:12, 10 December 2020

Internal

Overview

Function Syntax

function name([parameter1[, parameter2, [...]]]) {
  // code to be executed
  [statements]
}

Function Parameters and Arguments

The names listed in the function definition are the function parameters. The values passed to the function are the function arguments.

A JavaScript function does not specify data types for its parameters, it does not perform type checking on its arguments and it does not check the number of arguments received.

Missing Argument

If a function is called with missing arguments, the corresponding argument values are set to undefined.

function test(a, b) {
    console.log(a);
    console.log(b);
}
test('something');
something
undefined

Default Paramenter Value

ECMAScript 2015 allows default parameter values in the function declaration:

function test(a, b = 2) {
  // ...
}

The arguments Object

A function has a built-in object called the arguments object. The arguments object contains an array of the arguments used when the function was invoked:

function test() {
  var i;
  for(i = 0; i < arguments.length; i ++) {
    console.log(arguments[i]);
  }
}
test(1, 2, 3, 20, 50);

Pass by Value and by Reference

Arguments of the function are passed by value: the function only gets to know the argument value, not the argument's location. If the function changes an argument's value, it does not change the parameter's original value.

However, in JavaScript object references are values, so because of this objects will behave like they are passed by reference. If a function changes an object property, it will change the state of the object, so changes to an object state are visible outside the function.

Declaration

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function

Function Expressions

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function