JavaScript Functions and Events (2023)

Notes taken from various websites including:

https://www.w3schools.com/js/js_whereto.asp

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

JavaScript Functions

A JavaScript function is a block of JavaScript code, that can be executed when “called” for.

For example, a function can be called when an event occurs, like when the user clicks a button.

A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output.

Source

Function declarations
A function definition (also called a function declaration, or function statement) consists of the function keyword, followed by:

The name of the function.
A list of parameters to the function, enclosed in parentheses and separated by commas.
The JavaScript statements that define the function, enclosed in curly brackets, { /* … */ }.
For example, the following code defines a simple function named square:

function square(number) {
return number * number;
}

The function square takes one parameter, called number. The function consists of one statement that says to return the parameter of the function (that is, number) multiplied by itself. The statement return specifies the value returned by the function:

return number * number;

Parameters are essentially passed to functions by value — so if the code within the body of a function assigns a completely new value to a parameter that was passed to the function, the change is not reflected globally or in the code which called that function.

When you pass an object as a parameter, if the function changes the object’s properties, that change is visible outside the function, as shown in the following example:

function myFunc(theObject) {
theObject.make = “Toyota”;
}

const mycar = {
make: “Honda”,
model: “Accord”,
year: 1998,
};

console.log(mycar.make); // “Honda”
myFunc(mycar);
console.log(mycar.make); // “Toyota”

Differences between functions and methods (taken from Geeks for Geeks)

FunctionMethod
A JavaScript function is a block of code designed to perform a particular task.The javascript method is an object property that has a function value.
Syntax of Function is -:function functionName(parameters) {
   // Content
}
Syntax of Method is -:object = {
   methodName: function() {
       // Content
   }
};object.methodName()
A function can pass the data that is operated and may return the data. The method operates the data contained in a Class.
Data passed to a function is explicit.A method implicitly passes the object on which it was called.
A function lives on its own.A method is a function associated with an object property.
A function can be called directly by its name A method consists of a code that can be called by the name of its object and its method name using dot notation or square bracket notation.
Functions are helpful because it increases the reusability of the code.Javascript includes some in-built methods also for example -: parseInt() Method
The () Operator is used to Invoke the FunctionWe can access object method by the following the syntax -:objectName.methodName()

External JavaScript Advantages

Javascript can also be placed in the <body> of a HTML document and in external sheets with the file extension .js (not sure why I thought this was relevant, but there you go!)
Placing scripts in external files has some advantages:

It separates HTML and code
It makes HTML and JavaScript easier to read and maintain
Cached JavaScript files can speed up page loads

JavaScript Output

ref

JavaScript can interact with the DOM/webpage and display different data in several ways:

  • Wrting into an HTML element using innerHTML
  • Wirting into the HTML output using document.write()
  • Writing into an alert box, using window.alert()
  • Wiring into the browser console, using console.log()

Using InnerHTML

use the document.getElementByID(id) method.

JavaScript Events

HTML events are “things” that happen to HTML elements.

When JavaScript is used in HTML pages, JavaScript can “react” on these events.

more info at w3schools

JavaScript’s interaction with HTML is handled through events that occur when the user or the browser manipulates a page.

When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other examples include events like pressing any key, closing a window, resizing a window, etc.

Developers can use these events to execute JavaScript coded responses, which cause buttons to close windows, messages to be displayed to users, data to be validated, and virtually any other type of response imaginable.

Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a set of events which can trigger JavaScript Code.

Please go through this small tutorial for a better understanding HTML Event Reference. Here we will see a few examples to understand a relation between Event and JavaScript −

onclick Event Type

This is the most frequently used event type which occurs when a user clicks the left button of his mouse. You can put your validation, warning etc., against this event type.

Example

Try the following example.

 Live Demo

<html>
   <head>   
      <script type = "text/javascript">
         <!--
            function sayHello() {
               alert("Hello World")
            }
         //-->
      </script>      
   </head>
   
   <body>
      <p>Click the following button and see result</p>      
      <form>
         <input type = "button" onclick = "sayHello()" value = "Say Hello" />
      </form>      
   </body>
