DEV Community

Cover image for Talking about JavaScript function
Md. Injamul Alam
Md. Injamul Alam

Posted on

1

Talking about JavaScript function

What is Function in JavaScript?

In JavaScript, functions are defined with the 'function' keyword.

  • There is an another way to define a function, called 'Arrow Function'.

Declaration a Function

Syntax

function firstFunction () {
     // Code here ...
}
Enter fullscreen mode Exit fullscreen mode

Example

function firstFunction () {
     console.log('JavaScript function');
}
firstFunction();
// JavaScript function
Enter fullscreen mode Exit fullscreen mode

Function Expressions

A function expression can be stored in a variable.
Syntax

let firstFunction = function () {
    // Code here ...
}
Enter fullscreen mode Exit fullscreen mode

Example

let firstFunction = function () {
     return "JavaScript function";
}
firstFunction();
// JavaScript function
Enter fullscreen mode Exit fullscreen mode

Arrow Function

Arrow function allows a short syntax for writing function expressions.

  • We don't need the 'function' keyword, the 'return' keyword and the 'curly' brackets.

Syntax

let change = (argument1, argument2) => Code here ... ;
Enter fullscreen mode Exit fullscreen mode

Example:

let add = (x , y) => x + y; 
add(4, 6);
// Output will 10 
Enter fullscreen mode Exit fullscreen mode

Function Parameters

If you want to build a dynamic function then you have to use parameters.

  • Parameters are like an input. Based on your input it gives you the output.

Syntax with example

function add(x, y) {
  return (x + y);
}
add(10, 5); // Output: 15,
// Here, x is 10, y is 5.
Enter fullscreen mode Exit fullscreen mode

Default Parameters

If a function is called with missing arguments, the missing values are set to undefined.

  • It is better to assign a default value to the parameter.

Syntax

function myFunction (argument1 = default value) {
   // Code here ...
}
Enter fullscreen mode Exit fullscreen mode

Example

function sum (x = 1, y = 1) {
    return (x + y);
}
sum(4, 6); // here x is 4, y is 6
sum(4); // here x is 4 but y is 1 (default value)
sum(); // here x is 1, y is 1
Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay