DEV Community

Cover image for JavaScript Functions Explained - Part 1
Deep Space
Deep Space

Posted on

JavaScript Functions Explained - Part 1

Easy to understand example codes, animations (hand made by me). This article and videos is designed for both "Desktop" & "Mobile" users.

If you are a visual "mobile" person, the above video is for you.
In JavaScript Variables, we learned where&how to stick your Data. But what about the actions that manipulate the Data? We need functions.


Table Of Contents:

  1. What is a function ? (General idea of a function)
  2. JavaScript Functions
  3. JavaScript Functions - Call/Invoke Function

What is a function ? (General idea of a function)

There are many different explanations for the same thing. But I'll take my own approach. Because, that's how I personally learn myself.
Instead of talking about specific functions. First, let's talk about the general idea of a function.

You can think of a function like a machine that :

  1. Can Take Input
  2. Process it
  3. And give output/result

general idea of a function. How a function works


JavaScript Functions

A JavaScript function, is a block of code designed to perform a particular task. They also can be reused & modified.
A JavaScript function is executed/activated when something calls/invokes it.

To create a function, write the keyword function
Then give it a name like doSomething or whatever you name it (be descriptive).
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

At the end of the function name use () a pair of parenthesis doSomething()
A set of curly braces {} at the end like so doSomething () {} to define the block, that the function will execute when its called/invoked.

Inside there, I'll just print my name to the console, to make it a simple function.

Example Code:

function doSomething() {
console.log("Lia Sue");
}
Enter fullscreen mode Exit fullscreen mode

If you check the console, nothing hapens. That's because we actually have to invoke/call the functions.

JavaScript Functions - Call/Invoke Function

The way we invoke or call a function is, we have to use or type its name. After we declare/create the function. At the end of the name put a pair of parenthesis like so doSomething ();

// Declaring a function 
function doSomething() {
console.log("Lia Sue");
}
// Invoke / call function
doSomethiing();
Enter fullscreen mode Exit fullscreen mode

Hope this picture will help you visualize
JavaScript functions explanation

JavaScript Functions — Video for Desktop users

If you are reading it from a Desktop device and find vertical video annoying. Here’s a big video designed for Desktop, Enjoy!

Top comments (2)

Collapse
 
deep_space profile image
Deep Space

Thanks & mine was "A Gentle Intro" to functions.

Collapse
 
deep_space profile image
Deep Space

Thank you!