Topics To Cover
- What functions are and why we need them
- Function declaration syntax
- Function expression syntax
- Key differences between declaration and expression
- Basic idea of hoisting (very high level)
- When to use each type
What functions are and why we need them
A function in programming is the self-contained, named block of code it used to perform a specific task. Its like a sub-programm or black-box which take some input, process it and return a output.
Think it like a vending machine:
- Input (arguments): it take some mony the input and punch button start running.
- Body (function): its internal machanics of the vending machine. it identify is stock available and which item need to drop, calculate changes mony.
- Output (return value): machine drop item and changes in the slot.
Why we need it? You dont need to knwo how to build the vending machine every time when you need snacks, its electronics, complex coin slote mechanics. You only need to know how to use its interface.
Function declaration syntax
The standard JavaScript function declaration defined by the function keyword followed by name, with an optional parameters. Its body contain statements which executed when function will call.
Syntax :
function functionName (parameter1, parameter2, ...){
// code to be executed
return value; // optional return statement
}
-
functionkeyword: A required keyword, used to tell you are defining funciton. -
functionNamename: Function idetifire its a name, it use rules same as variable declaration (uses camel case). It used to called function later for using it. -
(...)parantheses: It enclosed optional, parameters a local variables used to hold arguments a input vlaues provided during calling. -
{...}curlybraceses: It enclosed bunch of statements which executed when function call. It has a access of there parameters. -
returnoptional statement: it used to return some values at places where function is called.
Example :
// Funciton declaration
function calculateSum(a,b){
return a+b
}
// Invoking (calling) the function
const result = calculateSum(2, 5)
console.log(result) // output: 7
In the given example i define a function named calculateSum, its job is to take two arguments in a and b parameters. These parameters used to calculate sum by using addition operator +. After that function return the calcualted sum value of given arguments.
Bellow that declaration i defined a constant variable named result which hold the ouput of calculateSum function. I use assignment operator = to hold the returned value.
Function calling syntax is, you can used its named with () parantheses which indicating that your calling this function mean executing there body. In the given example i put tow arguments 2 and 5 these will holded by the function parameters a and b. After the execution finished the final valued returned by function.
Finally useing console.log to log the result on the console which print vlaue 7.
Function expression syntax
Function declaraing a part of larger expression, typicaly assigning it into a variable. It only execute when code reaches to execution. Unline the funciton declaration, fuction expression can be unonymous (without name).
Syntax :
const greet = function(name){
return `Hello $(name)`
}
// The function is invoked using variable name
console.log(greet("Anthony")) // output: Hello Anthony
Most common syntax involve assigning a anonymous function to a variable using let, const, and var.
It can also be named for debugging purpose or recursion, though the it only accessible within the its own scope.
const factorial = function recursion(n){
if(n <= 1) return 1
return n * recursion(n-1)
}
const fact = factorial(3)
console.log(fact) // output: 6
Key differences between declaration and expression
The key difference is, function expression is evaluated into a value but funciton declaration is a statement which do action not evaluated into values. The most practicle difference is how they are handle hoisting and there use in certain context.
Evaluat to value: statements cannot be evaluated into values, its ony perform actions. The expression can evaluats to a single value like number, string or function object.
Hoisting: Declaration is hoisted on the top of their scope allowing them to invok before they apear in code. The expressions are not hoisted in same way. The variable holding expression may hoisted depending on keyword used for variable declaration, but the assignment happen when the code execution reach that line.
Naming: Function declaration must have name but function expression can be anonymous.
Basic idea of hoisting (very high level)
Hoisting means at very high level, you can use variable or function before you formaly declare them in code.
Its a mechanism in javascript in there function and variable declaration conceptually move to top of their containing scope during the compilation phase before the code actually executes.
Function Declaration
It is fully hoisted means the name and the body of the function is moved to top of the scope. It allow you to call it before it defined.
The javascript engine read its name and its body at the compilation time, that's why its hoisted.
// Works!
sayHello();
function sayHello() {
console.log("Hello!");
}
Function Expression
It is the function stored into the variable, it's not hoisted in the same way. Only the variable declaration is hoisted but the assignment stays in place.
// Throws TypeError: greet is not a function
greet();
var greet = function() {
console.log("Hello!");
};
The function greet is declared and assigned undefined. When you called it, you'r trying to call undefined()
Note: let and const are not hoisted so you can not access it before it's declaration. If you trying to do it you got reference errors.
When to use each type
Choise of using funciton declaration or expression is depends on wheter you need hoisting, how funciton is used, and the desired scope and code style.
Use Funciton Declaration when
Its a standalone statement use it when you need to access it from anywhere in you code. It hoisted so you can call it before its declaration apears. The keyword function at the start makes it easy to spot, improving code structure for top level funcitons. The funciton name is always available withitn its own scope, useful for recurion function.
// This is work because "add" is hoisted to the level
console.log(add(7, 8))
function add(a,b){
return a+b
}
Use Funciton Expression when
It create a funciton as a value which is than assigned to variable. In callback -- use it to pass as argument inside other funcitons. When you need to invok funciton immediatly and want to prevent variable polution of global scope. Used in conditional function definition -- defining function logic based on certain condition. Since they are not hoisted so it only exist when interpreter reaches it, which can lead more predictable or structured code flow.
// This will cause error if call before expression
// console.log(multiply(2,3)) // ReferenceError: cannot access 'multiply' before initialization
const multiply = function(a,b){
return a*b
}
// Must be called after definition
console.log(multiply(2,3)) // output: 6
Top comments (0)