Functions | Bondar Academy
Course: JavaScript for Testers
Module: JavaScript Fundamentals
Instructor: Artem Bondar
Lesson Summary
In this lesson, we explore the concept of functions in JavaScript, which allow us to encapsulate reusable logic in our code. Functions help avoid code repetition by enabling us to call the same block of code from various places in our application. Types of Functions Declarative Function: Defined using the function keyword, followed by a name, parentheses, and curly braces. Example: function hello1() { console.log("hello1"); } Anonymous Function: Lacks a name and must be assigned to a variable. Example: const hello2 = function() { console.log("hello2"); }; Arrow Function: A concise syntax introduced in ES6, also an anonymous function. Example: const hello3 = () => { console.log("hello3"); }; Function Parameters and Return Values Functions can accept arguments and return values. For instance, a function that prints a name can be defined as: function printName(name) { console.log(name); } To return a value, use the return keyword: function multiplyByTwo(number) { return number * 2; } Importing Functions Functions can be organized in separate files and imported into other JavaScript files. Use the import keyword to bring functions into your current file: import { printAge } from './helpers/printHelper.js'; Alternatively, you can import all functions from a file: import * as helper from './helpers/printHelper.js'; This lesson provided a foundational understanding of functions in JavaScript, including their types, usage, and how to import them from other files.