DEV Community

loading...

JavaScript Functions

deep_space profile image Deep Space ・2 min read

Summary: In this tutorial, you'll learn how to create a function in JavaScript and invoke/call it or start/make it work or activate it.

Alt Text

What is a function?

A function is like a machine

  • 1 takes input
  • 2 processes it
  • 3 gives output

If you are a visual person. Here's a video.

If you like reading. Below is the written version of the video.

1 Create a Function in JavaScript

To create a function in JavaScript, use the word

  • function.
  • Then give your function a name like doSomething
  • a pair of parentheses like ()
  • and curly braces like {}

All together in a code editor, it looks like so:

function doSomething() {
// code to be executed
}
Enter fullscreen mode Exit fullscreen mode

Explanation of Code

a) The word function is a JavaScript keyword. It tells JavaScript 'Hey, JavaScript, we are about to create a function'
b) After you write the function keyword you have to give it a name. In this example I gave it doSomething but you can name your function anything you want. (the same rules apply as naming variables).
c) The opening and closing parentheses () takes variables called function parameters we'll talk about those in the next post/video.
d) Inside the curly braces {} you put codes that you want your function to run or process
e) But the code above doesn't do anything because I just wanted to show/explain functions in their purest form.

Calling or Activating your Function

Now let's take the code above and log something to the browser console. Like 'Hello Lia'
To call or activate your function, you must use its name after your function like so: doSomething;
All together it looks something like this:

function doSomething() {
console.log('Hello Lia');
}
doSomething();
Enter fullscreen mode Exit fullscreen mode

If you check your browser console, you should see Hello Lia message or text.

Your task

Your task for this tutorial is to write a function that logs to the console 'Hello YourName '
Thanks for reading

Discussion (0)

pic
Editor guide