Basic concepts
In this guide you will learn what are the basic concepts you need to understand to correctly use the function editor.
Return
keyword
In the Wized Function editor, it is essential to always use the return
keyword. This word indicates the value that a function should return at the end of its execution.
Important
You must always include the return
keyword at the end of your functions. Make sure that you do not duplicate return
in the same function.
returning Numbers example
- Returning numbers
To return a numeric value, you would use:
const number_value = 42;
return number_value; // This will return the number 42
returning strings example
To return a string, you can provide a text value enclosed in quotes:
return 'Hello, World!'; // This will return the string 'Hello, World!'
returning Booleans example
To return a boolean value, you can simply return true
or false
:
const isLoggedIn = true;
return isLoggedIn; // This will return true
let
and const
keywords
You can use let
and const
to define variables in JavaScript. Here’s the difference:
let
: Used to declare variables whose value can change later.javascriptlet counter = 0; counter = 5; // Valid, because "let" allows reassignment
const
: Used to declare variables whose value will not change after being assigned.javascriptconst PI = 3.1416; PI = 3.14; // ❌ Error: Cannot reassign a value to a constant
Dot notation
The dot notation is a method for accessing specific properties within objects and arrays in JavaScript. Reference
How does It work?
Consider your data as a tree structure, where each branch represents a property and each leaf corresponds to a value. Dot notation allows you to "navigate" this tree by specifying the path from the root to the desired leaf.
example accessing an object value
For example, if you have a user object with properties like
name
and email
, you can access these properties using dot notation as follows:
const user = {
name: 'John Doe', // User's name
email: 'john.doe@example.com', // User's email
};
return user.name; // Returns 'John Doe'
return user.email; // Returns 'john.doe@example.com'
example accessing an array object value
Additionally, dot notation is not only used for objects but also for arrays. Here is an example of how to access a value within an array using dot notation:
const users = [
{ name: 'John Doe', email: 'john.doe@example.com' },
{ name: 'Jane Smith', email: 'jane.smith@example.com' },
];
// Accessing the name of the first user
return users[0].name; // Returns 'John Doe'
// Accessing the name of the second user
return users[1].name; // Returns 'Jane Smith'
Operators and expressions
Operators are used to perform calculations and comparisons in your JavaScript code. Below are the principal categories of operators you will encounter:
Arithmetic operators:
These include +
, -
, *
, /
, and %
, which perform addition, subtraction, multiplication, division, and modulus (remainder of division), respectively.
Subtraction example
// Subtraction: Calculate remaining stock
let initialStock = 10; // You can replace this value by any other value such as variables, cookies, request responses, etc.
let soldItems = 5; // fixed number of items sold
return remainingStock = initialStock - soldItems; // subtract sold items from stock
Multiplication example
// Multiplication: Calculate interest on product price
let productPrice = 200; // fixed product price
let interestRate = 3; // You can replace this value by any other value such as variables, cookies, request responses, etc.
return totalWithInterest = productPrice * interestRate; // multiply price by interest rate
Division example
// Subtraction: Calculate remaining stock with variable
let initialStock = v.initialStock; // stock variable
let soldItems = 5; // fixed number of items sold
return remainingStock = initialStock - soldItems; // subtract sold items from stock
// Multiplication: Calculate interest on product price from API response
let productPrice = 200; // fixed product price
let interestRate = r.getInterest.data; // interest rate from an API request response
return totalWithInterest = productPrice * interestRate; // multiply price by interest rate
// Division: Calculate average score from a sum of scores
let sumOfScores = v.totalScores; // total scores variable
let numberOfTests = 4; // fixed number of tests
return averageScore = sumOfScores / numberOfTests; // divide total scores by number of tests
Note
Make sure that if you are going to use variable values, cookies, responses to requests, etc. They must be already created and contain a value with a valid format.
Comparison operators:
These include >
, <
, >=
, <=
, ==
, !=
, ===
, and !==
. They are used to compare values, determining if one is greater than, less than, equal to, or not equal to another.
greater than example
// Greater than (>): Check if total points exceed a threshold
let totalPoints = v.totalPoints; // variable storing total points
let pointsThreshold = 100; // fixed threshold value
return exceedsThreshold = totalPoints > pointsThreshold; // true if totalPoints is greater than pointsThreshold
greater than or equal to example
// Greater than or equal to (>=): Check if cart total meets minimum for discount
let cartTotal = 50; // total value of items in the cart
let minForDiscount = 50; // minimum cart total for discount
return qualifiesForDiscount = cartTotal >= minForDiscount; // true if cartTotal is at least minForDiscount
equal to
In JavaScript, the operators =, ==, and === have different functions:
=
is the assignment operator. It is used to assign a value to a variable.
let x = 5; // x is now 5
==
is the loose equality operator. It compares values but converts types if necessary.
5 == "5"; // true (converts the string to a number before comparing)
===
is the strict equality operator. It compares both values and types, without conversions.
5 === "5"; // false (one is a number, the other is a string)
- example
// Strict equal to (==): Check if API response status differs from success
let responseStatus = r.request_name.status; // response status from an request
let successStatus = 200; // success status code
return isEqual = responseStatus == successStatus; // true if responseStatus is equal to successStatus
Note
Make sure that if you are going to use variable values, cookies, responses to requests, etc. They must be already created and contain a value with a valid format.
Logical operators:
These include &&
(AND), ||
(OR), and !
(NOT). They are used to combine or negate boolean expressions.
&& AND example
// AND (&&): Check if the `get_all_products` request was executed and successful.
let hasRequested = r.get_all_products.hasRequested; // Boolean if the request has already been executed
let successful = r.get_all_products.status === 200; // Boolean result of the validation if the get_all_products" request was successfully executed.
return hasRequested && successful; // true, if hasRequested and successful are true
OR (||) example
// OR (||): Check if product is in stock or if backorder is allowed
let inStock = v.stock > 0; // boolean indicating if stock is available
let allowBackorder = true; // boolean indicating if backorder is allowed
return canPurchase = inStock || allowBackorder; // true if in stock or backorder allowed
NOT (!) example
// NOT (!): Negate login status to check if user is not logged in
let loggedIn = r.login.ok; // boolean indicating login status
let isGuest = !loggedIn; // true if user is not logged in
combined example
// Combined example: Check if user is an admin and either logged in or has a valid session
let role = r.auth_user.data.role === "admin"; // boolean for admin role
let loggedInStatus = r.auth_user.ok; // boolean for login status
let validSession = v.session === "valid"; // boolean for valid session status
return access = role && (loggedInStatus || validSession); // true if admin and (logged in OR has a valid session)
Note
Make sure that if you are going to use variable values, cookies, responses to requests, etc. They must be already created and contain a value with a valid format.
Assignment operators:
These operators (=
,+=
,-=
,*=
,/=
,%=
) allow you to assign a value to a variable or update its existing value:
=
: Assigns a value to a variable.
return counter = 10; //In this example a fixed value `10` was set, however, you can replace it by the value of a cookie, variable, URL parameter, request response, etc.
+=
: Adds a value to the current value of the variable.
let counter = 10; //In this example a fixed value `10` was set, however, you can replace it by the value of a cookie, variable, URL parameter, request response, etc.
return counter +=1;
-=
: Subtracts a value from the current value of the variable.
let counter = 10; //In this example a fixed value `10` was set, however, you can replace it by the value of a cookie, variable, URL parameter, request response, etc.
return counter -=1;
*=
: Multiplies the current value of the variable by a value.
let counter = 10; //In this example a fixed value `10` was set, however, you can replace it by the value of a cookie, variable, URL parameter, request response, etc.
return counter *=1;
/=
: Divides the current value of the variable by a value.
let counter = 10; //In this example a fixed value `10` was set, however, you can replace it by the value of a cookie, variable, URL parameter, request response, etc.
return counter /=1;
%=
: Calculates the modulus (remainder of division)
let counter = 10; //In this example a fixed value `10` was set, however, you can replace it by the value of a cookie, variable, URL parameter, request response, etc.
return counter %=1;
Conditionals (if...else)
Conditionals allow you to execute different blocks of code depending on whether a condition is met or not. The basic structure of an if...else conditional is:
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to execute if the condition is false
}
If-else example
example
// example: Check if the user qualifies for a discount based on cart total
let cartTotal = v.cartTotal; // variable storing the total value in the user's cart
let discountThreshold = 50; // minimum cart total to qualify for a discount
if (cartTotal >= discountThreshold) {
// User qualifies for discount
return "Congratulations! You qualify for a discount.";
} else {
// User does not qualify for discount
return "Add more items to your cart to qualify for a discount.";
}
Ternary operators
The ternary operator is a shorthand way of writing a simple conditional on a single line. Its structure is:
condition ? valueIfTrue : valueIfFalse
Ternary Operators example
// example: Check if the user qualifies for a discount using a ternary operator
let cartTotal = v.cartTotal; // variable storing the total value in the user's cart
let discountThreshold = 50; // minimum cart total to qualify for a discount
// Ternary operator for discount qualification
let message = cartTotal >= discountThreshold
? "Congratulations! You qualify for a discount." // value if true
: "Add more items to your cart to qualify for a discount."; // value if false
return message;