Skip to main content

Command Palette

Search for a command to run...

Talking about JavaScript function

Published
2 min read
Talking about JavaScript function
M

I’m a Front End web developer. Everyone likes to write. I’m one of them. However, I’m not a professional writer. Sometimes I write and publish my experiences.

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 ...
}

Example

function firstFunction () {
     console.log('JavaScript function');
}
firstFunction();
// JavaScript function

Function Expressions

A function expression can be stored in a variable. Syntax

let firstFunction = function () {
    // Code here ...
}

Example

let firstFunction = function () {
     return "JavaScript function";
}
firstFunction();
// JavaScript function

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 ... ;

Example:

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

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.

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 ...
}

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