Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for JavaScript Functions — Understanding The Basics
Md Abdur Razzak
Md Abdur Razzak

Posted on

     

JavaScript Functions — Understanding The Basics

What is a Function?

  • A function is a subprogram designed to perform a particular task.

  • When a function is called, it gets run. We refer to this as calling a function.

  • Functions can take values as inputs and use them internally.

  • Functions yield values in all cases. In JavaScript, a function will return undefined if no return value is supplied.

  • Functions are objects.

Define a Function.
There are a few different ways to define a function in #"http://www.w3.org/2000/svg" width="20px" height="20px" viewbox="0 0 24 24">Enter fullscreen modeExit fullscreen mode

A named or anonymous function is defined by a function expression. A function without a name is known as an anonymous function. Function expressions cannot be used before they are defined because they are not hoisted. We are assigning a variable value to the anonymous function object in the example below.

`let name = function(parameters){ statements}`
Enter fullscreen modeExit fullscreen mode

A function expression can be written using a simpler syntax called an Arrow Function Expression. This value is not created by arrow functions on its own.

`let name = (parameters) => { statements}`
Enter fullscreen modeExit fullscreen mode

Parameters vs. Arguments.

If you’re new to JavaScript, you may have heard the terms parameters and arguments used interchangeably. While very similar, there is an important distinction to make between these two keywords.

Parameters are used when defining a function, they are the names created in the function definition. In fact, during a function definition, we can pass in up to 255 parameters! Parameters are separated by commas in the (). Here’s an example with two parameters — param1 & param2:

`const param1 = true;const param2 = false;function twoParams(param1, param2){ console.log(param1, param2);}`
Enter fullscreen modeExit fullscreen mode

Contrarily, arguments are the values that each parameter provides to the function during its execution, or when it is called. Our two arguments in the example above are both true and false.

Invoking a Function.

When a function is invoked, it begins to operate. We call this process "invocation." A function can be called by referring to its name, which is followed by an open and closed parenthesis: ().

Let's explore an example.

If you’re using Google Chrome, open up your dev console so you can code along with these examples:[WINDOWS]: Ctrl + Shift + J [MAC]: Cmd + Opt + J

Let's start by defining a function called logIt. The only input required for this function is the name. The function will log that name back to the console when it is executed:

`unction logIt(name){ console.log(name);}`
Enter fullscreen modeExit fullscreen mode

We call our function and pass in the single parameter to make it run. I am referring to this function as Md. Abdur Razzak here:

logIt('Md Abdur Razzak');

You can call your function with an empty set of parenthesis if it doesn't have any parameters:

`function logIt2(){ console.log('The second one);}logIt2();// The second one`)
Enter fullscreen modeExit fullscreen mode

Function Return.

Every function in JavaScript returns undefined unless otherwise specified.

Let’s test this by creating and invoking an empty function:

`function test(){};test();// undefined`
Enter fullscreen modeExit fullscreen mode

Awesome, as expected, undefined is returned.

Now, we can customize what is returned in our function by using the _return _keyword followed by our return value. Take a look at the code below:

`function test(){ return true;};test();// true`
Enter fullscreen modeExit fullscreen mode

In this example, we explicitly tell the function to returntrue. When we invoke the function, that’s exactly what happens.

But why is this important?
It’s important because the value that a function returns, is actually returned to the caller of the function. Take a look at this code:

`let double = function(num) {  return num * 2;}`
Enter fullscreen modeExit fullscreen mode

This is a function expression that creates a function that will return two times the value of our input parameter num. We can then invoke the function and save the return value to a variable:

let test = double(3);
When we log out our test value, we get 6:

console.log(test);// 6
Enter fullscreen modeExit fullscreen mode

Awesome! The _return _variable not only returns values from a function, but it assigns them to whatever is called the function!

Another important rule of the return statement is that it stops function execution immediately.

Consider this example where we have two return statements in our test function:

`function test(){ return true; return false;};test();// true`
Enter fullscreen modeExit fullscreen mode

Our function is immediately stopped from running by the initial return statement, which also makes our function return true. Line three's code, return false; is never run.

Function Objects.

Functions are function objects. In JavaScript, anything that is not a primitive type (undefined, null, boolean, number, or string) is an object. Objects in JavaScript are extremely versatile. Because of this, we can even pass a function as a parameter into another function.

When a function accepts another function as a parameter or returns a function, it is called a higher-order function. You’ve probably already used a bunch of higher-order functions and don’t even know it:Array. prototype.map andArray.prototype.filter are higher-order functions (Just to name a couple). You can check out some of my previous articles to learn more about objects and higher-order functions in JavaScript

Key Takeaways.
This is a lot of information to digest. Here’s a list of the important stuff:

  • A function is a portion of a software created to carry out a specific activity.

  • Expressions are not hoisted; function declarations are.

  • When a function is called, it gets run. We refer to this as calling a function.

  • Functions can take values as inputs and use them internally. A parameter is the name given to the value. An argument is the actual value by itself.

  • Functions invariably yield a value. In JavaScript, a function will return undefined by default if no return value is supplied.

  • Objects are functions.

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
jonrandy profile image
Jon Randy 🎖️
🤖 Artisanal developer - coding with varying degrees of success since 1983
  • Location
    Bangkok 🇹🇭
  • Joined
• Edited on• Edited

We are assigning a variable value to the anonymous function object in the example below.

It's important to point out that this action makes the function cease to be anonymous - it will acquire the name of the variable:

// True anonymous function - no nameconsole.log((function(){}).name)// empty string - anonymous// Anonymous function assigned to a var// now had a name, not anonymousconstmyFunc=function(){}console.log(myFunc.name)// 'myFunc' - not anonymous any more
Enter fullscreen modeExit fullscreen mode

So, in your example, the variablename doesnot contain ananonymous function, rather a named one.

More on anonymous functions here:

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Md Abdur Razzak
Md. Abdur Razzak is a passionate Front-End Developer skilled in React.js. He values learning, connecting with others, and sharing knowledge online. Reach him at: mdabdurrazzakrakib290@gmail.com
  • Location
    Chittagong, Bangladesh
  • Education
    National University
  • Pronouns
    Rakib
  • Work
    Front end developer at FKR IT
  • Joined

More fromMd Abdur Razzak

Loops in JavaScript !!📚🔄
#javascript#es6#frontend#beginners
What is hoisting in javaScript?
#hoisting#javascript#frontend#webdev
DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp