0
0
JavascriptHow-ToBeginner · 3 min read

How to Call a Function in JavaScript: Simple Guide

In JavaScript, you call a function by writing its name followed by parentheses, like functionName(). If the function needs inputs, you put them inside the parentheses, for example functionName(arg1, arg2). This runs the code inside the function.
📐

Syntax

To call a function, use the function's name followed by parentheses. If the function requires arguments, place them inside the parentheses separated by commas.

  • functionName: The name of the function you want to run.
  • (): Parentheses that trigger the function call.
  • arguments: Optional values passed to the function inside the parentheses.
javascript
functionName();
functionName(arg1, arg2);
💻

Example

This example shows how to define a function and then call it with and without arguments. It prints messages to the console.

javascript
function greet() {
  console.log('Hello!');
}

greet(); // Calls greet without arguments

function add(a, b) {
  console.log(a + b);
}

add(5, 3); // Calls add with arguments 5 and 3
Output
Hello! 8
⚠️

Common Pitfalls

Common mistakes when calling functions include forgetting the parentheses, which means the function does not run but instead returns the function itself. Another mistake is calling a function before it is defined (unless using function declarations).

javascript
function sayHi() {
  console.log('Hi!');
}

// Wrong: missing parentheses, function not called
const wrongCall = sayHi;
console.log(typeof wrongCall); // Outputs 'function'

// Right: with parentheses, function runs
sayHi(); // Outputs 'Hi!'
Output
function Hi!
📊

Quick Reference

ActionSyntaxDescription
Call function without argumentsfunctionName()Runs the function with no inputs
Call function with argumentsfunctionName(arg1, arg2)Runs the function with given inputs
Assign function without callingconst f = functionNameStores the function itself, does not run it
Call anonymous function immediately(function() { ... })()Defines and runs a function right away

Key Takeaways

Call a function by writing its name followed by parentheses.
Include arguments inside parentheses if the function needs inputs.
Forgetting parentheses means the function won't run, just referenced.
Function declarations can be called before they appear in code.
Use parentheses carefully to control when functions run.