JavaScript Tutorials

Overview

JavaScript functions are blocks of code designed to perform a particular task when called by another piece of code at some point after creation.

Simple Example

HTML Code (where the result will be placed):

<p id="demo"></p>

JavaScript:

  • A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ()
  • Function names can contain letters, digits, underscores, and dollar signs (same rules as variables)
  • The parentheses may include parameter names separated by commas: (parameter1, parameter2, …)
  • The code to be executed is placed inside curly brackets {}
// function to compute the p1 x p2
function myFunction(p1, p2) {
    return p1 * p2;
}

// code to "call" the above function and do the computation
let result = myFunction(2, 3);
document.getElementById("demo").innerHTML = result;

The Parts of the Function and the Call to the Function

In the following, we have three items:

  • Function name – myFunction
  • Parameters the function will accept – p1, p2
  • Return value – in this case the product of the two parameters
function myFunction(p1, p2) {
    return p1 * p2;
}

The following calls the function and applies the returned value to a variable.

  • let result – this declares a variable named “result” (it can be named almost anything)
  • myFunction – the name of the function “called” (referred to)
  • (2, 3) – the values to be applied to the variables accepted by the function
let result = myFunction(2, 3); // the function will return 6

Note

Variables declared within a JavaScript function, become LOCAL to the function. Local variables can only be accessed from within the function.

In the following, x would only be declared and equal 7 within the function. Outside the function, it would not be declared/defined unless otherwise done outside the function.

function myFunction(p1, p2) {
let x = 7;
return x * p1 * p2;
}


JavaScript Notes:

  • When using JavaScript, single or double quotation marks are acceptable and work identically to one another; choose whichever you prefer, and stay consistent
  • JavaScript is a case-sensitive language; firstName is NOT the same as firstname
  • JavaScript variables are case sensitive (x is not the same as X)
  • Arrays count starting from zero NOT one; so item 1 is position [0], item 2 is position [1], and item 3 is position [2] … and so on
  • JavaScript variables must begin with a letter, $, or _

We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.