JavaScript and TypeScript course ยท Module 1: JavaScript Basics
Functions
In this lesson16
In Jurassic Park, the team of employees performs various specialized tasks: Dr. Wu handles genetics, the security team monitors fences, and veterinarians take care of dinosaur health. Each specialist performs specific tasks when asked, without needing to explain every time exactly how to do it.
In JavaScript, functions work similarly - they are blocks of code designed to perform specific tasks. Functions can be defined once and called multiple times, making code more modular, readable, and easier to maintain.
Defining Functions
In JavaScript, there are several ways to define functions. Let's start with the most basic one - function declaration:
// Basic function declaration syntax
function functionName(parameter1, parameter2, ...) {
// Code block to execute
return value; // Optional statement returning a value
}In the context of Jurassic Park, we could create a function to check enclosure safety:
// Function to check enclosure safety
function checkEnclosureSafety(powerLevel, fenceCondition, dinoSpecies) {
// Safety conditions dependent on species
let minPowerLevel;
if (dinoSpecies === "Tyrannosaurus" || dinoSpecies === "Velociraptor") {
minPowerLevel = 90; // For dangerous predators we require high power level
} else if (dinoSpecies === "Dilophosaurus" || dinoSpecies === "Carnotaurus") {
minPowerLevel = 75; // For smaller predators
} else {
minPowerLevel = 50; // For herbivores
}
// Check safety conditions
if (powerLevel < minPowerLevel) {
return "UNSAFE: Power level too low for this species!";
}
if (fenceCondition !== "intact") {
return "UNSAFE: Fence requires repair!";
}
return "SAFE: Enclosure meets all safety requirements.";
}
// Examples of function usage
let tRexInspectionResult = checkEnclosureSafety(85, "intact", "Tyrannosaurus");
console.log(`T-Rex enclosure: ${tRexInspectionResult}`); // "T-Rex enclosure: UNSAFE: Power level too low for this species!"
let triceratopsInspectionResult = checkEnclosureSafety(60, "intact", "Triceratops");
console.log(`Triceratops enclosure: ${triceratopsInspectionResult}`); // "Triceratops enclosure: SAFE: Enclosure meets all safety requirements."Function Expressions
Another way to define functions is using a function expression, where a function is assigned to a variable:
// Function expression
const functionName = function(parameter1, parameter2, ...) {
// Code block to execute
return value; // Optional
};Example from Jurassic Park:
// Function to calculate daily food requirement
const calculateDailyFoodRequirement = function(species, weight, age) {
let baseFactor;
// Determining the base factor depending on diet
if (["Tyrannosaurus", "Velociraptor", "Spinosaurus"].includes(species)) {
baseFactor = 0.10; // 10% of body weight for carnivores
} else if (["Allosaurus", "Carnotaurus", "Dilophosaurus"].includes(species)) {
baseFactor = 0.08; // 8% of body weight for smaller carnivores
} else {
baseFactor = 0.15; // 15% of body weight for herbivores (eat more, but less caloric food)
}
// Age correction (young specimens eat proportionally more)
let ageFactor = age < 5 ? 1.5 : age < 10 ? 1.2 : 1.0;
// Calculate daily food requirement in kg
let dailyRequirement = weight * baseFactor * ageFactor;
return Math.round(dailyRequirement * 10) / 10; // Round to 1 decimal place
};
// Usage examples
console.log(`Daily food requirement for young T-Rex: ${calculateDailyFoodRequirement("Tyrannosaurus", 2000, 3)} kg`);
// "Daily food requirement for young T-Rex: 300 kg"
console.log(`Daily food requirement for adult Stegosaurus: ${calculateDailyFoodRequirement("Stegosaurus", 5000, 12)} kg`);
// "Daily food requirement for adult Stegosaurus: 750 kg"Arrow Functions
Arrow functions are a more concise way to write functions, introduced in ES6:
// Arrow function syntax
const functionName = (parameter1, parameter2, ...) => {
// Code block
return value;
};
// For simple functions with a single expression, you can omit curly braces and the return keyword
const simpleSum = (a, b) => a + b;Example application in Jurassic Park:
// Arrow function to classify dinosaurs
const classifyDinosaur = (species, length, speed) => {
// Threat classification based on species, size, and speed
if (["Tyrannosaurus", "Spinosaurus"].includes(species) && length > 10) {
return "Highest threat - Class A";
} else if (["Velociraptor", "Dilophosaurus"].includes(species) && speed > 30) {
return "High threat - Class B";
} else if (["Allosaurus", "Carnotaurus"].includes(species)) {
return "Medium threat - Class C";
} else if (species.includes("raptor") || speed > 40) {
return "Elevated threat - Class D";
} else {
return "Low threat - Class E";
}
};
// Simple arrow functions without code blocks
const isPredator = species => ["Tyrannosaurus", "Velociraptor", "Spinosaurus", "Allosaurus", "Carnotaurus", "Dilophosaurus"].includes(species);
const estimateSpeed = (limbLength, mass) => Math.round(limbLength * 0.7 * (100 / mass));
// Usage examples
console.log(classifyDinosaur("Tyrannosaurus", 12, 27)); // "Highest threat - Class A"
console.log(classifyDinosaur("Gallimimus", 2, 45)); // "Elevated threat - Class D"
console.log(isPredator("Stegosaurus")); // false
console.log(estimateSpeed(2.5, 20)); // 9Function Parameters
Functions can accept parameters, which are local variables available inside the function:
Default Parameters
Since ES6, we can define default values for parameters:
function setIncubatorTemperature(species, temperature = 37.5) {
console.log(`Set incubator temperature for ${species} eggs to ${temperature}ยฐC`);
// Further code...
}
setIncubatorTemperature("Velociraptor"); // "Set incubator temperature for Velociraptor eggs to 37.5ยฐC"
setIncubatorTemperature("Triceratops", 36.2); // "Set incubator temperature for Triceratops eggs to 36.2ยฐC"Rest Parameters
Allow passing an indefinite number of arguments as an array:
function monitorDinosaurs(...ids) {
console.log(`Monitoring ${ids.length} dinosaurs...`);
for (let id of ids) {
console.log(`Checking dinosaur #${id}...`);
// Monitoring code...
}
return `Monitoring of ${ids.length} dinosaurs complete.`;
}
console.log(monitorDinosaurs(101, 102, 103, 104, 105));
// Will display:
// "Monitoring 5 dinosaurs..."
// "Checking dinosaur #101..."
// "Checking dinosaur #102..."
// "Checking dinosaur #103..."
// "Checking dinosaur #104..."
// "Checking dinosaur #105..."
// "Monitoring of 5 dinosaurs complete."Returning Values
Functions can return values using the return statement:
function analyzeDnaSample(sample) {
// Sample analysis code...
if (!sample || sample.length < 10) {
return { success: false, message: "Insufficient genetic material." };
}
// Analysis simulation
const species = ["Tyrannosaurus", "Triceratops", "Velociraptor", "Stegosaurus", "Brontosaurus"];
const randomIndex = Math.floor(Math.random() * species.length);
return {
success: true,
species: species[randomIndex],
dnaPurity: Math.round(Math.random() * 50 + 50), // 50-100%
completeness: Math.round(Math.random() * 40 + 60), // 60-100%
message: "Analysis completed successfully."
};
}
const analysisResult = analyzeDnaSample("ACGTAAGTCCTGAT");
console.log(analysisResult);
// Example output:
// {
// success: true,
// species: "Velociraptor",
// dnaPurity: 87,
// completeness: 75,
// message: "Analysis completed successfully."
// }
if (analysisResult.success) {
console.log(`Identified ${analysisResult.species} DNA with ${analysisResult.dnaPurity}% purity`);
} else {
console.log(`Analysis error: ${analysisResult.message}`);
}Variable Scope
Variables defined inside a function are local to that function and are not accessible from outside:
function prepareJurassicIncident() {
// Local variable, not accessible outside the function
let secretSystemCode = "TRex1993";
console.log(`Code generated inside function: ${secretSystemCode}`);
return "Incident prepared.";
}
prepareJurassicIncident();
// Attempting to access the local variable outside the function will cause an error
// console.log(secretSystemCode); // ReferenceError: secretSystemCode is not defined
// Variables defined outside a function are accessible inside
let jurassicParkLocation = "Isla Nublar";
function displayParkInfo() {
// Access to outer variable
console.log(`Jurassic Park is located on the island: ${jurassicParkLocation}`);
// Local variable
let dinosaurCount = 200;
console.log(`Current dinosaur count: ${dinosaurCount}`);
}
displayParkInfo();
// console.log(dinosaurCount); // ReferenceError: dinosaurCount is not definedNested Functions
Functions can be defined inside other functions:
function conductScientificResearch(species) {
console.log(`Starting scientific research on species: ${species}`);
// Nested function - only accessible inside conductScientificResearch
function analyzeSample() {
console.log(`Analyzing ${species} DNA sample...`);
return "Analysis complete";
}
// Another nested function
function simulateGrowth() {
console.log(`Simulating ${species} growth and development...`);
return "Simulation complete";
}
// Calling nested functions
const analysisResult = analyzeSample();
const simulationResult = simulateGrowth();
return {
species,
analysisResult,
simulationResult,
researchDate: new Date().toISOString()
};
}
const researchReport = conductScientificResearch("Velociraptor");
console.log(researchReport);
// Nested functions are not accessible outside the outer function
// analyzeSample(); // ReferenceError: analyzeSample is not definedHigher-Order Functions
In JavaScript, functions are first-class objects, which means they can be passed as arguments to other functions or returned by functions:
// Function accepting another function as a parameter
function monitorEnclosure(enclosureId, alarmFunction) {
console.log(`Monitoring enclosure #${enclosureId}`);
// Simulating a problem
const anomalyDetected = Math.random() > 0.7;
if (anomalyDetected) {
// Calling the passed function when a problem is detected
alarmFunction(`Anomaly detected in enclosure #${enclosureId}!`);
}
return { enclosureId, status: anomalyDetected ? "Anomaly" : "Normal" };
}
// Functions that can be passed as arguments
function soundAlarm(message) {
console.log(`SOUND ALARM: ${message}`);
}
function visualAlarm(message) {
console.log(`VISUAL ALARM: ${message}`);
}
function staffNotifications(message) {
console.log(`SMS NOTIFICATION: ${message}`);
}
// Using the higher-order function with different alarm functions
monitorEnclosure(1, soundAlarm);
monitorEnclosure(2, visualAlarm);
monitorEnclosure(3, staffNotifications);
// We can also pass an anonymous function
monitorEnclosure(4, function(message) {
console.log(`EMERGENCY PROCEDURE: ${message}`);
console.log("Launching evacuation protocol...");
});
// Or an arrow function
monitorEnclosure(5, message => console.log(`DIAGNOSTIC REPORT: ${message}`));Function Returning a Function
// Function creating and returning another function
function createSpeciesMonitor(species) {
// We return a new function tailored to a specific species
return function(action) {
const actionTime = new Date().toLocaleTimeString();
console.log(`[${actionTime}] ${species}: ${action}`);
// Additional logic dependent on species
if (["Tyrannosaurus", "Velociraptor", "Dilophosaurus"].includes(species) && action.includes("near the fence")) {
console.log(`WARNING! Dangerous predator ${species} near the fence!`);
}
};
}
// Creating monitors for different species
const tRexMonitor = createSpeciesMonitor("Tyrannosaurus");
const triceratopsMonitor = createSpeciesMonitor("Triceratops");
// Using the returned functions
tRexMonitor("Moving in the southern direction");
tRexMonitor("Approaching near the fence");
triceratopsMonitor("Grazing in the northern part of the enclosure");Immediately Invoked Function Expressions (IIFE)
An IIFE (Immediately Invoked Function Expression) is a function that is defined and called immediately:
// IIFE structure
(function() {
// Function code...
})();
// IIFE with parameters
(function(name) {
console.log(`System initialization: ${name}`);
})("Jurassic Park");IIFEs are useful for creating a private scope and avoiding pollution of the global object:
// Jurassic Park system initialization using IIFE
const jurassicParkSystem = (function() {
// Private variables, not accessible from outside
const securityCodes = {
mainGates: "GATES1993",
laboratory: "INGEN2015",
powerSystem: "NEDRY1992"
};
let systemStatus = "offline";
let securityLevel = 0;
// Private functions
function validateCode(providedCode, requiredCode) {
return providedCode === requiredCode;
}
// Public interface - only these functions will be accessible from outside
return {
startSystem: function() {
systemStatus = "online";
securityLevel = 3;
console.log("Jurassic Park system started.");
return true;
},
checkStatus: function() {
return {
status: systemStatus,
securityLevel,
updateTime: new Date().toISOString()
};
},
grantAccess: function(area, code) {
if (!validateCode(code, securityCodes[area])) {
console.log(`Access denied to area: ${area}`);
return false;
}
console.log(`Access granted to area: ${area}`);
return true;
}
};
})();
// Using the public interface
jurassicParkSystem.startSystem();
console.log(jurassicParkSystem.checkStatus());
jurassicParkSystem.grantAccess("mainGates", "GATES1993"); // true
jurassicParkSystem.grantAccess("laboratory", "wrong code"); // false
// Attempting to access private variables will fail
// console.log(jurassicParkSystem.securityCodes); // undefined
// console.log(jurassicParkSystem.validateCode); // undefinedRecursion
Recursion is a technique where a function calls itself:
// Recursive function simulating dinosaur reproduction
function simulateReproduction(initialPopulation, yearsAhead, growthRate = 1.5) {
// Recursion termination condition
if (yearsAhead <= 0) {
return initialPopulation;
}
// Calculate new population after one year
const newPopulation = Math.round(initialPopulation * growthRate);
console.log(`Year ${yearsAhead} until end of simulation. Population: ${newPopulation}`);
// Recursive call with new population and decreased year counter
return simulateReproduction(newPopulation, yearsAhead - 1, growthRate);
}
// Initial population: 2 dinosaurs, simulation for 5 years ahead
const finalPopulation = simulateReproduction(2, 5);
console.log(`Final population after 5 years: ${finalPopulation}`);
// Result:
// Year 5 until end of simulation. Population: 3
// Year 4 until end of simulation. Population: 5
// Year 3 until end of simulation. Population: 8
// Year 2 until end of simulation. Population: 12
// Year 1 until end of simulation. Population: 18
// Final population after 5 years: 18It's important to always have a recursion termination condition to avoid infinite calls, which can cause a stack overflow error.
Hoisting
Hoisting is a JavaScript behavior that "moves" declarations to the top of their scope:
// We can call a function before its declaration thanks to hoisting
console.log(checkParkSafety()); // "Park safe"
// The function declaration is moved to the top
function checkParkSafety() {
return "Park safe";
}
// However, function expressions are not fully hoisted
// console.log(calculateRisk()); // Error: calculateRisk is not a function
// Only the variable declaration is hoisted, not its value
var calculateRisk = function() {
return "Low risk";
};
// Similarly with let and const - they are hoisted but not initialized
// console.log(analyzeData); // ReferenceError: Cannot access 'analyzeData' before initialization
let analyzeData = function() {
return "Analysis complete";
};Closures
A closure is created when an inner function has access to the scope of the outer function, even after it has finished executing:
function createDinosaurCounter(roomName) {
let dinosaurCount = 0;
// The inner function creates a closure
function updateCounter(change) {
dinosaurCount += change;
console.log(`${roomName}: Current dinosaur count: ${dinosaurCount}`);
return dinosaurCount;
}
return {
addDinosaur: function() {
return updateCounter(1);
},
removeDinosaur: function() {
return updateCounter(-1);
},
getDinosaurCount: function() {
return dinosaurCount;
}
};
}
// Creating two independent counters for different rooms
const enclosureACounter = createDinosaurCounter("Enclosure A");
const enclosureBCounter = createDinosaurCounter("Enclosure B");
enclosureACounter.addDinosaur(); // "Enclosure A: Current dinosaur count: 1"
enclosureACounter.addDinosaur(); // "Enclosure A: Current dinosaur count: 2"
enclosureBCounter.addDinosaur(); // "Enclosure B: Current dinosaur count: 1"
enclosureACounter.removeDinosaur(); // "Enclosure A: Current dinosaur count: 1"Closures are extremely useful for creating factory functions, data encapsulation, and implementing design patterns.
Best Practices When Using Functions
One function, one task: Functions should be designed to perform one specific task. This makes testing, debugging, and maintaining code easier.
Descriptive function names: Use clear, descriptive function names that indicate their purpose (e.g.,
loginUserinstead ofuFunc1).Limit the number of parameters: Try to limit the number of parameters. If a function requires many parameters, consider using an options object:
// Instead of:
function configureSecuritySystem(powerLevel, sensorSensitivity, reactionTime, operationMode, notifications) {
//
}
// Use:
function configureSecuritySystem(options) {
const {
powerLevel = 100,
sensorSensitivity = "high",
reactionTime = 5,
operationMode = "automatic",
notifications = true
} = options;
//
}
// Calling:
configureSecuritySystem({
powerLevel: 90,
reactionTime: 3,
operationMode: "manual"
});Avoid side effects: Try to ensure that functions don't modify variables outside their scope or the objects and arrays passed to them (the function receives a reference to the same object, so the change is visible outside).
Return value conventions: Be consistent in returning values. Avoid functions that sometimes return a value and sometimes don't.
Error handling: Always consider potential errors and handle them appropriately using try-catch blocks or returning status objects.
function cloneDinosaur(dna) {
try {
if (!dna || dna.length < 100) {
throw new Error("Insufficient DNA for cloning");
}
// Cloning code...
return {
success: true,
dinosaur: { species: "Velociraptor", id: "VR-" + Math.floor(Math.random() * 1000) }
};
} catch (error) {
console.error(`Cloning error: ${error.message}`);
return {
success: false,
error: error.message
};
}
}The Future of JavaScript - TC39 and Language Development Proposals
Just as dinosaur DNA constantly evolved to adapt to a changing environment, JavaScript also undergoes a continuous process of evolution. Behind this process stands TC39 - the technical committee responsible for the development of the JavaScript language.
What is TC39?
TC39 (Technical Committee 39) is a group of experts that manages the development of the ECMAScript specification (the official name of the JavaScript standard). TC39 includes representatives from companies such as Google, Mozilla, Apple, Microsoft, as well as other organizations and independent experts.
Just as the scientific council of Jurassic Park decides which dinosaur species will be bred and how they will be managed, TC39 decides which new features will be added to JavaScript and in what form.
The Proposal Process - Stages 0-4
Every new feature in JavaScript goes through stages 0, 1, 2, 2.7, 3 and 4, from idea to implementation:
Stage 0 - Strawman
The earliest stage - it's like the first sketch of a new dinosaur species on paper. Anyone can submit an idea. There are no formal requirements; it's simply a place for sharing ideas.
Stage 1 - Proposal
The committee has decided that the idea is worth considering. It's like the phase when Jurassic Park scientists decided it was worth seriously considering cloning a specific species. At this stage:
- The problem that the proposal aims to solve is identified
- A general solution is described
- Potential challenges are identified
Stage 2 - Draft
The proposal now has a preliminary technical specification. It's like a detailed genetic plan and breeding procedures for a new dinosaur. At this stage:
- The syntax is largely shaped
- Semantics are formally described
- The feature is expected to be eventually included in the language
Stage 2.7 - Approved specification (since 2024)
The committee has approved the specification, and conformance tests (test262) are being written. Browsers start implementing the feature once the tests exist.
Stage 3 - Candidate
The specification is complete and awaiting implementation feedback. It's like the first cloning attempts - we have a complete plan, now we test it in practice. At this stage:
- Browsers and environments begin implementing the feature
- Feedback from developers is collected
- Only minor corrections are made
Stage 4 - Finished
The proposal is ready to be included in the official ECMAScript specification! It's like the moment when a new dinosaur successfully hatches and is ready for presentation in the park. At this stage:
- At least two independent implementations exist
- Tests are written and accepted
- The feature will be included in the next version of ECMAScript
Interesting Proposals at Various Stages
Let's look at a few fascinating proposals that could change the way we write JavaScript code:
Pipeline Operator (|>) - Stage 2
The pipeline operator allows chaining operations in a more readable way, similar to water transport channels in Jurassic Park:
// Without pipeline operator
const result = Math.round(Math.max(5, 10, 15) * 2);
// With pipeline operator (% is the result of the previous step)
const result = Math.max(5, 10, 15)
|> % * 2
|> Math.round(%);
// Example with park security system
const securityStatus = fetchSensorData()
|> filterActiveSensors(%)
|> analyzeThreatLevel(%)
|> generateSecurityReport(%);Records & Tuples - withdrawn proposal
Records & Tuples, immutable data structures compared by value, reached Stage 2, but in 2025 the committee withdrew the proposal. It is a good example that not every proposal makes it into the language.
Pattern Matching - Stage 1
A powerful pattern matching mechanism that makes conditional code more readable. It's like a dinosaur classification system - we can precisely match actions to different types:
// Instead of many if/else or switch statements
const handleDinosaur = (dino) => {
match (dino) {
when ({ species: "Tyrannosaurus Rex", health: health }) if (health < 50) -> {
return "Call the vet for the T-Rex!";
}
when ({ diet: "carnivore", escaped: true }) -> {
return "ALARM! Predator has escaped!";
}
when ({ species: "Velociraptor" }) -> {
return "Check enclosure security";
}
when ({ health: h }) if (h > 90) -> {
return "Dinosaur in excellent condition";
}
default -> {
return "Standard monitoring procedure";
}
}
};Decorators - Stage 3
Decorators allow modifying classes and their members in a declarative way. It's like the tag and chip system for dinosaurs - we add extra functionality without modifying the basic structure:
// Decorator for logging method calls
function log(method, context) {
return function (...args) {
console.log(`Calling ${context.name} with arguments: ${JSON.stringify(args)}`);
const result = method.apply(this, args);
console.log(`Result: ${result}`);
return result;
};
}
class DinosaurMonitor {
@log
checkHealth(dinosaurId) {
// Health checking
return "healthy";
}
@log
feedDinosaur(dinosaurId, foodAmount) {
// Feeding the dinosaur
return "fed";
}
}
// Every method call will be automatically logged!
const monitor = new DinosaurMonitor();
monitor.checkHealth("TREX-001");
// Console: Calling checkHealth with arguments: ["TREX-001"]
// Console: Result: healthyHow to Follow Language Development?
If you want to stay up to date with JavaScript's evolution, similar to how Jurassic Park scientists monitor the evolution of their dinosaurs, you can:
TC39 GitHub Repository: https://github.com/tc39/proposals
- Complete list of all proposals with their current statuses
- Discussions and technical documentation
TC39 Meeting Notes: https://github.com/tc39/notes
- Notes from committee meetings
- Insight into the decision-making process
Can I Use: https://caniuse.com
- Checking browser support for new features
- Planning when to safely use new functionality
Babel: https://babeljs.io
- Ability to experiment with new features right now
- Transpiling modern code to versions supported by older browsers
TC39 Website: https://tc39.es
- Official committee website
- Process documentation and rules
Why Follow TC39 Proposals?
- Future-proofing - knowing upcoming features allows planning application architecture with the future in mind
- Influence on the language - the community can submit feedback and influence the shape of new features
- Competitive advantage - knowledge of the latest language capabilities makes you a more valuable developer
- Better code quality - new features often offer cleaner and safer ways to solve problems
Just as Jurassic Park constantly evolves, adding new species and improving security systems, JavaScript also continuously develops. Understanding the TC39 process and following new proposals is like having a genetic map of the language's future - it allows us to prepare for what's coming and shape that future through active community participation.
Summary
Functions in JavaScript, much like specialized teams in Jurassic Park, allow you to:
- Organize code - grouping related logic in one place
- Reuse - defining logic once and using it multiple times
- Abstraction - hiding implementation details behind a simple interface
- Modularity - building complex systems from simpler, independent components
Key concepts about functions:
- Different ways to define them: declarations, expressions, arrow functions
- Parameters and arguments, including default and rest parameters
- Returning values
- Variable scope
- Higher-order functions
- Recursion
- Closures
We also learned about the TC39 mechanism and the JavaScript development process - from Stage 0 proposals to finished implementations at Stage 4. Understanding this process allows us to stay current with the language's evolution and prepare for the future of JavaScript programming.
In the next lesson, you will combine everything you have learned in the final project.
Code for this lesson: index.js
// Functions in JavaScript
// Different ways of defining and using functions
// === Function declaration ===
console.log("=== Function declaration ===");
function checkHealth(name, health) {
if (health > 80) {
return name + " - EXCELLENT";
} else if (health > 50) {
return name + " - GOOD";
} else {
return name + " - NEEDS CARE";
}
}
console.log(checkHealth("T-Rex", 95));
console.log(checkHealth("Raptor", 72));
console.log(checkHealth("Brachio", 45));
// === Default parameters ===
console.log("\n=== Default parameters ===");
function feedDinosaur(name, amount = 50) {
console.log(name + " fed: " + amount + " kg");
}
feedDinosaur("T-Rex", 200);
feedDinosaur("Compy"); // will use default value 50
// === Arrow functions ===
console.log("\n=== Arrow functions ===");
const calcAge = (discoveryYear) => 2024 - discoveryYear;
console.log("T-Rex discovered in 1905, years of research:", calcAge(1905));
console.log("Triceratops discovered in 1889, years of research:", calcAge(1889));
// Arrow with multiple lines
const dinoProfile = (name, weight, diet) => {
const threat = diet === "carnivore" ? "HIGH" : "LOW";
return name + " (" + weight + "kg) - Threat: " + threat;
};
console.log(dinoProfile("T-Rex", 7000, "carnivore"));
console.log(dinoProfile("Brachio", 80000, "herbivore"));
// === Functions as arguments (callback) ===
console.log("\n=== Callback ===");
const dinosaurs = ["T-Rex", "Velociraptor", "Triceratops"];
dinosaurs.forEach(function(dino, index) {
console.log((index + 1) + ". " + dino);
});
// With an arrow function
const weights = [7000, 15, 8000, 80000];
const large = weights.filter(w => w > 5000);
console.log("\nLarge dinosaurs (>5000kg):", large);
// === Return ===
console.log("\n=== Function with return ===");
function findLargest(array) {
let max = array[0];
for (const value of array) {
if (value > max) {
max = value;
}
}
return max;
}
console.log("Heaviest:", findLargest(weights), "kg");
// Your task:
// 1. Create a function that calculates the average of an array
// 2. Use an arrow function to filter data
// 3. Write a function with a default parameter
Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is a default parameter in a function?
2. What does a modern JavaScript engine (e.g. V8) do with a piece of code that runs very often ("hot" code)?
3. What will the expression 0 === false return in JavaScript?
4. Which web application layer is responsible for communication with the server?
5. What is the FIRST step in the JavaScript debugging process?
6. What scope do variables declared with let and const have?
Hands-on tasks in the game
- Code editor
Write a function calculateFoodPortion(diet, weightKg) that returns the daily food portion in kg: 5% of the weight for the 'carnivore' diet, 3% for 'herbivore' and 4% for 'omnivore'. Call it for a T-Rex ('carnivore', 8000) and display the result in the console.
- Horizontal ordering
Arrange the function call elements with arguments:
- Vertical ordering
Arrange the stages of defining and calling functions in JavaScript:
- Click in order
Arrange the function declaration elements in the correct order:
- Code editor
Write a function calculateFossilAge(currentYear, fossilYear) that returns the fossil's age in millions of years: (currentYear - fossilYear) / 1000000. Write years BC as negative numbers. Call it for a T-Rex (2024, -68000000) and display the result in the console.
- Click in order
Arrange the arrow function elements in the correct order:
- Code editor
You have enclosure data: const voltage = 8500 and const fenceHealth = 40. Create a variable isSafe that is true when voltage > 5000 and at the same time fenceHealth > 50 (use &&), and a variable needsAttention that is true when fenceHealth < 50 or voltage === 0 (use ||). Display both in the console.
Tasks after this lesson
- QuestionFunction Parameters
- Coding taskPractice: Functions
- Put in orderFunction Call
- Put in orderStages of Defining and Calling Functions
- Click in orderSorting: Function Declaration
- Coding taskExercise: Write a Function to Calculate Fossil Age
- Click in orderSorting: Arrow Function
- QuestionThe JavaScript engine and frequently run code
- QuestionStrict Comparison Operator
- QuestionWeb Application Layers
- Coding taskPractice: Comparison and Logical Operators
- QuestionJavaScript Debugging Process
- QuestionScope of let and const Variables