DEV Community

Cover image for JavaScript & TypeScript: How to Use Functions Inside Five
Dom | Five.Co
Dom | Five.Co

Posted on • Originally published at five.co

JavaScript & TypeScript: How to Use Functions Inside Five

One of the most significant ways to control and reuse code is with the time-honored approach of bundling it into a named block of code that can be invoked repeatedly: we speak, of course, of the traditional function.

JavaScript functions are essential building blocks in application development, enabling developers to create reusable blocks of code that perform specific tasks. They play a pivotal role in structuring and organizing code, promoting modularity and maintainability of applications.

In this article, we'll delve into the world of JavaScript functions, exploring their advantages and we will explain how to write functions inside of Five.

JavaScript: The Old Faithful

JavaScript, often referred to as the "language of the web," is a dynamic, interpreted language that runs directly in the browser. It provides the foundation for building interactive and dynamic web pages. JavaScript's syntax is concise and flexible, allowing developers to write code quickly and efficiently. This simplicity makes it an ideal choice for beginners or those who want to prototype and develop small-scale projects rapidly.

JavaScript functions

Syntax and Flexibility

One of JavaScript's key attractions is its familiar syntax. Its syntax resembles many other programming languages such as C, Java, and Python, making it easy to learn and adapt for developers coming from different backgrounds. For experienced programmers, the transition to JavaScript is usually seamless.

Another advantage is JavaScript's flexibility. It's a dynamically typed language, which means you don't need to explicitly declare variable types. This flexibility makes JavaScript forgiving, as it allows you to perform operations that other statically typed languages might consider errors. While this flexibility can lead to unexpected behavior if not handled carefully, it also enables rapid prototyping and quick iterations.

The JavaScript Ecosystem

JavaScript is known for its vast ecosystem of libraries, frameworks, and tools. The community-driven nature of JavaScript has led to the development of numerous open-source projects, making it easier for developers to find solutions to common problems. Popular JavaScript frameworks like React, Angular, and Vue.js have revolutionized web development by providing efficient and scalable ways to build user interfaces. Additionally, JavaScript has an expansive selection of libraries, such as Express.js and Redux, to address server-side, state management, and other specific needs.

TypeScript: The Type-Safe Alternative

TypeScript is a superset of JavaScript, meaning it builds upon JavaScript by adding static typing. It aims to enhance JavaScript's capabilities by enabling developers to catch type-related bugs during the development phase, rather than at runtime. TypeScript code runs through a compilation process that checks for type errors and transpiles it into JavaScript, which can then be executed by browsers or other JavaScript environments.

Static Typing Advantages

The key feature that sets TypeScript apart from JavaScript is static typing. With TypeScript, you can specify types for variables, function parameters, and return values. This additional layer of type checking catches potential errors and improves code quality. By catching type-related bugs earlier, TypeScript helps reduce the number of unforeseen issues that may arise during runtime.

Static typing also brings the advantage of better code documentation and improved readability. With explicitly defined types, developers can easily understand the expected inputs and outputs of functions, making code easier to understand and maintain. IDEs and code editors that support TypeScript can provide enhanced features such as autocompletion, refactoring tools, and immediate feedback on potential type mismatches.

Tooling and Development Experience

Alongside static typing, TypeScript provides a robust set of tools to enhance the development experience. The TypeScript compiler, tsc, offers a wide range of configuration options and can integrate with popular build systems such as Webpack or Babel. Additionally, TypeScript provides valuable features like code analysis, linting, and advanced language services to identify potential issues and improve code quality.

Another advantage of TypeScript is its compatibility with JavaScript. Since TypeScript is a superset of JavaScript, existing JavaScript code can be gradually migrated to TypeScript without any major alterations. Developers familiar with JavaScript can write TypeScript code from the start or begin with JavaScript and gradually introduce TypeScript's features as the project complexity increases.

The TypeScript Ecosystem

TypeScript adoption has been gaining momentum, and as a result, it now enjoys widespread community support and an expanding ecosystem. Many popular JavaScript libraries and frameworks, including React, Angular, and Vue.js, have dedicated TypeScript support, providing type definitions that enable developers to write TypeScript code with ease.

TypeScript also benefits from its close relationship with Microsoft. With robust documentation, official guides, and active development, TypeScript provides a level of stability and assurance to developers. This close relationship results in continuous improvements to the language and its tooling, ensuring that TypeScript remains a reliable and efficient choice for modern web development.

What are JavaScript Functions?

A function is a block of code that is used to perform a single, related action. Functions provide better modularity for your application as well as high code reusability.

Use of JavaScript Functions

JavaScript functions have a wide range of use cases due to their versatility and ability to encapsulate code logic. Here are some typical use cases for JavaScript functions:

Uses of JavaScript functions

1. Using Functions with Events:

Functions are commonly used as event handlers to respond to user interactions like button clicks, form submissions, or mouse movements. By attaching functions to events, developers can define specific actions or behaviors in response to user actions.

2. Data Processing and Manipulation:

