Javascript Functions

JavaScript Functions

A function is a block of code that is designed to perform a task that can be used over and over again. Functions are very important in Javascript.

JavaScript Built In Functions

console.log(); // Writes out text to JavaScript Console 

Create Your Own Functions

The Function Keyword: is used to define a function. It’s followed by its name and parentheses (). Function naming follows the same rules as variables. The code that gets executed when the function is called goes between the curly brackets {}.

Parameters: Are variables listed inside the parentheses as a part of the function definition. Parameters allow you to input data into the function to produce different results.

Creating JavaScript Functions

// Defines the function
function myFunction(parameter1, parameter2) {
// code to execute
}
//Calls the function
myFunction(1,7);

The Return Statement

Stops code from executing inside the function. It also returns a value to the function caller. Every function in JavaScript returns undefined unless otherwise specified. This function doubles its input then returns the value to the caller so that can be read inside the console.

String Variables In Javascript

//Function that doubles the input
function double(input) {
return input * 2;
}
console.log(double(2));  // console will read out number 4

JavaScript Arrow Functions

Arrow functions were introduced in ES6 as a new way for writing function expressions. With them you can accomplish the same result with fewer lines of code. Instead of the function keyword, it uses an arrow => made from an equal sign and a greater than symbol. You don’t need the return keyword or the {} if the function is a single line. Using arrow functions saves typing but in my opinion makes the code more difficult to read.

Arrow Function With No Parameters

const horn = () => {  console.log("Toot")  };
horn();

Comparing Arrow Functions With Regular Functions

Multiply 2 Numbers - Regular Function

function multiply(x, y)  { 
    return x * y 
};
console.log(  multiply(5,5)  );  // 25

Multiply 2 Numbers - Arrow Function

onst multi = (x, y) => { return x * y };
console.log(  multi(5,5)  );

Get The Distance Between 2 Points - Regular Function

function calcDistance(x0, y0, x1, y1) {
    return Math.hypot(x1 - x0, y1 - y0);
}
console.log(  calcDistance(1, 1, 200, 300)  ); 
//359.1684841407999

Get The Distance Between 2 Points - Arrow Function

const distance = (x0, y0, x1, y1) =>
Math.hypot(x1 - x0, y1 - y0);
console.log(  distance(1, 1, 200, 300)  );
//359.1684841407999

Generate A Random HEX Code - Regular Function

function randHexColor() {
    let n = (Math.random() * 0xfffff * 1000000).toString(16);
    return '#' + n.slice(0, 6);
  };
console.log(  randHexColor()  );   // #53d2dd

Generate A Random HEX Code - Arrow Function

const randomHexColorCode = () => {
    let n = (Math.random() * 0xfffff * 1000000).toString(16);
    return '#' + n.slice(0, 6);
  };
console.log(  randomHexColorCode() ); // #53d2dd

Random Number In Range (Decimal) - Regular Function

function randomNumberInRange(min, max) { 
	return Math.random() * (max - min) + min; 
}
console.log(   randNumInRange(-10, 10)   );
//  -4.956981024239093

Random Number In Range (Decimal) - Arrow Function

const randNumInRange = (min, max) => Math.random() 
  * (max - min) + min;
console.log(   randomNumberInRange(-10, 10)   );
//  -1.4613828340073098

Random Number In Range (Integer) - Regular Function

function randomIntegerInRange (min, max) {
	return Math.floor(  Math.random() 
           * (max - min + 1) + min    );
}
console.log(   randomIntegerInRange(1, 10)   ); 

Random Number In Range (Integer) - Arrow Function

const randInt = (min, max) => Math.floor(Math.random() 
   * (max - min + 1)) + min;
console.log(   randInt(-10, 10)   ); 

Average Numbers - Regular Function

function averageNum(...nums) {
	return nums.reduce((acc, val) => acc + val, 0) 
        / nums.length;
}
console.log(   averageNum(100, 50, 12)   );  // 54

Average Numbers - Arrow Function

const average = (...nums) =>
    nums.reduce((acc, val) => 
    acc + val, 0) / nums.length;
console.log(   average(100, 50, 12)   );  // 54

Convert Radians To Degrees - Regular Function

function radiansToDegrees(rad) {
	return (rad * 180.0) / Math.PI;
} 
console.log(   radiansToDegrees(Math.PI)   ); 
// 180

Convert Radians To Degrees - Arrow Function

const radsToDegrees = rad => (rad * 180.0) / Math.PI;
console.log(   radsToDegrees(Math.PI)   ); 
// 180

Convert Degrees To Radians - Regular Function

function degreesToRadians(deg) {
	return (deg * Math.PI) / 180.0;
} 
console.log(   degreesToRadians(180)    ); 
// 3.141592653589793

Convert Degrees To Radians - Arrow Function

const degreesToRads = deg => (deg * Math.PI) / 180.0;
console.log(   degreesToRads(180)    ); 
// 3.141592653589793

Fahrenheit To Celsius - Regular Function

function fahrenheitToCelsius(degrees) {
	return ((degrees - 32) * 5) / 9;
}
console.log(   fahrenheitToCelsius(104)    );  // 40 Degrees
// Follows the conversion formula C = (F - 32) * 5 / 9

Fahrenheit To Celsius - Arrow Function

const fahrenheitToCelsius = degrees => 
   ((degrees - 32) * 5) / 9;
console.log(   fahrenheitToCelsius(32)    );  // 0 Degrees
// Follows the conversion formula C = (F - 32) * 5 / 9

Celsius To Fahrenheit - Regular Function

function celsiusToFahrenheit(degrees) {
	return 1.8 * degrees + 32;
}
console.log(   celsiusToFahrenheit(40)    ); // 104
// Follows the conversion formula F = 1.8C + 32

Celsius To Fahrenheit - Arrow Function

const celToFahrenheit = degrees => 1.8 * degrees + 32;
console.log(   celToFahrenheit(40)    ); 
// 104
// Follows the conversion formula F = 1.8C + 32

Round To Decimal - Regular Function

function roundNum (n, decimals = 0) {
	return Number(`${Math.round(`${n}e${decimals}`)}
        e-${decimals}`);
}
console.log(    roundNum(1.005, 2)     ); 
// 1.01

Round To Decimal - Arrow Function

const round = (n, decimals = 0) => 
   Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
console.log(    round(1.005, 2)     ); 
// 1.01

Is Prime? - Regular Function

function isNumPrime(num) {
    const boundary = Math.floor(Math.sqrt(num));
    for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;
    return num >= 2;
};
console.log(   isNumPrime(11)    ); // true

Is Prime? - Arrow Function

const isPrime = num => {
  const boundary = Math.floor(Math.sqrt(num));
  for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;
  return num >= 2;
};
console.log(   isPrime(11)    ); // true

Midpoint Between 2 vectors - Regular Function

function getMidpoint([x1, y1], [x2, y2]) {
	return [(x1 + x2) / 2, (y1 + y2) / 2];
}
console.log(   getMidpoint([2, 2], [4, 4])   ); // [3, 3]

Midpoint Between 2 vectors - Arrow Function

const midpoint = ([x1, y1], [x2, y2]) =>
   [(x1 + x2) / 2, (y1 + y2) / 2];
console.log(   midpoint([2, 2], [4, 4])   ); // [3, 3]

Reverse A String - Regular Function

const string = "Hello World Hidden Message";
function reverseString(string) {
    return string.split('').reverse().join('');
}
console.log(reverseString(string));

Reverse A String - Arrow Function

const str = "Hello World Hidden Message";
const reverseStr = (str) => str.split('').reverse().join('');
console.log(reverseStr(str));

Facebook Video