Identifying the Functions and Methods in JavaScript

Objective

After completing this lesson, you will be able to Identify the functions and methods in JavaScript.

Functions and Methods

Introduction

Functions are one of the basic building blocks in JavaScript. A function is a set of instructions that perform a task or calculate a value. Functions are reusable and can be called anywhere in your code. They also help organize your code and make it more readable.

Function Declaration

Here's how to define a simple function in JavaScript.

Code Snippet
Copy code
Switch to dark mode
123
function FnName(parameters) { // code to be executed }
  • function is a keyword that starts the function declaration.
  • nameOfFunction is the name of the function. Function names can contain letters, digits, underscores, and dollar signs.
  • parameters are optional and represent values that we can pass into the function. They act as placeholders for actual values, also known as arguments, that will be input when the function is called.

Refer to the following example.

Code Snippet
Copy code
Switch to dark mode
123
function greet(name) { console.log("Hello, " + name); }

In the function greet, name is a parameter. When we call the function, we provide an argument for that parameter.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
1
greet("Alice"); // Outputs: "Hello, Alice"

Functions can have multiple parameters.

Code Snippet
Copy code
Switch to dark mode
1234567
function addNumbers(num1, num2) { return num1 + num2; } let sum = addNumbers(5, 10); console.log(sum); // Outputs: 15

In this case, the function addNumbers is returning the sum of num1 and num2, which is stored in the variable sum and then logged to the console.

Function Expression

Function expressions in JavaScript are a way to define functions as expressions rather than standalone function declarations. Function expressions can be stored in variables, array values, and object properties and passed as arguments to other functions or returned as values by other functions.

Function expressions can be named or anonymous.

Here is an example of a named function expression.

Code Snippet
Copy code
Switch to dark mode
123
let greet = function sayHello() { console.log("Hello, world!"); }

In this example, sayHello is the name of the function. However, this name is only in scope within the function itself, which is useful for recursion (when a function calls itself). Outside the function, you would still call it using the variable name: greet();

Function expressions are used for a variety of reasons, such as:

  • They can be used in places where statements aren't allowed, such as inside ternary operators or inside expressions.
  • They allow you to define "private" functions that can only be accessed within the scope of an outer function.
  • They can be used to define Immediately Invoked Function Expressions (IIFEs), which run as soon as they are defined.

In general, function expressions provide a lot of flexibility in how you define and use functions in JavaScript.

Arrow Function

Arrow functions were introduced in ES6 (ECMAScript 2015) as a new syntax for writing JavaScript functions. They save developers time and simplify function scope.

Here's a basic example of an arrow function.

Code Snippet
Copy code
Switch to dark mode
123
let greet = (name) => { console.log("Hello, " + name); }

This will behave the same way as the previous function expression examples.

You can also call this function the same way.

Code Snippet
Copy code
Switch to dark mode
1
greet("Caroline"); // Output: "Hello, Caroline"

Arrow functions are more powerful and flexible than this, however.

If there's only one argument, you can omit the parentheses around the parameters.

Code Snippet
Copy code
Switch to dark mode
123
let greet = name => { console.log("Hello, " + name); }

If the function body just returns a value, you can omit the curly braces and the return keyword.

Code Snippet
Copy code
Switch to dark mode
1234
let square = num => num * num; console.log(square(5)); // Output: 25

This version of the function takes a number, squares it, and returns the result.

One key feature of arrow functions is that they do not have their own this value. The value of this inside an arrow function is always inherited from the enclosing scope. This is different from regular function expressions, which create their own this value. This makes arrow functions very useful when working with object methods, callbacks, and closures.

Immediately Invoked Function Expressions (IIFE)

An IIFE (pronounced "iffy") is a JavaScript function that is executed as soon as it is defined. The main reason for using an IIFE is privacy, because variables declared inside the IIFE cannot be accessed by the outside world.

Here is the syntax of an IIFE.

Code Snippet
Copy code
Switch to dark mode
123
(function() { // statements })();

Or it can also be written with arrow function syntax.

Code Snippet
Copy code
Switch to dark mode
123
(() => { // statements })();

Here's a simple example.

Code Snippet
Copy code
Switch to dark mode
1234567
(function() { let message = "Hello, world!"; console.log(message); // Output: "Hello, world!" })(); console.log(message); // Output: Error: message is not defined

In this example, message is a variable that's only visible within the scope of the IIFE. The IIFE runs immediately, printing "Hello, world!" to the console. When we try to log message outside of the IIFE, we get an error because message is not defined in that scope.

IIFEs are commonly used to create a new lexical scope — they allow you to create local variables that don't pollute the global scope. This is particularly useful if you're writing a library and you don't want to add any new global variables that could conflict with other scripts on the page.

It's important to note that while IIFEs were once the common way to create private scope, the introduction of block-scoped variables (let and const) and modules in ES6 has provided other, often clearer, ways to accomplish the same goals.

Methods

In JavaScript, functions can also be defined as object properties. When a function is a property of an object, we call it a method.

Here's an example of an object that has a method.

Code Snippet
Copy code
Switch to dark mode
1234567
let person = { firstName: "John", lastName: "Doe", fullName: function() { return this.firstName + " " + this.lastName; } };

In this case, fullName is a method of the person object. You can call it as shown in the following code snippet.

Code Snippet
Copy code
Switch to dark mode
1
console.log(person.fullName()); // Outputs: "John Doe"

Note the use of the this keyword in the fullName method. Inside a method, this refers to the object that the method is a part of. So this.firstName is equivalent to person.firstName, and this.lastName is equivalent to person.lastName

It's important to note that starting with ES6, there's a new shorthand for defining methods in an object.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
1234567
let person = { firstName: "John", lastName: "Doe", fullName() { return `${this.firstName} ${this.lastName}`; } };

In this case, the function keyword is dropped and we use template literals for string concatenation, which is a more modern approach and is widely used in contemporary JavaScript code.

Whether you're using methods to manipulate the data within your object, or to provide functionality related to your object, methods are a fundamental part of working with objects in JavaScript.

Scope

Introduction

In JavaScript, scope refers to the context in which variables and functions are declared, and how they are accessible in your code. Essentially, it determines the visibility and lifecycle of variables and parameters.

There are three types of scope in JavaScript:

  1. Global Scope: Variables declared outside any function, block, or module scope have global scope. They can be accessed from any function or block in the program.

  2. Function Scope: Variables declared within a function using the var keyword are scoped to that function. They can only be accessed within that function.

  3. Block Scope: Variables declared with let and const are block-scoped, meaning they can only be accessed within the block of code in which they were defined.

Let's look at each type of scope in detail.

Global Scope

When a variable in JavaScript is declared outside of a function or block, it is called a global definition. This means that it can be accessed from any part of the code, including inside functions and inside blocks.

Here's a simple example of a global variable.

Code Snippet
Copy code
Switch to dark mode
123456789
let myGlobalVariable = "Hello, world!"; function sayHello() { console.log(myGlobalVariable); // "Hello, world!" } sayHello(); // Outputs "Hello, world!"

In this example, myGlobalVariable is a global variable because it's declared outside of the sayHello function. This means it can be accessed inside the sayHello function when we call it.

Global variables are useful when you need to manage data that you want to be able to access from multiple parts of your script. However, excessive use of global variables can cause problems:

  1. Namespace pollution: When your codebase has too many global variables, there's a higher risk of variable name clashes. This is particularly problematic when integrating with third-party scripts.

  2. Code maintainability: Global variables can be modified from any part of your code, making it harder to keep track of where changes are being made.

  3. Memory consumption: Global variables remain in memory for as long as your page is running, which can lead to higher memory usage.

Considering these potential issues, it's generally best to limit the use of global variables and use local scope (function or block scope) where possible.

Block Scope

The Block scope, introduced in ES6 with the keywords let and const, refers to a scope created inside a set of curly braces {}. This can be in a function, an if statement, a for loop, a while loop, or some other type of block. Variables declared within a block using let or const can only be accessed within that block, and only after they have been declared.

Here's an example.

Code Snippet
Copy code
Switch to dark mode
1234567
if (true) { let blockVar = "I am inside a block!"; console.log(blockVar); // Outputs: "I am inside a block!" } console.log(blockVar); // Error: blockVar is not defined

In this code, blockVar is only accessible within the if block where it's declared. Trying to access it outside that block results in an error, because blockVar is not defined in that scope.

Block scope is a powerful tool that can help you write cleaner, more maintainable code. It allows you to limit the visibility of variables to where they're needed, reducing the risk of naming collisions and unexpected side effects.

It's worth noting that var, the traditional way to declare variables in JavaScript, does not respect block scope. Instead, var creates function scope or global scope variables. This is a key reason let and const are often preferred over var in modern JavaScript code.

Function Scope

Function scope in JavaScript refers to the range in which variables can be accessed. When you declare a variable inside a function with the var keyword, it is restricted to that function, which means that it can be accessed only inside that function. This is called function scope.

Here's a simple example.

Code Snippet
Copy code
Switch to dark mode
12345678
function myFunction() { var functionScopedVariable = "I am inside the function"; console.log(functionScopedVariable); // Outputs: "I am inside the function" } myFunction(); console.log(functionScopedVariable); // Error: functionScopedVariable is not defined

In this example, functionScopedVariable is only visible within myFunction. When we try to log functionScopedVariable outside of myFunction, we get an error because functionScopedVariable is not defined in that scope.

It's important to note that this only applies to variables declared with var. If you declare a variable inside a function using let or const, it will be block scoped, not function scoped. This is one of the reasons why let and const are generally preferred over var in modern JavaScript. They allow for better control over the scope of variables, which can help prevent bugs and make your code easier to understand.

Context

Introduction

In JavaScript, context refers to the value of this within a function or a method during its execution. The context determines what this refers to, and it's based on how the function is called, not where the function is defined. The context is crucial when working with objects, methods, and event handlers, because it helps to understand and manage the relationships between different parts of your code.

Method Context

When a function is a property of an object (a method), the context is the object itself.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
123456789
let person = { name: "Peter", sayHello: function() { console.log("Hello, " + this.name); } }; person.sayHello(); // Outputs: "Hello, Peter"

In this case, this refers to person because sayHello is invoked as a method of person.

Function Context

In a regular function (that is, one not called as a method), this usually refers to the global object (window in a browser). However, in strict mode, this will be undefined.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
12345
function greet() { console.log('Hello, ' + this.name); } let name = 'Bob'; greet(); // 'Hello, Bob' (or 'Hello, undefined' in strict mode)

In this case, this inside greet refers to window (or is undefined in strict mode), not to any particular object.

Event Handler Context

In an event handler, this refers to the element that is currently handling the event.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
123
btn.addEventListener('click', function() { console.log(this.id); });

The value of this can be confusing because it's not determined by how or where a function is defined, but by how it's called. If you're ever in doubt, ask yourself: "What is this function being called on?" That's usually what this refers to.

Event Handler

Introduction

Event handlers in JavaScript are functions that are triggered in response to specific events occurring in a web application, such as user interactions or changes in the Document Object Model (DOM). They allow you to create dynamic and interactive web applications by executing code based on user input or other events.

Here's an overview of how to create event handlers in JavaScript.

Inline Event Handlers

These are added directly within the HTML markup. This is generally not recommended, as it can make the code harder to maintain and is not considered best practice.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
1
<button onclick="alert('Button clicked!')">Click me</button>

Traditional Event Handlers

These are added by assigning a function to an element's event property. This method can only handle one event listener per event type.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
1234
const button = document.getElementById('myButton'); button.onclick = function() { alert('Button clicked!'); };

Event Listeners

This is the preferred method of attaching event handlers, because it provides more flexibility and allows you to add multiple event listeners for the same event type.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
1234
const button = document.getElementById('myButton'); button.addEventListener('click', function() { alert('Button clicked!'); });

You can also use the removeEventListener method to remove event listeners when they are no longer needed.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
12345678
function handleClick() { alert('Button clicked!'); button.removeEventListener('click', handleClick); } const button = document.getElementById('myButton'); button.addEventListener('click', handleClick);

Event Delegation

This technique involves attaching a single event listener to a parent element that listens for events from its child elements. This can be more efficient and makes it easier to handle events for dynamically added elements.

Refer to the following code snippet.

Code Snippet
Copy code
Switch to dark mode
12345678
const parentElement = document.getElementById('parent'); parentElement.addEventListener('click', function(event) { if (event.target.tagName === 'BUTTON') { alert('Button clicked!'); } });

In this example, clicking any button within the parent element will trigger the alert. The event object contains information about the event, such as the target element, event type, and more.

These are the basic concepts of event handling in JavaScript. You can use these techniques to create interactive web applications and respond to various events triggered by user actions or changes in the DOM.

Log in to track your progress & complete quizzes