</html>

More info at Tutorialspoint (includes a massive list of event types)

The This Keyword in JavaScript (2023)

This – references the object that is executing the current function

  • If the function is part of an object, we call that function a method.

“This” will reference that object

  • if the function is a regular function

“This” will reference the global / window object

in case, like me, you’ve forgotten what an object is, Mozilla describes it as

“In JavaScript, an object is a standalone entity, with properties and type. Compare it with a cup, for example. A cup is an object, with properties. A cup has a color, a design, weight, a material it is made of, etc. The same way, JavaScript objects can have properties, which define their characteristics.”

Example of an Object – with a function/method:

const person = {
  firstName: "John",
  lastName : "Doe",
  id       : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};

In the example above, this refers to the person object. Because the function is in an object

Some more notes about the This Keyword, robbed from around the web:

In general, the this references the object of which the function is a property. In other words, the this references the object that is currently calling the function.

Javascript Tutorial

Suppose you have an object called counter that has a method next(). When you call the next() method, you can access the this object.

let counter = {
  count: 0,
  next: function () {
    return ++this.count;
  },
};

counter.next();

Inside the next() function, the this references the counter object. See the following method call:

counter.next();

Global context

In the global context, the this references the global object, which is the window object on the web browser or global object on Node.js.

This behavior is consistent in both strict and non-strict modes. Here’s the output on the web browser:

console.log(this === window); // trueCode language: JavaScript (javascript)

If you assign a property to this object in the global context, JavaScript will add the property to the global object as shown in the following example:

this.color= 'Red';
console.log(window.color); // 'Red'

The this keyword is a source of confusion.

If you just type and run “this”, you’ll get the window object (the top of the DOM hierarchy)

If you type “this” inside a function, the value of this is contextual and dynamic. It can change.

Mozilla JS website

In most cases, the value of this is determined by how a function is called (runtime binding). It can’t be set by assignment during execution, and it may be different each time the function is called. The bind() method can set the value of a function’s this regardless of how it’s called, and arrow functions don’t provide their own this binding (it retains the this value of the enclosing lexical context).

In non–strict mode, this is always a reference to an object. In strict mode, it can be any value. For more information on how the value is determined, see the description below.

Description

The value of this depends on in which context it appears: function, class, or global.

Function context

Inside a function, the value of this depends on how the function is called. Think about this as a hidden parameter of a function — just like the parameters declared in the function definition, this is a binding that the language creates for you when the function body is evaluated.

For a typical function, the value of this is the object that the function is accessed on. In other words, if the function call is in the form obj.f(), then this refers to obj. For example:

function getThis() {
  return this;
}

const obj1 = { name: "obj1" };
const obj2 = { name: "obj2" };

obj1.getThis = getThis;
obj2.getThis = getThis;

console.log(obj1.getThis()); // { name: 'obj1', getThis: [Function: getThis] }
console.log(obj2.getThis()); // { name: 'obj2', getThis: [Function: getThis] }

More info and better description of this keyword on the Mozilla website here

Arrow Functions vs Regular Functions in JavaScript (2023)

JavaScript has 2 types of functions.

Normal/regular functions

Arrow functions

Arrow functions are simpler and shorter.

A normal JS function, with arguments (stuff in brackets), which returns something:

function multiply(num1, num2) {
  const result = num1 * num2
  return result
}

The same function, as an arrow function is:

const multiply = (num1, num2) => {
  const result = num1 * num2
  return result
}

If the only statement, is the return statement, then the arrow function can be even shorter:

const multiply = (num1, num2) => num1 * num2

Reference

Freecodecamp


You can define functions in JavaScript by using the “function” keyword.

// Function declaration
function greet(who) {
  return `Hello, ${who}!`;
}

The second way to define a function, is to use the arrow function syntax:

const greet = (who) => {
return Hello, ${who}!;
}


Reference

dmitripavlutin.com


  1. you can omit the return statement and curly braces in arrow function, when its a one line function

2. When the function has only 1 argument, the round bracket is optional.