functions
What I learned, what I’m still figuring out, and where I might go next.
Functions
JavaScript supports functions via the function keyword.
// function declaration
function getSum(a, b) {
return a + b;
}
// function call
const result = getSum(60, 9);
console.log(result);
// 69
Function Hoisting
In Python, a function must be defined before it’s used. Welcome to JavaScript where the nothing makes sense, and the points don’t matter. As long as a function is defined somewhere in the file, it can be called even before the definition.
console.log(getLabel(3));
// prints 'awful'
function getLabel(numStars) {
if (numStars > 7) {
return "great";
} else if (numStars > 3) {
return "okay";
} else {
return "awful";
}
}
Multiple Return Values
Many languages allow multiple values to be returned from a function… Don’t do it in JS.
function getUser() {
return "[email protected]", 21, "active";
// DON'T DO THIS
// it only returns 'active'
}
The JavaScript code above won’t actually throw any sort of error, it will just silently return the "active" string… which is behavior that you probably didn’t want. You can only return one value from a function in JavaScript.
Functions as Values
JavaScript supports first-class and higher-order functions, which are just fancy ways of saying “functions as values”. Functions can be treated like any other data type—such as number and string and boolean.
function add(x, y) {
return x + y;
}
function mul(x, y) {
return x * y;
}
We can create a new aggregate function that accepts a function as its 4th argument:
function aggregate(a, b, c, arithmetic) {
const firstResult = arithmetic(a, b);
const secondResult = arithmetic(firstResult, c);
return secondResult;
}
It calls the given arithmetic function (which could be add or mul, or any other function that accepts two parameters and returns a number) and applies it to three inputs instead of two. It can be used like this:
function main() {
const sum = aggregate(2, 3, 4, add);
// sum is 9
const product = aggregate(2, 3, 4, mul);
// product is 24
}
Scope
Scope in JavaScript defines where variables and functions are accessible in your code, and it can behave differently depending on the environment (such as a browser or Node.js). There are four levels, from highest to lowest:
- Global Scope:
- Variables declared globally have the highest level of scope and can be accessed from anywhere in your code.
- In browsers, global variables are properties of the
windowobject. For example,window.myGlobalVar = 'hello world'defines a global variable. - In Node.js, global variables are properties of the
globalobject:global.myGlobalVar = 'hello world'.
- Module Scope:
- In ES modules (both in Node.js and modern browsers), variables declared at the top level of a module are scoped to that module. They are not added to the global scope.
- In the browser, using
<script type="module">creates a module scope for that script.
- Function Scope:
- Variables declared with
var(we try to avoid this) are limited to the function scope. They are accessible only within that function and any nested functions.
- Variables declared with
- Block Scope:
- ES6 introduced block scope with the
letandconstkeywords. A block is typically defined by curly braces{}, like inifstatements, loops, and other blocks of code. - Variables declared with
letandconstare confined to their block, making them more predictable and reducing the chances of accidental variable hoisting.
- ES6 introduced block scope with the
Anonymous Functions
Anonymous functions are true to form in that they have no name. They’re useful when defining a function that will only be used once or to create a quick closure.
Let’s say we have a function conversions that accepts another function, converter as input:
function conversions(converter, x, y, z) {
const convertedX = converter(x);
const convertedY = converter(y);
const convertedZ = converter(z);
console.log(convertedX, convertedY, convertedZ);
}
We could define a function normally and then pass it in by name… but if we only want to use it in this one place, we can define it inline as an anonymous function:
// using a named function
function double(a) {
return a + a;
}
conversions(double, 1, 2, 3);
// 2 4 6
// using an anonymous function
conversions(
function (a) {
return a + a;
},
1,
2,
3,
);
// 2 4 6
Default Parameters
In JavaScript, you can specify default values for function parameters. This is particularly useful for optional parameters where you want to ensure a specific default behavior if the caller does not provide certain arguments. Default parameter values can be set during the function declaration.
function getGreeting(email, name = "there") {
console.log(`Hello ${name}, welcome! You've registered your email: ${email}`);
}
getGreeting("[email protected]", "infktd");
// Hello infktd, welcome! You've registered your email: [email protected]
getGreeting("[email protected]");
// Hello there, welcome! You've registered your email: [email protected]
If the second parameter is omitted, the default value "there" will be used in its place. Optional parameters (those with default values) should be defined after all mandatory parameters to avoid ambiguity.
Passing Value
Variables in JavaScript are typically passed by value_. “Pass by value” means that when a variable is passed into a function, that function receives a copy of the variable. The function is unable to mutate the caller’s original data.
let x = 5;
increment(x);
console.log(x);
// 5
function increment(x) {
x++;
console.log(x);
// 6
}