FUNCTIONS IN JAVA SCRIPT: As the building blocks of code 😁
When someone talks about functions, what comes to my mind is maybe a birthday party, a wedding ceremony, graduation parties or any other event that encompasses celebration ,enjoyment and eating food.
However, my perspective about this word was modified after a great introduction to JavaScript by my Teacher Mr Tugume Andrew in one of my online lessons at Refactory. Functions don’t only have one meaning in English as i had known before but rather in a programming language such as JavaScript, there's more to it than it seemed before.
I got to know that functions in JavaScript are like mini machines inside your code You give them input, they do some work and give you output
What a function is
A function is a block of code designed to perform a specific task. Below is a structure of a function that can help you understand, as i did😊
function greet(name) {
console.log(“Hello ” + name); }
function — This is a keyword, it tells JavaScript “I am about to declare or create a function
greet —This is the function name, think of it like naming a person, just like you call someone by their name ie John, Jackie. Without the name JavaScript would not know which function you want to run.
(name) — This is the parameter list. A parameter is a variable that receives data when the function is called.
{ } — It contains the function body
How one can create a function
Function declaration i.e.
function showText() {
console.log(“JavaScript is fun”)
}
showText(); // Out put will be JavaScript is fun
Get Shamillahnamulondo’s stories in your inbox
Join Medium for free to get updates from this writer.
Function expression
const add = function(a, b) {
return a + b;
};
console.log(add(5,3)) ; // Output will be 8
Arrow function
in JS => is called an arrow, it is short hand for the word function.
const multiply = (a, b) => a * b ;
console.log(multiply(4, 2)) ; // Out put will be 8
Real world application
Functions are used every where i.e.
- In form validation : function validateEmail (email) {….}
- In E-Commerce or calculation : function calculateTotal(cart) {….}
- In DOM events : button.addEventListener(“click” , function() {….}
Why functions are important
Functions can be reusable i.e. you write once, but you use many times
Functions can break big problems into smaller pieces
Functions are easier to debug and update
Functions are the heart of JavaScript. Once you understand how to create them like i did, you can easily build almost any web app with zero confusion.👌👌👌



