JavaScript Functions

JavaScript Functions

Last weeks I've worked mostly with arrays and functions, and I want to share some of what I've learned about functions.

JavaScript function is a block of code designed to perform a particular task. A JavaScript function is executed when "something" invokes it (calls it). Functions are used to perform operations. We can call JavaScript function many times to reuse the code. There are mainly two advantages of JavaScript functions:

  1. Code reusability: we can call a function several times so it save coding.
  2. Less coding: it makes our program compact; we don’t need to write many lines of code each time to perform a common task.

JavaScript Function Syntax

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). Function names can contain letters, digits, underscores, and dollar signs (same rules as variables). The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...). The code to be executed, by the function, is placed inside curly brackets: {}.

function functionName(parameter1, parameter2, parameter3){ 
 //code to be executed  
}           

Function parameters are listed inside the parentheses () in the function definition. Function arguments are the values received by the function when it is invoked. Inside the function, the arguments (the parameters) behave as local variables.

Function Invocation

As I said above, the code inside the function will execute when "something" invokes (calls) the function:

  • When an event occurs (when a user clicks a button)
  • When it is invoked (called) from JavaScript code
  • Automatically (self invoked)

The () operator invokes the function. Accessing a function without () will return the function object instead of the function result.

JavaScript Functions can have 0 or more arguments(parameters).

A simple example of function in JavaScript that does not has arguments:

function myFunction() {
   alert("Hi! This is a simple JS function");
}

myFunction()

//Output will show an alert in browser with the message above.        

JavaScript Function Arguments

We can call function by passing arguments. Let’s see the example of function that has one argument:

let number = 4;

function getCube(number) {
   alert(number * number * number)
}

get cube();

//Output will show an alert with the number 64 (4 * 4 * 4)        

Function with Return Value

We can call function that returns a value and use it in our program. Let’s see the example of function that returns value:

function getInfo() {
   return "Hello JavaScript!"
}
console.log(getInfo());

//Output will show in console: Hello JavaScript!        

JavaScript Function Object

In JavaScript, the purpose of Function constructor is to create a new Function object. It executes the code globally. However, if we call the constructor directly, a function is created dynamically but in an unsecured way.

Syntax:

new function([arg1[,arg2[,...argn]],]functionBody)        

Parameter:

arg1, arg2, .... , argn - represents the argument used by function.

functionBody - represents the function definition.

JavaScript Function Methods

Let's see function ,ethods with description:

  • apply() -  is used to call a function contains this value and a single array of arguments.
  • bind() - is used to create a new function.
  • call() - is used to call a function contains this value and an argument list.
  • toString() - It returns the result in a form of a string.

JavaScript Function Object Examples

Example for displaying the sum of given numbers:

let add = new Function('num1', 'num2', 'return num1 + num2');
console.log(add(2, 5));

//Output: 7        

Example for displaying the power of provided value:

let pwr = new Function('num1', 'num2', 'return Math.pow(num1,num2)')

console.log(pwr(2, 4));

//Output: 16        

* The Math.pow() method returns the value of a base raised to a power. That is:

No alt text provided for this image



Why Functions?

You can reuse code: define the code once, and use it many times. You can use the same code many times with different arguments, to produce different results.

To view or add a comment, sign in

More articles by Cristian Micicoi

  • First steps towards React

    Once you have a good understanding of JavaScript, you can start learning the basics of React. React is built on top of…

  • JavaScript Conditionals

    JavaScript conditionals are a crucial element of programming, allowing developers to control the flow of their code…

  • Variables in JavaScript

    So far I've written what I've learned about JavaScript, but I haven't really specified what variables and their…

    1 Comment
  • JavaScript alert()

    The browsers we use can invoke a system dialog to display information to the user. The system dialog is not related to…

  • JavaScript Array map() method

    Sometimes you may need to take an array and apply some procedure to its elements so that you get a new array with…

  • JavaScript Objects

    In the previous article I presented the basics of what I learned about arrays in JavaScript and about the fact that…

  • JavasScript Arrays

    In JavaScript, objects allow you to store keyed collections of values. That’s fine.

  • JavaScript - HTML DOM Methods

    DOM stands for Document Object Model. It is an application programming interface that allows us to create, add, modify…

  • JavaScript Classes

    A class is a blueprint for the object. You can create an object from the class.

  • JavaScript setInterval() method

    Javascript setInterval() Today I learned about another JavaScript method, called setInterval(). I used it in creating…

    2 Comments

Insights from the community

Others also viewed

Explore topics