Writing Some Functions

30.05.2016 |

Episode #5 of the course A quick introduction to JavaScript by Rich Armstrong

 

Just like you can get the max value with Math.max(12, 56); you can also write your own functions or methods. You do so like this:

function area (num1, num2) {
 return num1 * num2*;
}

You’ll see the function keyword, the function name (area in this case), and the option of passing two parameters (num1 and num2 in this case) into the function. The code within the {} gets run when you call the function area(10,12);. Notice the () after the function name—this tells the browser to run the function. Try it! You’ll see a value is returned. If you don’t include the (), see what happens: area;

You can write your own functions that just do things without returning anything (undefined is actually returned), and you can write functions that don’t make use of parameters:

// no params
function sayMyName () {
 return "My name is Rich Armstrong. I like you.";
}
sayMyName();

// no return
function visit (newURL) {
 location.href = newURL;
}
visit('http://mrra.co');

You can also store functions in variables to be called later:

var notifyTheUser = function (notice) {
 alert(notice);
}
notifyTheUser('Holy crap this is cool!')

Now it’s your turn. Write a function on JS Fiddle, run it, save it, and share it with me! Tweet at me. I’m @mr_r_a on Twitter. Here’s my area function as an example!

There are a few built-in objects like Math that have useful functions, and arrays and strings have some pretty useful methods (internal functions) too. Try out the following:

var name = "Richard The-ginger-nose-touching-awesome Armstrong”;
var nickName = name.substr(0,4)
console.log(“My nickname is: ” + nickName)
var names = name.split(‘ ’);
console.log(‘names are’, names)
var lastName = names.pop()
console.log('last name is: '+lastName);
names.push('Hugestrongarms')
lastName = names[names.length-1];
console.log('last name is: '+lastName);

Pretty interesting, right?

Remember: Download Google Chrome for Desktop and Sublime Text 3 to make the most of these lessons. And remember to open up your JavaScript Console: Alt+Cmd+J (OS X) or Alt+Ctrl+J (Windows).

 

Recommended book

“The Principles of Object-Oriented JavaScript” by Nicholas C. Zakas

 

Share with friends