#JavaScript Functions
##Objectives
- Understand what a JavaScript function is
- Be able to recognize a function syntax
- Understand how to write a constructor function
###What is a JavaScript function?
In JavaScript, a function can be both a method AND a class.
###Using JS functions as a subroutine
A JavaScript function is essentially a block of code to do a particular task. Sometimes you will hear them being referred to as methods or subroutines. In the Object-Oriented Programming (OOP) paradigm, think of it like behaviors.
- To use JavaScript as a method, you will have to 1) define the method and 2) invoke it.
Demo
// Define our function with a parameter name
function sayHi(name){
// write a message saying hi
console.log('Hi, I am ' + name);
}
// Invoke our function with the argument 'Stanley'
sayHi('Stanley');
####Activity
Write a function that does a square root of any integer argument and test it on the numbers 4, 6, and 22
#####Part II
Write a check in the function that ensures only a number can be inserted. Return false if the parameter is not an integer
Solution:
function squareRoot(num){
if(typeof num==='number' && (num%1)===0){
return num * num;
}else{
return false;
}
}
console.log(square(4));
console.log(square(6));
console.log(square(8));
console.log(square('hello world'));
#####Part III
Partner up with the person next to you and create a JS function that convert Fahrenheit to Celsius
function toCelsius(fahrenheit){
return (fahrenheit - 32)/(1.8);
}
console.log(toCelsius(100));
###What the heck is a class?
A class is a simply template to create objects!
For instance, let's create a human class
// Define the class
function Human(name){
this.name = name;
this.sayHi = function(){
console.log('Hi, my name is ' + this.name);
}
// Initialize the object utilizing the 'new' keyword
var Stanley = new Human('Stanley');
Stanley.sayHi();
###What the heck is this
The this
keyword in javascript, in a constructor function context, refers to the the Object once its been initialized with the new
keyword.
However, keep in mind, in a global context, this
refers to the window object
####Activity
Now, make your person be able to calculate the square root of numbers
Then
Make your person be able to convert fahrenheit to celsius!
###Questions
- What are the two main purposes of using functions in JavaScript?
- What is this keyword refer to in the global context?
- What is the syntax for writing a basic subroutine?