JavaScript Scratches

Functions

Every programming language has a feature like functions, sometimes called 'subroutines' or 'procedures'.

They are small blocks of code (technically objects) that perform a singular function - imagine that.

The beauty and power of functions is that once you have one that works, you can use it over and over again - either in the same program or a different one.

Functions are reusable
Functions organize code
Functions enable modularity
Functions are parameterized
Functions can be nested

Declaring

There are a few different ways to declare JavaScript functions. Most commonly is this one:

Declared Function

Similar to defining a variable for the first time, there are specific rules to follow for functions.

Since the declaration is NOT an executable JavaScript statement, we don't need a semi-colon to complete it.

function Far2Cent (n) {
	return (n-32 / 1.8;
}
var n=-40;
Far2Cent(n);
Sprint(n +" degrees Fahrenheit is "+Far2Cent(n)+" degrees Centigrade<br/>");

Arrow Function

This format works if only 1 statement returns a value.

let a=77;let b=3;
let expo = (a,b) => {return Math.pow(a,b)}; // function definition
let result=expo(a,b);
Sprint(a+"<sup>"+b+"</sup> is "+result+"<br/>");

Expression Function

A useful way to put the result of a function into a variable. Similar to the arrow example.

const cubeit = function (i) {return Math.cbrt(i)};
let resultant=cubeit(37);
Sprint("Cube root of 37 is "+resultant+"<br/>");

Be careful not to use an already-used name for functions and variables.

Invoking

Once you have a function defined, let's see how to use it - or call it or invoke it.

Yes, merely defining a function does not do anything yet - it is not executed. This only happens when it is invoked.

Take the example above 'Far2Cent': it's a function we defined, but it was not 'executed / invoked / called' until we actually wrote the line 'Far2Cent(n);'.

Or the cube root function 'cubeit'. It was declared / defined on 1 line: 'const cubeit = function (i) {return Math.cbrt(i)};',
but was not executed until the line
'let resultant=cubeit(37);'.

My Function

I'm lazy, so here is a function I made to eliminate some extra typing.

To output a string to the monitor is typically done with a 'document.write' command.

This makes more sense to me:

let Sprint = function(s) {
    document.write(s);
}

It's used like this:

const cubeit = function (i) {return Math.cbrt(i)};
let resultant=cubeit(37);
Sprint("Cube root of 37 is "+resultant+"<br/>");

Hmmm. Where did we just see that?

Note that we had to use &lt; and &gt; codes to print the angle brackets around the break tag.

To do this yourself:

  • Replace < with &lt; or &60;
  • Replace > with &gt; or &62;
  • Replace & with &amp;
  • Replace " with &quot;