Week 3
3.4 Functions In JavaScript
Week 3
3.4 Functions In JavaScript
Functions In JavaScript
Functions are one of the most important concepts in JavaScript! They let us group code into reusable blocks, making programs more organized, readable, and efficient.
In this section, we’ll cover:
Declaring and calling functions
Function parameters and return values
Arrow functions
Function expressions vs. function declarations
Let’s dive in!
A function is like a recipe—it contains instructions (code) that we can run whenever needed.
function sayHello() {
console.log("Hello, world!");
}
This doesn’t run immediately! It just defines the function.
sayHello(); // Output: Hello, world!
A function runs only when we call it!
Functions can accept inputs (parameters) and return outputs.
Think of parameters as ingredients in a recipe!
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!
greet("Bob"); // Output: Hello, Bob!
We pass "Alice" and "Bob" as arguments, and the function personalizes the greeting!
A function can send back a result using return.
function add(a, b) {
return a + b;
}
let sum = add(5, 3);
console.log(sum); // Output: 8
💡 return gives back a value that we can store in a variable!
🚨 Important: return stops the function immediately!
function test() {
return "First return";
return "Second return"; // Never runs!
}
console.log(test()); // Output: "First return"
JavaScript has a shortcut for writing functions called arrow functions (=>).
Regular Function:
function multiply(x, y) {
return x * y;
}
Arrow Function Equivalent:
const multiply = (x, y) => x * y;
Arrow functions remove the function keyword and {} when the function has a single statement.
const greet = name => "Hello, " + name + "!"; // No () needed for one parameter
console.log(greet("Alice")); // Output: Hello, Alice!
const square = num => num * num;
console.log(square(4)); // Output: 16
If there are no parameters, use ():
const sayHi = () => "Hi there!";
console.log(sayHi()); // Output: Hi there!
JavaScript has two main ways to create functions:
2, Can be called before it’s defined (hoisted)
console.log(sayHello()); // Works before definition!
function sayHello() {
return "Hello!";
}
Function declarations are hoisted, meaning they can be used before they are defined!
NOT hoisted (must be defined first)
const sayHi = function() {
return "Hi!";
};
console.log(sayHi()); // Output: Hi!
Function expressions are NOT hoisted, so they must be defined before use!
console.log(test());
function test() {
return "I was hoisted!";
}
What will be printed?
Next up: JavaScript Objects And Arrays!