CodeOrc.com - Learn by example
X
Make an RPG
Vue Implementations

Javascript functions

The function definition is like a todo list for you computer.

This is a function definition:

function print( a ) { $('.print').append( a + '<br>' ); }

This is how you execute that function:

print( "hello" );

Copy and paste the above function call, so that it appears below the function definition:

function print( a ) { $('.print').append( a + '<br>' ); } print( "hello" );

Hit the green Run button. Now you should see that "hello" has been printed out in the run window at the bottom right.

Let's write a function to add 2 variables: a and b

function add( a, b ) { var sum = a + b; print( sum ); }

Copy that function into your code, after the print_me function. Now we're going to call that function, like so

add(2, 5);
DO IT
Did it work? Try to figure it out. If it still doesn't work just click DO IT and we'll fix the code for you.
Change the numbers and see what happens.

Return Value

The return value is a variable that's based back from the function. Let's remove the print statement and add a return value like so:

function add( a, b ) { var sum = a + b; return sum; }

Now change the function call like so:

var sum = add( 4, 12 ); print( sum );

When you hit the run button, you should see 16. Now, we're going to sum the result of one addition with the result of another addition:

var sum = add( 4, 1 ); var sum2 = add( 2, 3 ); var final = add( sum, sum2 ); print( final );
DO IT
Did it work? Try to figure it out. If it still doesn't work just click DO IT and we'll fix the code for you.

In the next lesson, we will learn about Javascript if statement

Get the Latest Tutorial Updates
<< >>
X