Javascript all functions with examples

Function In JavaScript

In this tutorial, you will learn about javascript functions, how to define them, how to use them, why to use them, etc with various examples.

What is a function?

A function is a named sequence of statements that performs a specific operation. Functions are used to break down a program into smaller, reusable pieces.

function name(param1, param2, . ) < // statements >

In javascript, a function is defined using the keyword function and is immediately followed by the function name and a pair of parenthesis.

Inside the parenthesis, you can define any number of arguments that are passed to the function when it is called.

The function can return a value by using the return statement, or it can end the function by using the return keyword.

Читайте также:  Код javascript во внешнем файле

javascript function

The basic idea of a function is to reduce the number of repeated code blocks and executing a code block whenever needed.

function add(a, b) < let sum = a + b; // statement return sum; // return >console.log(add(1, 2));

Javascript Function Declaration

A function declaration is a way to declare a function in javascript. It is a way to tell javascript that you want to create a function and to give it a name.

To use a function you must first declare it. In javascript, the function is declared by using the function keyword.

Syntax

function name_of_function (param1, param2. ) < // javascript statements return something; >

Here are the steps to declare a function in javascript.

  1. Start function with the function keyword
  2. Then write the name of the function with a space. The naming convention of function is the same as a variable naming convention.
  3. Then give arguments to the function enclosed in parentheses and separated by commas like (parameter1, parameter2, . )
  4. Then define the function body by curly braces
  5. At the end of the function use return keyword to return any object or value.

Example

// Function declaration function hello()

Javascript function call

Just defining a function does nothing until it is invoked or called.

How to call a function in javascript?

To call a function, you need to use the function name followed by a parenthesis and the arguments that you want to pass to the function.

If there is no parameter then write blank parenthesis.

// Function declaration function hello() < console.log("Hello World!"); >// Function call hello();
// Function declaration function hello(name) < console.log(`Hello $!`); > // Function call hello("John");

Call Javascript Function From HTML

You can call a javascript function from HTML using events.

When an event occurs like button click, mouse move, document load, etc then you can use some event handler to trigger the event which will call the function.

  

Use some event to call a function from HTML.

function message()

Note : You can call a function from any event we want and as many times.

Javascript function parameter

Javascript function parameters are the values that are passed in the function to be used inside its statements.

The actual values that are passed in the function are known as arguments while the variable that is declared in the function is known as a parameter.

The data type of javascript function parameter could be any valid data type, for example, string, number, array, etc.

function message(user, message) < console.log("User: " + user + " , Message: " + message); >message("Herry", "How are you?"); message("John", "I'm fine.");

What happens when you provide more or fewer parameters to the function than the defined arguments?

  1. When a number of arguments are less than parameters then the rest parameters will be undefined
  2. when the number of arguments are more than parameters then extra arguments will be ignored

Let’s see an example to understand.

function fullName(firstname, lastname) < console.log(firstname + " " + lastname); >fullName("Stephen", "Hawking"); // Stephen Hawking fullName("Stephen", "William", "Hawking"); // Stephen William fullName("Stephen"); // Stephen undefined

Javascript Function Return

Javascript function can return values to the caller. The return value is known as return value.

To return something from the function return keyword is used with the return value separated by space.

The function stops execution when reached to return statement even if there are more statements in the function after a return.

The return value can be stored in a variable.

function multiply(a, b) < return a * b; >// storing return value in a variable var value = multiply(4, 6); console.log(value);

The return value can be placed anywhere in the function but as soon as the function finds a return statement it stops further execution of the code in a function.

Also, you can use a return statement without returning any value just to stop the execution of the function.

function pass(mark) < if (!mark) < console.log("Invalid Marks!"); return; >if (mark > 40) < console.log("Pass!"); return true; >else < console.log("Fail!"); return false; >> pass(60);

Javascript Function Local Variable

The variables that are defined inside the function have local scope. This means these variables can’t be accessed outside the function.

But a function can access the variable that is defined outside the function.

function localVariable() < // local scope let a = 10; console.log("'a' inside function is " + a); >localVariable(); console.log("'a' outside function is " + typeof a);

Javascript Function Expression

Function expression lets us define the function and assign it to some variable.

A function expression, in general, has no name hence it is also called an anonymous function.

A function expression is more convenient to pass as an argument in callback functions.

var sum = function (num1, num2) < return num1 + num2; >// function called using variable name console.log(sum(12, 32));

Javascript Function Declaration VS Expression

These are 2 important differences between function declaration and function expression:

    A function declaration can be hoisted but a function expression can’t be hoisted. It means you can use a function before it is declared while you can’t use a function before function expression is declared.