Functions are frequently used for data processing and manipulation tasks, such as filtering, sorting, or transforming data. They enable developers to create reusable data processing pipelines, making it easier to work with complex datasets.

3. API Calls and Asynchronous Operations:

JavaScript functions are essential when working with APIs or performing asynchronous operations like fetching data from a server. Functions can be used to encapsulate API calls and handle responses, making the code more organized and reusable.

4. Code Reusability:

Functions are ideal for promoting code reusability. Instead of repeating the same code in multiple places, developers can define functions once and reuse them throughout the codebase. This simplifies maintenance, improves readability, and reduces the chances of introducing bugs.

5. Modularity and Code Organization:

JavaScript functions facilitate code modularity and organization. By breaking down complex tasks into smaller, self-contained functions, developers can enhance code readability, maintainability, and collaboration among team members.

Using Functions in Five: JavaScript & TypeScript Code Editor

Inside Five, developers can create JavaScript or TypeScript functions, using Five's code editor. The code editor comes with helpful features, such as syntax highlighting, autocompletion, or a co-pilot for interpreting and debugging code.


What is Five?

Five is a low-code solution that helps developers rapidly build & deploy online database applications. Five provides pre-built features, such as a fully provisioned MySQL database, authentication, and one-click application deployment—or table, form, and chart wizards. Developers can also create logic by writing JavaScript or TypeScript functions in Five.


To access the code editor, open Five and select one of your applications. Next, click on Manage, then on Logic, and then Code Editor. 

Now click on the Plus icon. Choose a name for your function, as well as the language you'd like to use: JavaScript or TypeScript.

You can now write standard JavaScript or TypeScript to create functions right inside of Five. In this tutorial, we will simply test our function by attaching it to a process and testing if our function will do the desired task whenever the process is completed.

Let's begin by creating a process to which we will attach our function. Start by navigating to processes: click on 'Tasks' and then 'Processes'

Next, create a new process by clicking on the yellow '+' button and giving it a name. Now click on the 'Fields' tab and create a new field called Name and give it a display type of _Text.

After completing our process, let's return to the code editor and create a function.

To begin, we can write a simple log statement to test our function. In Five, you can use console.log() , the same way you would using standard JavaScript / TypeScript. However, for server-side events, we utilize five.log(). Take a look at the snippet below ( we will be using JavaScript to keep things simple )

function logGreeting(five, context, result) {
five.log("Hello");
return five.success(result);
}

You might have noticed that functions within Five have three default arguments: five, context, and result. We've already utilized five for logging, and we passed the result to five.success() to indicate that the function was executed without errors.

Now, let's delve into the context.

In Five, the context variable encompasses all the data associated with the action to which the function is linked. For instance, if we connect our function to the process we made earlier, the context variable will capture whatever input we provide in the Name field.

function logGreeting(five, context, result) {
const name = context.Name
five.log("Hello " + name);
return five.success(result);
}

We've modified our function to extract the value from the 'Name' field within 'context'. We then log this value using five.log(). Finally, we return the outcome using five.success()

Next, let's attach our function to our process. Start by navigating back to 'Processes' inside the 'Task' menu, select the process that we created earlier, and then click on the events tab which will show all the events that a process goes through. Here, attach the function in the 'Do Complete' event

Now let's finally put our process into a menu so that we can access it in our end-user application.

Navigate to 'Visual' and then click on 'Menu', we will create a new menu item, and then in the 'Action' field we will select our process

Finally let's run our application, to test our function we will run it in debug mode and that can be done by simply clicking on the ▶️ with the magnifying glass on the header.

Five will now run your application. But now you'll also have access to the inspector, which you will be able to find minimized on the right. Maximize it by clicking on the 🔎 icon which will cause it to expand.

Now simply put your name in the Name field and then run the process by clicking on the ✔️icon on the top right. You'll see that you have successfully logged your message along with your name in the inspector.

Congratulations you have successfully written and executed your function in Five.


Conclusion

JavaScript and TypeScript functions are fundamental aspects of web development, offering a multitude of advantages. By leveraging functions effectively, developers can streamline their code, enhance maintainability, and enrich the overall user experience. Additionally, well-optimized JavaScript and TypeScript functions are essential for search engine optimization, leading to quicker page loads and better rankings.

If you are a beginner or looking for a language with less strict conventions and a broader community base, JavaScript is the way to go. With its established presence and rich ecosystem.

However, if you aim for better maintainability, scalability, and the benefits of static typing, TypeScript should be your choice. TypeScript empowers developers to catch bugs early, improve code readability, and leverage code intelligence provided by modern IDEs and editors

Through this tutorial, we've explored the foundational concepts of these languages, their unique features, and their application within the Five environment.

By harnessing the capabilities of Five's code editor and the platform's event-driven architecture, developers can seamlessly integrate custom logic into their applications. Whether you're a seasoned developer or just starting out, the combination of JavaScript or TypeScript with Five's robust toolset offers a dynamic and efficient way to build applications. Dive in, experiment, and unlock the full potential of your web development journey with Five.

Top comments (0)