Lecture Notes Of Day 7
Functions in JavaScript
Objective:
What are
Functions?
In programming, a function
is a reusable block of code that performs a specific task. Functions allow us
to encapsulate logic, which can be executed multiple times with different
inputs.
Functions are especially useful
for avoiding code repetition and for organizing complex programs into smaller,
manageable tasks.
1.
Function Declaration and Function Expression
There are two main ways to define
functions in JavaScript: function declaration and function expression.
1.1 Function
Declaration (Function Statement)
A function declaration defines a
named function that can be called from anywhere in the code, even before its
definition due to JavaScript’s hoisting mechanism.
Syntax:
function functionName(parameters) {
// code to be executed
}
Example:
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!
In the example above:
- The
function is named greet.
- It
accepts one parameter name.
- It
prints a greeting message to the console.
1.2 Function
Expression
A function expression defines a
function and assigns it to a variable. This function can only be called after
it is defined in the code.
Syntax:
const functionName = function(parameters) {
// code to be executed
};
Example:
const greet = function(name) {
console.log("Hello, " + name + "!");
};
greet("Bob"); // Output: Hello, Bob!
In this case:
- The
function is assigned to the variable greet.
- The
function can be called like any other variable.
2.
Parameters and Return Values
2.1 Parameters
Parameters are values you pass
into a function when you call it. They act as placeholders for the actual
values, which are provided when the function is invoked.
Example:
function add(a, b) {
return a + b;
}
console.log(add(3,
5)); // Output: 8
Here:
- a
and b are parameters of the add function.
- When
calling add(3, 5), the values 3 and 5 are passed to a and b.
2.2 Return
Values
Functions can return values to
the caller using the return keyword. This is how you get the result of a
function.
Example:
function square(x) {
return x * x;
}
let
result = square(4);
console.log(result); // Output: 16
In this example:
- The square
function takes one parameter x and returns the square of x.
- The
return value 16 is assigned to the result variable and printed to the
console.
3.
Function Scope and Local/Global Variables
3.1 What
is Scope?
In JavaScript, scope
refers to the region of the program where a variable is accessible. There are
two main types of scope:
- Global
scope: Variables declared outside of functions,
accessible anywhere in the program.
- Local
scope: Variables declared inside a function,
accessible only within that function.
3.2 Global
Variables
Global variables are declared
outside of functions and can be accessed by any part of the code.
Example:
let name = "John"; // Global variable
function greet()
{
console.log("Hello, " + name);
}
greet(); // Output: Hello, John
Here:
- The
variable name is declared globally and is accessible inside the greet
function.
3.3 Local
Variables
Local variables are declared
inside a function and can only be accessed within that function.
Example:
function add(a, b) {
let sum = a + b; // Local variable
return sum;
}
console.log(add(3,
4)); // Output: 7
console.log(sum); // Error: sum is not defined
Here:
- sum is
a local variable to the add function.
- Trying
to access sum outside the function results in an error because it's not in
the global scope.
3.4 Function
Scope
Variables defined inside a
function are local to that function. This is known as function scope.
Even if you declare a variable outside the function, a local variable with the
same name will take precedence within the function.
Example:
let name = "Alice"; // Global variable
let name = "Bob"; // Local variable
console.log("Hello, " +
name); // Output: Hello, Bob
}
console.log(name); // Output: Alice
In this case:
- Inside
the function greet(), the local name variable ("Bob") is used.
- Outside
the function, the global name variable ("Alice") is still
accessible.
4.
Function Hoisting
In JavaScript, hoisting is
a behavior where function declarations are moved to the top of their scope during
the compilation phase. This means that you can call a function before its
declaration in the code.
Example:
greet("Alice");
function greet(name)
{
console.log("Hello, " + name);
}
In the above example:
- The greet
function is called before its declaration.
- This
works because function declarations are hoisted.
However, function expressions are
not hoisted. If you try to call a function expression before its definition, it
will throw an error.
Example (Error):
greet("Alice"); // Error
const
greet = function(name) {
console.log("Hello, " + name);
};
5.
Summary
- Function
Declaration: A named function defined using the function
keyword.
- Function
Expression: A function assigned to a variable. It cannot
be called before its definition.
- Parameters:
Placeholders for values that you pass into a function.
- Return
Values: Values returned from a function to the
caller using the return keyword.
- Scope:
Determines the visibility of variables. Local variables are accessible
only inside the function, while global variables can be accessed anywhere.
- Hoisting:
Function declarations are hoisted to the top, but function expressions are
not.
Practice
Try to implement the following
tasks to practice working with functions:
1. Create a
function that takes two numbers as parameters and returns their sum.
2. Create a
function that accepts a string and returns its length.
3. Write a
function that checks if a given number is even or odd.
4. Write a
function that finds the factorial of a number using recursion.
