- Published on
Comparing Javascript Functions
- Authors
- Name
- Zach Hutton
- @ZachHutton99
Overview
Javascript has multiple ways of specifying and defining functions including a multitude of keywords such as let, const, and function.
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets:
In this example, it's only adding 1+1 and logging it to the console, a thousand times.
I then average out the runtime which is how I got to the numbers listed below.
Function Declaration
Function Declaration is the traditional way to define a function. It is somehow similar to the way we define a function in other programming languages. We start declaring using the keyword function.
Then we write the function name and then parameters.
function add(a, b) {
console.log(a+b)
}
Average Runtime: 32.00 milliseconds
Function Expressions
Function Expression is another way to define a function in JavaScript. Here we define a function using the variable identifiers const, let, and var.
const add = function(a, b) {
console.log(a+b);
}
Average Runtime: 31.74 milliseconds
let add = function(a, b) {
console.log(a+b);
}
Average Runtime: 31.72 milliseconds
var add = function(a, b) {
console.log(a+b);
}
Average Runtime: 31.64 milliseconds
Arrow Functions
Arrow functions have been introduced in the ES6 version of JavaScript. It is used to shorten the code. Here we do not use the function keyword and instead use the arrow symbol =>.
The arrow symbol is denoted with an equals sign followed by a greater than sign.
let add = (a, b) => console.log(a + b);
Average Runtime: 31.95 milliseconds
const add = (a, b) => console.log(a + b);
Average Runtime: 32.03 milliseconds
var add = (a, b) => console.log(a + b);
Average Runtime: 32.05 milliseconds
const add = (a, b) => {
console.log(a + b);
}
Average Runtime: 31.74 milliseconds