JavaScript Functions
Lecture Based on JavaScript Absolute
Beginner's Guide
Why Functions?
• Organize and group code
• Make code reusable
• Reduce repetition
• Easier to maintain
• Example:
alert("hello, world!");
Distance Example
• Formula: distance = speed × time
• Without functions, code is repetitive
• Example:
var speed = 10;
var time = 5;
alert(speed * time);
• [Image: Figure 3.1 & 3.2: Distance formula illustration]
Function Version of Distance
• Use functions to reduce repetition
• Pass different values to the function
• Example:
function showDistance(speed, time) {
alert(speed * time);
}
showDistance(10, 5);
showDistance(85, 1.5);
What Is a Function?
• Wrapper for code
• Groups statements together
• Reusable across program
• Core part of JavaScript
• Example:
function sayHello() {
alert("hello!");
}
sayHello();
Functions with Arguments
• Functions can take data as input
• Order matters in arguments
• Example:
function showDistance(speed, time) {
alert(speed * time);
}
showDistance(10, 5);
• [Image: Figure 3.4 & 3.5: Order and naming of arguments]
Returning Data
• Use 'return' keyword to send data back
• Store result in a variable
• Example:
function getDistance(speed, time) {
var distance = speed * time;
return distance;
}
var d = getDistance(10, 5);
Exiting a Function
• Return ends function execution
• Code after return is ignored
• Return without value exits early
• Example:
function doSomething() {
// do something
return;
}
Key Takeaways
• Functions make code reusable
• Arguments pass data into functions
• Return sends data back
• Used in almost every JS application