Functions in JavaScript
Functions in JavaScript
Objective: Introduce the trainees to functions, their importance, and how to use
them effectively in JavaScript. The session emphasizes clear examples and
simple explanations to ensure foundational understanding.
Function Basics
a. Declaring and Invoking Functions
What are Functions?
● A function is a reusable block of code designed to perform a specific
task.
● Functions help organize code and avoid repetition. A JavaScript function
is executed when “something” calls (invokes) it.
Syntax:
javascript
function functionName(parameters) {
// Code to execute
}
Example:
javascript
function greet() {
console.log("Hello, World!");
}
greet(); // Outputs: Hello, World!
b. Function Expressions
● What Are They?
Functions assigned to variables. These are not hoisted.
● Characteristics:
o Must be defined before use.
Example:
javascript
const multiply = function (x, y) {
return x * y;
};
b. Arrow Functions
● A shorthand way to write functions, introduced in ES6.
● Arrow functions have a concise syntax and behave differently with the
this keyword.
Syntax:
javascript
const functionName = (parameters) => expression;
Example:
javascript
const add = (a, b) => a + b;
console.log(add(5, 10));
// Outputs: 15