Computer Science

Javascript Function

A JavaScript function is a block of code that performs a specific task. It is defined using the "function" keyword and can be called multiple times within a program. Functions can take input parameters and return output values, making them reusable and efficient for organizing and executing code.

Written by Perlego with AI-assistance

6 Key excerpts on "Javascript Function"

  • Book cover image for: JavaScript: Novice to Ninja
    • Darren Jones(Author)
    • 2017(Publication Date)
    • SitePoint
      (Publisher)

    Chapter 4: Functions

    A function is a chunk of code that can be referenced by a name, and is almost like a small, self-contained mini program. Functions can help reduce repetition and make code easier to follow. In this chapter, we’ll be covering these topics:
    • Defining functions―function declarations, function expressions, Function() constructors and the new arrow syntax
    • Invoking a function
    • Return values
    • Parameters and arguments
    • Hoisting―variables and functions
    • Callbacks―functions as a parameter
    • Project ― we’ll be using functions to make the Quiz Ninja code easier to follow
    In JavaScript, functions are considered to be first-class objects. This means they behave in the same way as all the other primitive data types and objects in the language. They can be be assigned to variables, stored in arrays and can even be returned by another functions.
    This makes functions a very important and powerful part of the JavaScript language with many of its features relying on them. Fully understanding functions is an essential skill of the JavaScript ninja.

    Defining a Function

    There are a number of ways to define a function in JavaScript. Three of the most common are covered below. ES6 introduced a new way to define functions, using what is known as 'arrow' notation. This is covered later in the chapter.

    Function Declarations

    To define a function literal we can use a function declaration:
    function hello(){ console.log('Hello World!'); }
    This starts with the function keyword and is followed by the name of the function, which in this case is called 'hello ', followed by parentheses. Following this is a block that contains the code for the function.
    This is known as a named function as the function has a name: 'hello '.

    Function Expressions

    Another way of defining a function literal is to create a function expression. This assigns an anonymous function
  • Book cover image for: Multimedia Web Design and Development
    No longer available |Learn more

    Multimedia Web Design and Development

    Using Languages to Build Dynamic Web Pages

    client-side language, meaning all of the computations are done and actions are taken on the client’s Web browser.
    A programming language is a formal set of commands that can be used to manipulate data in a system; the programs using this kind of language are compiled and linked, turning the manually typed code into machine code prior to execution.
    A scripting language is a formal set of commands that can be used to manipulate data in a system; the scripts using this kind of language are written without the steps to compile and link them into machine code prior to execution.
    A client-side language, or front-end language, is a scripting or programming language that is executed on the local machine without involvement from the server. The client can view all source code.
    A server-side language , or back-end language, is a scripting or programming language that is executed on the server, where only the results of the computation are delivered to the client machine. In general, the client does not see the source code.
    Computational complexity is an estimate of how long it will take a program or a script to complete its operation. Syntax structures like loops and complex mathematics increase the complexity of a program or script. This can be measured in different units and is often a general estimate.
    A variable is a named placeholder representing a data value that may or may not change during execution.
    When JavaScript is invoked, the browser is using the computing resources of the local machine to process the information and compute the results. This means the server is not slowed down by this computation, but it also means the speed and efficiency of the script are determined by the state of the user’s machine, which is generally unknown. For this reason, JavaScript works best when it is concise and limited in computational complexity
  • Book cover image for: JavaScript for Web Warriors
    • Patrick Carey, Sasha Vodnik, Patrick Carey(Authors)
    • 2021(Publication Date)
    37 So far, the code you have written has consisted of simple statements placed within script sections. However, like most programming languages, JavaScript allows you to group programming statements in logical units. In JavaScript, a group of statements that you can execute as a single unit is called a function. You’ll learn how to create functions in this chapter, and you’ll practice using them to organize your code. In addition to functions, one of the most important aspects of programming is the ability to store values in computer memory and to manipulate those values. In the last chapter, you learned how to store values in computer memory using variables. The values, or data, contained in variables are classified into categories known as data types. In this chapter, you’ll learn about JavaScript data types and the operations that can be performed on values of each type. You’ll also explore the order in which different operations are performed by JavaScript processors, as well as how to change this order. CHAPTER 2 When you complete this chapter, you will be able to: ❯ ❯ Write and call functions to perform actions and calculate values ❯ ❯ Associate functions with events using event handlers and event listeners ❯ ❯ Use built-in Javascript Functions ❯ ❯ Understand the scope of variables and functions ❯ ❯ Understand the data types supported by JavaScript and write expressions with numeric values, text strings, and Boolean values ❯ ❯ Create expressions using arithmetic, assignment, comparison, logical, string, and special operators ❯ ❯ Understand order precedence and associativity of operations ❯ ❯ Work with events and values associated with form controls ❯ ❯ Access your browser’s debugging console Working with Functions, Data Types, and Operators Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
  • Book cover image for: JavaScript for Modern Web Development
    eBook - ePub

    JavaScript for Modern Web Development

    Building a Web Application Using HTML, CSS, and JavaScript

    • Alok Ranjan, Alok Ranjan, Abhilasha Sinha, Ranjit Battewad(Authors)
    • 2020(Publication Date)
    • BPB Publications
      (Publisher)
    }
  • Function: A block of code performing some action. We will learn more about functions in the next section.
  • Functions

    We have always seen people repeating the same code again and again, which raises the need for putting the common code in a single place and reuse it. Functions help us achieve that in different ways.

    What is a function?

    A function is a code block that is designed to work together to perform a specific task. The task to be done by the function is defined once and can be invoked or executed in the form of a function, a number of times.
    A simple explicit function can be defined is shown as follows: function calculateDistanceTravelled( startPos, currentPos ) { var distance = Math.sqrt( Math.pow(currentPos.xPos - startPos.xPos, 2) + Math.pow(currentPos.yPos - startPos.yPos, 2)); return Math.ceil(distance); } Here you have done the following:
    • function keyword is used to explicitly define and give a name to the function as the name, calculateDistanceTravelled
    • The function accepts two parameters (JavaScript objects)
    • A local variable is used inside the function to hold the calculated distance value
    • Logic to apply ceiling to the calculated distance
    • Finally, return a value from the function to indicate the end of execution flow and transfer of control back to the caller
      • Note that if the return statement is not explicitly provided, then undefined is returned as a value.

    More about functions

    In the previous section, we defined a function. Now we will use it by invoking it. For this we will have to pass the required parameters to the function call as shown in the following code block: var startPos = { xPos : 20, yPos : 20 }; var currentPos = { xPos : 40, yPos : 40 }; document.write("You have travelled : " + calculateDistanceTravelled(startPos, currentPos) + " KM ");

    Function as expression

    We used the Pow method of the Math object to define the function in the example earlier. Let's define an explicit function like square to calculate the square of a number, using a function expression as shown.
  • Book cover image for: Web Programming
    eBook - PDF

    Web Programming

    Building Internet Applications

    • Chris Bates(Author)
    • 2014(Publication Date)
    • Wiley
      (Publisher)
    Figure 6.10 shows this in action. 1 document.writeln("

    "); data.splice(2, 0, "element one", "element two"); document.writeln(data.join(", ") + "
    "); data.splice(3, 3, "element three", "element four"); 5 document.writeln(data.join(", ")); document.writeln("

    "); unshift(element1[, element2[,elementN]]) inserts a list of elements onto the front of the array. The list of new elements can have just one item. Although this discussion of arrays has been long and rather involved, they are an important structure in JavaScript. When I start to show some dynamic HTML you will see that everything revolves around the manipulation of arrays so it is important that you have a good understanding of how they work. 188 6. An Introduction to JavaScript New elements Array Splice at position 2 Delete from 3 and 4 Figure 6.10 Splicing arrays 6.10 FUNCTIONS A function is a piece of code that performs a specific task. These tasks are larger than those of a statement – almost every function is made up of a number of statements. By creating a function the same piece of code can be used repeatedly throughout the time that the program runs yet it only needs to be developed in one place. JavaScript has a lot of functions built into the language. You have already seen some of these and you will meet more as we go along. Once you have created some functions you need to know how to use them. This is done by calling the function. When programmers talk about a function call they are talking about using the code in the function at another point in the program. Until the program calls a function, that code will not do anything. This can be useful as it means that you can partially develop your functions without affecting the rest of your program provided you do not call them. 6.10.1 Defining Functions function name(parameters) Functions are (not surprisingly) defined using the function keyword.
  • Book cover image for: JavaScript for Sound Artists
    eBook - PDF

    JavaScript for Sound Artists

    Learn to Code with the Web Audio API

    • William Turner, Steve Leonard(Authors)
    • 2017(Publication Date)
    • Routledge
      (Publisher)
    39 5 In this chapter, you will learn about functions, various ways to work with functions, and variable scope Functions allow you to write code in a way that avoids repetition They also allow you to encapsulate your code and perform a specific task based on a set of inputs Scope pertains to the context in which variables are declared JavaScript handles variables differently depending on their scope, and you will learn how to use variables in functions when writing programs Functions—A Simple Example To explain functions, let’s look at the design of an audio effects module Imagine a simple hardware audio effects box equipped with a single input channel and a single output channel Now imagine this effects box changes the original input in some way depending on a collection of user-defined settings In this design, the output of the effects box is the result of the input signal combined with the user settings that produce some change in the original signal Functions
  • Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.