Functions can take in input, do operations on input, and return a result.
A function needs to be declared using the function keyword and called or invocated using the function name:
function greet() {
console.log("Hello!");
}
greet();
Parameters
Parameters are placeholders for values that will get passed into the function when called.
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("Alice"); // "Hello, Alice!"
greet("Nick"); // "Hello, Nick!"
Default values for parameters
You can set default values for parameters to use if no arguments are provided.
Use the assignment operator to assign the parameter a default value.
function greetings(name = "Guest") {
console.log("Hello, " + name + "1");
}
greetings(); // "Hello, Guest!"
greetings("Anna"); // "Hello, Anna!"
Default return value
By default, undefined is returned if you don’t explicitly use the ‘return’ keyword followed by value (to make a return statement).
function doSomething() {
console.log("Doing something...");
}
let result = doSomething();
console.log(result); // undefined
Return value
Include a return statement:
function calculateSum(num1, num2) {
return num1 + num2;
}
console.log(calculateSum(3, 4)); // 7
Anonymous function
An anonymous function doesn’t have a name declared like function calculateSum() but is saved to a variable where it can be referenced or called. It ends with a ; unlike named functions.
const sum = function (num1, num2) {
return num1 + num2;
};
console.log(sum(3, 4)); //7
Function expression
Function Expressions are functions that you assign to variables or use in an expression context, like this function defined inside a method parameter.
setTimeout(function () {
console.log("Hi");
}, 1000);
By assigning a function to a variable, you can use the function in any part of your code where the variable is accessible.
const multiplyNumbers = function(firstNumber, secondNumber) {
return firstNumber * secondNumber;
};
console.log(multiplyNumbers(4, 5)); // Output: 20
Most function expressions are anonymous, but not all. For example, this function expression has a name.
const greet = function sayHello() {
console.log("Hello");
};
Arrow functions
An arrow function is like an anonymous function without the function keyword and with the arrow (=>) between the parameter and function body
const greetings = (name) => {
console.log("Hello, " + name + "!");
};
All arrow functions are function expressions.
Parameter parentheses syntax
-
You can omit the parentheses if there’s only on parameter
const greetings = name => { console.log("Hello " + name); }; -
Use empty parentheses if there are no parameters
const greetings = () => { console.log("Hello"); };
One-line arrow functions
If the function body is only a single line of code, you can
- write arrow functions in one line
- leave out the curly braces { }
- leave out the
returnkeyword (throws a syntax errorUncaught SyntaxError: Unexpected token 'return')
const greetings = name => console.log("Hello" + name);
const calculateArea = (width, height) => width * height;
When to use arrow functions
Depends on the style of the existing code base when working on a team.
Programming scope
Scope in programming is the visibility and accessibility of variables in different parts of your code. It determines where variables can be accessed or modified.
There are three types of scope, from outermost to innermost scope
Global scope
Variables declared in the global scope are accessible from anywhere in your code but should be used sparingly to avoid variable naming conflicts and make the code harder to maintain.
It’s convenient to access global variables from inside the function body.
let globalVar = "I'm a global variable!";
function printGlobalVar() {
console.log(globalVar)
}
printGlobalVar(); // "I'm a global variable!"
Local scope
Local scope refers to variables only accessible within a function.
function greet() {
let message = "Hello, local scope!";
console.log(message);
}
console.log(message); // throws an error
Block scope
Block scope was introduced in ES6 with the let and const keywords.
let and const variables declared within curly braces (if statements, loops) are only accessible in that code block.
(sounds like local scope, I guess the difference is local scope is variables within functions and block scope refers to variables declared within curly braces?)
if (true) {
let blockVar = "I'm in a block";
console.log(blockVar); // "I'm in a block"
}
console.log(blockVar); // ReferenceError
Historically, var ignored block scope boundaries
function demo() {
if (true) {
var a = 1;
let b = 2;
}
console.log(a); // 1
console.log(b); // ReferenceError
}