Skip to content

Basic Concepts

The keyword return

The return keyword is essential in JavaScript functions. It indicates the value that the function should return at the end of its execution.

Important

In Wized, you must always include the return keyword at the end of your functions in the Function Editor, even if it returns a boolean value, such as true or false. If you don't include return, your function will return undefined, which may result in errors or unexpected behavior in your application.


Dot Notation

Dot notation is an effective and straightforward method for accessing specific properties within objects and arrays in JavaScript.

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.

For example, if you have a user object with properties like name and email, you can access these properties using dot notation as follows:

javascript
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'

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:

javascript
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 email of the second user
return users[1].email; // Returns 'jane.smith@example.com'

Operators and Expressions

Operators are symbols 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.

JavaScript
// 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

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.

JavaScript
// 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 (>=): Check if cart total meets minimum for discount
let cartTotal = v.cartTotal; // 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 (==): Check if user role matches required role (loose equality)
let userRole = v.userRole; // user role variable
let requiredRole = "admin"; // required role
return isAdmin = userRole == requiredRole; // true if userRole loosely equals requiredRole

// Strict not equal to (!==): Check if API response status differs from success
let responseStatus = r.apiResponse.status; // response status from an API
let successStatus = 200; // success status code
return isError = responseStatus !== successStatus; // true if responseStatus is not equal to successStatus

Logical Operators:

These include && (AND), || (OR), and ! (NOT). They are used to combine or negate boolean expressions.

JavaScript
// AND (&&): Check if user is logged in and has admin role
let isLoggedIn = c.loggedIn; // boolean from cookie indicating login status
let isAdmin = v.role === "admin"; // boolean check for admin role
let canAccess = isLoggedIn && isAdmin; // true if both logged in and role is admin

// 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 = v.backorder; // boolean indicating if backorder is allowed
let canPurchase = inStock || allowBackorder; // true if in stock or backorder allowed

// NOT (!): Negate login status to check if user is not logged in
let loggedIn = c.loggedIn; // boolean indicating login status
let isGuest = !loggedIn; // true if user is not logged in

// Combined example: Check if user is an admin and either logged in or has a valid session
let role = v.role === "admin"; // boolean for admin role
let loggedInStatus = c.loggedIn; // boolean for login status
let validSession = v.session === "valid"; // boolean for valid session status
let access = role && (loggedInStatus || validSession); // true if admin and (logged in OR has a valid session)

Assignment Operators:

These operators allow you to assign a value to a variable or update its existing value:

  • =: Assigns a value to a variable.
  • +=: Adds a value to the current value of the variable.
  • -=: Subtracts a value from the current value of the variable.
  • *=: Multiplies the current value of the variable by a value.
  • /=: Divides the current value of the variable by a value.
  • %=: Calculates the modulus (remainder of division) of the current value of the variable by a value.
JavaScript
let counter = 0;

counter += 1; // Increment the value of "counter" by 1 (it is now equal to 1)

counter *= 2; // Multiply the value of "counter" by 2 (it now equals 2)

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:

JavaScript
if (condition) {

// Code to be executed if the condition is true

} else {

// Code to execute if the condition is false

}

Example

JavaScript
// 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:

JavaScript
condition ? valueIfTrue : valueIfFalse

Example

JavaScript
// 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."
    : "Add more items to your cart to qualify for a discount.";

return message;