hello(); // run successfully function hello() < // function declaration return "Hello World!"; >
hello(); // error function not declared let hello = function() < // function expression return "Hello World!"; >

Javascript Immediately Invoked Function Expression(IIFE)

immediately Invoked Function Expression (IIFE) is the function is executed right after the function is declared.

Syntax of IIFE

The variables defined inside IIFE is not accessible outside the function.

If you assign IIFE to some variable then it stored the function’s return value, not the function itself.

var example = (function()< return "Returned value is stored." >)(); console.log(example);

Frequently Asked Questions

  1. What is function and method in JavaScript? A function is a block of code that is used to perform a specific task. A method is a function that is associated with a specific object. A method can also be an instance function, which means that it is associated with an object and can be called directly on that object.
  1. Function in javascript is declared using the function keyword.
  2. A function can have any number of arguments starting from 0.
  3. You can call the javascript function from HTML using some event.
  4. As soon as the function reaches the return statement it stops further execution of it.
  5. Variable defined in a function has local scope and can’t be accessed outside the function.

Источник

Functions in JavaScript — with Examples [Updated]

For creating functions in JavaScript we have the «function» keyword.
Using this keyword we can tell JavaScript that we are declaring a function here.
After that, we have to give a name for our function
(Function name can be anything like yourname, ABC, myfun anything you want but there are some rules that your function can’t start with numbers like 123fun but you can use numbers at the end like myfun1, myfun2, etc)
followed by round brackets «myfunction()» and between «<>» curly braces we can write our code.

function myfunction() < alert("My First Function"); >myfunction();

Functions in JavaScript - with Examples [Updated]

keep in mind: Functions only execute their code when we call it. Without calling it won’t display any output. So to run your functions code you need to call your function.

How to call a function in JavaScript

In JavaScript, we have so many methods for calling functions.

Method 1: Calling a function using JavaScript

Here we can call our function by writing our function name inside after or before declaring your Function (It’s always recommended to call your function after declaring it).

//declaring function function myfunction() < alert("Calling using Method 1"); >//calling function myfunction();

Method 2: Calling a function using onClick Event

In HTML we have different types of Events (Like onCLick onSubmit, onHover, etc). So using those methods you can call a JavaScript function. Where when the onClick event will it will call our function and JavaScript will execute the code of our function.

   function myfunction() 

Method 2: Calling a function using onClick Event

How to call external javascript function from HTML button onclick

To call the external javascript function from HTML button onClick we need to import our External JavaScript first (Inside the HEAD tags or before calling it).

After successfully importing the External JavaScript file we can now call that JavaScript function by Using the Function Name (that we wanna call/Run) inside the onClick=» » event.

Types of functions in JavaScript

In JavaScript, we mainly have 3 types of functions
1. Named Functions
2. Anonymous Function
3. Immediately invoked function expressions

1. Named Functions in JavaScript

Named functions in JavaScript have a name, using which we can call the function from anywhere. Like from Script file by using «functionname();» or using Events like «onClick=’functionname()'».

2. Anonymous Functions in JavaScript

Anonymous Functions in JavaScript don’t have any names.
You can declare them anonymously and the name is not available nor needed in some tasks.

var myname = (function myname()< alert("programmingHEAD"); >)();

3. Immediately invoked function expressions in JavaScript

Immediately invoked function expressions in JavaScript are the same as Anonymous functions. You don’t have to give a function name (you can assign a function name if you want to) and the best thing is it’s going to run whenever the browser going to reaches this function without manually calling it.
So that’s why this is called Immediately invoked function expressions because it going to execute Immediately when the browser reaches it.

Function parameters/Arguments

Function parameters/Arguments are the names listed in the function definition. Function Parameters/Arguments are Values that we can pass while calling a function and access the values inside the function.

Function parameters/Arguments Syntax

function myfun(argument1, argument2)< //argument1 and 2 will be accessible here >

function in JavaScript example

Example 1: How to ADD, Subdivide and Multiply two numbers using Functions

function add(a,b) < alert(a+b); >function sub(a,b) < alert(a-b); >function multi(a,b) < alert(a*b); >add(5,2); sub(5,2); multi(5,2);

Example 2: Store your name inside a Variable using functions

var myname = (function greaterOrNot()< return "ProgrammingHead"; >)(); console.log(myname);

Here we declared our function as a value for a variable «myname» and then instead of alerting or printing our names to the output screen, we are returning our output value «programminghead» so we can store it inside our variable «myname».
After that, we can get our returned/Stored values from our variable name by using «alert(myname)».

Источник

Оцените статью