Functions in JavaScript

Functions in JavaScript
What is a function in Programming?

A function is a block of code, that is organized and reusable.

why/when do we need a function?

We use a function when we have a block of code, that we will reuse multiple times. so to save time, we put all that code inside what we call a function, then we can run it, by simply, type in the function's name.

Create A Function in JavaScript.

To create a function in JavaScript, we use the keyword function, we can create it, using a function declaration or a function expression.

Function Declaration.

To create a function using a function declaration, we first type the function keyword, then the name of the function, then the parenthesis ( ), and then the curly brackets {}.

Example : 

function doSomething(){

        // code goes here.


To execute the code inside the function you must call the function first.
To call the function "doSomething" above, you have to run this line of code :


The name of the function + the parenthesis ().

Function Expression.

To create a function using a function expression, we first say, let then the variable name, (ex : let x ), then the equal sign "=", then the function keyword, then the parenthesis, then the curly brackets (and the code inside), and finally a semicolon ";".

Example : 

let x = function () {

            // code goes here.


Now to call the function above, we simply call the variable, like this :


The function created using a function expression, is also called an anonymous function, as it has no name.

You can see this article in action, by watching my tutorial about functions in JavaScript below.

The Lesson : 
Practice : 

Post a Comment

You're welcome to share your ideas with us in comments.

Previous Post Next Post