Beyond ABAPdesigned by@Tejoram97
Beyond ABAP / SAPUI5 / JavaScript, jQuery & Node.js

JavaScript, jQuery & Node.js

SAPUI5 · SAP Fiori UI5 and Mobile ·

Open the interactive lesson →
  1. What JavaScript is and how a page loads it
  2. Single-threaded with an event loop
  3. Syntax rules, naming and strict mode
  4. Variables, scope and hoisting
  5. Data types, operators and equality
  6. Control flow and error handling
  7. Functions
  8. The this keyword
  9. Objects, arrays, destructuring and JSON
  10. Array methods (map, filter, reduce …)
  11. The DOM, output and events
  12. Asynchronous JavaScript: callbacks, promises, async/await, fetch
  13. Modules: ES modules, CommonJS and sap.ui.define
  14. Debugging in the browser DevTools
  15. jQuery
  16. Node.js, npm and the UI5 Tooling
  17. Interview questions

SAPUI5 is a JavaScript framework, so every controller, formatter and helper you write is JavaScript. This page covers the language as a UI5 developer needs it – variables, functions, this, objects, arrays, promises, modules and debugging – then jQuery (legacy in UI5) and Node.js, the runtime behind the UI5 Tooling, SAP Fiori tools and CAP. HTML and CSS are on SAPUI5 › 01 · HTML5 & CSS3.

Part 1 – What JavaScript is and how a page loads it

JavaScript (JS) is the programming language of the web. HTML gives structure, CSS gives the look, JavaScript gives behaviour. The language standard is ECMAScript (ES2015 = "ES6" brought let/const, classes, arrow functions, promises and modules; since then a new edition comes every year). Java and JavaScript are unrelated languages with different design, purpose and usage.

  • What JS does in the browser: validate input, show output and messages, change HTML and CSS at runtime (the DOM), react to events, call servers (AJAX) and run business and processing logic on the client.
  • Engines compile JS just in time: V8 (Chrome, Edge, Node.js), SpiderMonkey (Firefox), JavaScriptCore (Safari).

Client-side JavaScript

Server-side JavaScript

Runs in

The browser

A server runtime – Node.js

Typical work

UI logic, validation, DOM, calling OData services

Read the database, business logic, send mail, call external APIs, serve OData

SAP example

SAPUI5 / Fiori apps

SAP CAP services, UI5 Tooling dev server

Test it

Browser console (F12 › Console)

node in a terminal

Three ways to include JavaScript

<!-- 1. Inline: code in an event attribute – avoid -->
<button onclick="alert('Saved')">Save</button>

<!-- 2. Internal: <script> block in the page -->
<script>
function greet(sName) {
return "Hello " + sName;
}
</script>

<!-- 3. External: separate .js file – the normal way -->
<script src="js/app.js" defer></script>
<script type="module" src="js/main.js"></script>

Way

Reuse

Notes

Inline

None – bound to one element

Mixes logic into HTML; blocked by a Content Security Policy (CSP). Use addEventListener instead

Internal

Within the page

Code inside functions in a <script> block

External

Whole app, cached

.js file loaded with <script src>; defer / type="module" run it after the HTML is parsed

  • UI5 apps are CSP-compliant: no inline scripts or handlers. Events are attached in XML views (press=".onSave"), and the code lives in modules (Part 13).

Part 2 – Single-threaded with an event loop

JavaScript runs your code on one thread, one statement after the other – it is synchronous by default. It still stays responsive because slow work (timers, HTTP calls, file access) is handed to the runtime (browser Web APIs or Node.js), which does the waiting outside the JS thread. When the work is done, a callback is put into a queue, and the event loop runs it as soon as the call stack is empty. This gives non-blocking I/O and concurrency, not parallelism.

  • Synchronous call: the caller waits until the answer comes back – the UI is blocked.
  • Asynchronous call: the caller continues at once; the result arrives later through a callback function or a promise (Part 12).
Event loop with call stack, Web APIs, microtask queue and task queue
  • Microtasks (promise .then, code after await) all run before the next task (timer, click, network event). That is why setTimeout(fn, 0) runs after already-resolved promises.
  • A long synchronous loop freezes the page (no clicks, no repaint). Heavy computing belongs on the server or in a Web Worker (true parallel thread; worker_threads in Node.js).
  • Old UI5 code used synchronous XHR to load modules and data – it blocks the UI and is deprecated. Modern UI5 loads everything asynchronously (data-sap-ui-async="true").

Part 3 – Syntax rules, naming and strict mode

Naming conventions

Convention

Used for

Example

camelCase

Variables and functions

orderTotal, loadOrders()

PascalCase

Classes and constructors; UI5 modules

Controller, JSONModel

UPPER_SNAKE_CASE

Real constants

MAX_ITEMS

Leading _

Private members (convention only)

_onRouteMatched

UI5 code adds a type prefix (Hungarian notation) to variable names:

Prefix

Type

Example

s

string

sName

i / f

integer / float

iCount, fPrice

b

boolean

bVisible

o

object

oView, oModel, oEvent

a

array

aItems

m

map (object used as key/value store)

mParameters

fn

function

fnCallback

$

jQuery object (legacy)

$Element

Keywords

Group

Keywords

Declarations

var, let, const, function, class, extends, import, export

Control flow

if, else, switch, case, default, for, while, do, break, continue, return

Errors

try, catch, finally, throw

Objects and types

new, this, super, typeof, instanceof, in, of, delete

Async and generators

async, await, yield

Literal values

true, false, null (and the global undefined)

Strict mode

"use strict";  // first line of a script or function

total = 10;    // ReferenceError: total is not defined (no implicit global)
  • Strict mode turns silent mistakes into errors: no undeclared variables, this is undefined in plain function calls, no duplicate parameter names.
  • ES modules and classes are always strict. UI5 files usually start the sap.ui.define factory with "use strict";.

Part 4 – Variables, scope and hoisting

const fTaxRate = 0.19;  // cannot be re-assigned
let iCount = 0;         // can be re-assigned
iCount = iCount + 1;

const aItems = [];      // const = the binding is fixed ...
aItems.push("A");       // ... the array content can still change

var sOld = "legacy";    // function-scoped, avoid in new code
  • Rule of thumb: const by default, let when the value must change, never var in new code. var appears in older UI5 samples (var that = this;).

Scope

Scope decides where a variable can be used. JavaScript uses lexical scope: what counts is where the code is written, and lookup goes from the inside outwards.

Scope

Created by

Contains

Global

Top level of a classic script

var / function declarations at top level become properties of window (globalThis). Avoid globals

Module

Each ES module file (and each sap.ui.define factory function)

Top-level variables of that file only

Function

Every function

Parameters, var, let, const declared in it

Block

Every { } – if, for, while, plain blocks

Only let, const and class – var ignores blocks

for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i));  // 3, 3, 3 – one shared i (function scope)
}
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log(j));  // 0, 1, 2 – a new j for every iteration
}

Hoisting and the Temporal Dead Zone

Before a scope runs, the engine registers all declarations in it – this is called hoisting ("declarations move to the top" is only a mental picture). What you can do before the declaration line depends on the kind of declaration:

console.log(sA);  // undefined – var is hoisted and set to undefined
var sA = "A";

console.log(sB);  // ReferenceError – sB is in the Temporal Dead Zone
let sB = "B";

sayHi();          // works – function declarations are fully hoisted
function sayHi() { console.log("Hi"); }

sayBye();         // TypeError – only the var is hoisted, not the function
var sayBye = function () { console.log("Bye"); };
Nested scopes and var, let, const comparison with the Temporal Dead Zone
  • let, const and class are hoisted to the top of their block but not initialised: from the start of the block to the declaration line they are in the Temporal Dead Zone (TDZ), and any access throws a ReferenceError.
  • Strict mode does not stop hoisting; it stops accidental globals. Best practice: declare variables at the top of their scope, before use.

Part 5 – Data types, operators and equality

Type

Example

typeof result

string

"Order", 'A', template literal

"string"

number (integer and decimal, 64-bit float)

42, 3.14, NaN, Infinity

"number"

bigint (very large integers)

9007199254740993n

"bigint"

boolean

true, false

"boolean"

undefined – declared but no value

let x;

"undefined"

null – intentionally empty

null

"object" (a historic bug)

symbol – unique key

Symbol("id")

"symbol"

object (incl. arrays, dates, functions)

{ id: 1 }, [1, 2], new Date()

"object"; functions give "function"

  • The first seven are primitives (immutable values, copied by value); everything else is an object (copied by reference).
  • typeof [] === "object" – use Array.isArray(a) to test for arrays.
  • Decimal numbers are binary floats: 0.1 + 0.2 is 0.30000000000000004. Amounts from OData (Edm.Decimal) arrive as strings – format them with UI5 types instead of calculating with floats.
  • Literals are fixed values written in code: numbers, strings, true/false, null, template literals, object {…} and array […] literals, regular expressions /^\d+$/, BigInt 10n.
const sName = "Anna";
const iQty = 3;
const sMsg = `Hello ${sName}, you ordered ${iQty * 2} items`;   // template literal

Operators

Group

Operators

Notes

Arithmetic

+ - * / % **, ++ --

** = power; *, /, % bind tighter than + and -; + also joins strings ("1" + 2 = "12")

Assignment

= += -= *= /=, ??=, ||=

= assigns a value

Comparison

=== !== < > <= >=, == !=

Always use === / !==

Logical

&&, ||, !

Return one of the operands: sName || "Unknown"

Nullish coalescing

??

Default only for null/undefined: iQty ?? 1 keeps 0

Optional chaining

?.

oOrder?.customer?.name – undefined instead of an error

Conditional (ternary)

cond ? a : b

bOk ? "Success" : "Error"

Spread / rest

...

Copy or collect elements (Part 9)

Type

typeof, instanceof

oCtrl instanceof Controller

== vs ===

Expression

== (loose, converts types)

=== (strict, no conversion)

1 vs "1"

true

false

0 vs ""

true

false

0 vs false

true

false

null vs undefined

true

false

NaN vs NaN

false

false – use Number.isNaN()

  • Falsy values: false, 0, -0, 0n, "", null, undefined, NaN. Everything else is truthy – including "0", [] and {}.

Part 6 – Control flow and error handling

if (iQty > 100) {
sLevel = "large";
} else if (iQty > 10) {
sLevel = "medium";
} else {
sLevel = "small";
}

switch (sStatus) {
case "A": sText = "Approved"; break;
case "R": sText = "Rejected"; break;
default:  sText = "Open";
}

for (let i = 0; i < aItems.length; i++) { /* index loop        */ }
for (const oItem of aItems) { /* values of an array, string, Map */ }
for (const sKey in oOrder) { /* property names of an object      */ }
while (bMore) { /* … */ }
function parseQuantity(sValue) {
const iQty = Number(sValue);
if (!Number.isInteger(iQty) || iQty <= 0) {
throw new Error(`Invalid quantity: ${sValue}`);
}
return iQty;
}

try {
parseQuantity("abc");
} catch (oError) {
console.error(oError.message);   // Invalid quantity: abc
} finally {
console.log("always runs");
}
  • break leaves a loop or switch; continue jumps to the next iteration.
  • throw any value, but prefer new Error("…") (has message and a stack trace). finally runs whether or not an error happened.

Part 7 – Functions

A function is a reusable block of code. It takes parameters, and return stops it and hands a value back to the caller (without return the result is undefined).

// 1. Function declaration – hoisted, can be called before this line
function multiply(a, b) {
return a * b;
}
const iResult = multiply(4, 3);  // 12

// 2. Function expression – anonymous function stored in a variable
const divide = function (a, b) {
return a / b;
};

// 3. Arrow function – short syntax
const square = (x) => x * x;              // one expression: implicit return
const add = (a, b) => {                   // block body: needs return
return a + b;
};
const makeItem = (sId) => ({ id: sId });  // object literal in ( )

// 4. Default and rest parameters
function formatPrice(fValue, sCurrency = "EUR") {
return `${fValue.toFixed(2)} ${sCurrency}`;
}
function sum(...aNumbers) {  // collects all arguments into an array
return aNumbers.reduce((iSum, i) => iSum + i, 0);
}
formatPrice(9.5);            // "9.50 EUR"
sum(1, 2, 3);                // 6

Kind

Hoisted?

Own this?

Typical use

Declaration function f() {}

Yes, fully

Yes (depends on the call)

Named helper functions

Expression const f = function () {}

No (variable only)

Yes

Functions as values, callbacks

Arrow const f = () => {}

No

No – uses the outer this

Callbacks inside methods, short helpers

Method { onPress() {} }

–

Yes – the object

Controller methods, object methods

  • An anonymous function (a, b) {} alone as a statement is a syntax error: anonymous functions are always used as expressions – assigned, passed as callbacks or called immediately.
  • Arrow functions have no own this and no arguments, and cannot be called with new. Do not use them as object or controller methods that need this; do use them for callbacks inside methods.
  • Other forms: class methods and constructors, async function (Part 12), generator function*.

Callbacks, closures and IIFE

// Callback: a function passed to another function and called by it later
setTimeout(() => console.log("1 second later"), 1000);
aItems.forEach((oItem) => console.log(oItem.name));

// Closure: an inner function keeps access to the outer variables
function createCounter() {
let iCount = 0;
return () => ++iCount;
}
const next = createCounter();
next();  // 1
next();  // 2 – iCount lives on in the closure

// IIFE: immediately invoked function expression (old way to get a private scope)
(function () {
const sPrivate = "not global";
})();
  • Every sap.ui.define factory function is a closure over its module; formatters and event handlers close over controller variables.

Part 8 – The this keyword

this is decided by how a function is called, not where it is written – except in arrow functions, which take this from the surrounding code.

How the function is called

this is

As a method: oOrder.getTotal()

The object before the dot (oOrder)

Plain call getTotal() – sloppy (non-strict) code

The global object (window)

Plain call getTotal() – strict code, ES modules, classes

undefined

Top level of a classic script / of an ES module

window / undefined

With new: new Order() or a class constructor

The new instance

Arrow function

The this of the enclosing scope (lexical)

DOM event handler (addEventListener with a normal function)

The element the handler is attached to

f.call(o, a, b), f.apply(o, [a, b]), f.bind(o)

o – set explicitly (bind returns a new function)

UI5 event handler from an XML view (press=".onPress")

The controller

  • globalThis is the standard name for the global object in every environment (browser and Node.js).
sap.ui.define(["sap/ui/core/mvc/Controller", "sap/m/MessageToast"],
(Controller, MessageToast) => {
"use strict";
return Controller.extend("my.orders.controller.Main", {
onRefresh() {
// Arrow callback: "this" is still the controller
this.loadOrders().then(() => {
this.getView().setBusy(false);
MessageToast.show("Orders refreshed");
});
},
onRefreshOld() {
const that = this;              // legacy pattern before arrow functions
this.loadOrders().then(function () {
that.getView().setBusy(false);
});
}
});
});
  • Old code used var that = this; or .bind(this); arrow functions make both unnecessary. Note that the controller methods themselves are normal methods (onRefresh() {}), not arrows.

Part 9 – Objects, arrays, destructuring and JSON

Kind of value

Holds

ABAP analogy

Primitive (scalar)

One value: const iId = 10;

Elementary variable

Object

Named properties of any type

Structure

Array

Ordered list of items, index from 0, any types mixed

Standard table of values

Array of objects

List of records [{…}, {…}]

Internal table – the shape OData and JSON models use

const oEmployee = {
id: 10,
name: "Anna",
salary: 900,
currency: "EUR",
address: { city: "Berlin" },  // nested object
getLabel() {                  // method
return `${this.name} (${this.id})`;
}
};
oEmployee.name;                 // "Anna" – dot notation
oEmployee["currency"];          // "EUR"  – bracket notation (dynamic keys)
oEmployee.salary = 950;         // change
delete oEmployee.address;       // remove a property

const aEmployees = [oEmployee, { id: 11, name: "Ben", salary: 800, currency: "EUR" }];
aEmployees.length;              // 2
aEmployees[1].name;             // "Ben"
aEmployees.at(-1);              // last item
  • Object.keys(o), Object.values(o), Object.entries(o) list properties; "id" in o checks one.
  • Objects and arrays are references: const oCopy = oEmployee; points to the same object. Copy with spread (shallow) or structuredClone(o) (deep).

Destructuring and spread

const { name, salary = 0 } = oEmployee;           // object destructuring with default
const [oFirst, ...aRest] = aEmployees;            // array destructuring + rest

const oUpdated = { ...oEmployee, salary: 1000 };  // copy and override (shallow)
const aAll = [...aEmployees, oNewEmployee];       // copy and append

function showEmployee({ name, id }) {             // destructure parameters
return `${id}: ${name}`;
}

Classes

class Order {
constructor(sId) {
this.id = sId;
this.items = [];
}
addItem(oItem) {
this.items.push(oItem);
return this;                        // allows method chaining
}
}
class RushOrder extends Order {
constructor(sId) {
super(sId);                         // call the parent constructor first
this.priority = "high";
}
}
new RushOrder("4711").addItem({ product: "A" }).addItem({ product: "B" });
  • Classes are syntax on top of JavaScript's prototypes. Classic UI5 uses its own inheritance: Controller.extend("my.Ctrl", { … }), BaseObject.extend(…); UI5 with TypeScript uses real classes.

JSON

JSON (JavaScript Object Notation) is a text format for data exchange, based on JS literal syntax but stricter. OData services, manifest.json, package.json and JSONModel all use it.

{
"employees": [
{ "id": 10, "name": "Anna", "salary": 900, "currency": "EUR", "active": true },
{ "id": 11, "name": "Ben",  "salary": 800, "currency": "EUR", "manager": null }
]
}

JSON rule

JS object literal allows

Keys must be in double quotes: "name"

Unquoted keys: name: "Anna"

Strings only in double quotes

Single quotes and template literals

Values: string, number, true/false, null, object, array

Also undefined, functions, dates, NaN

No comments, no trailing commas

Comments and trailing commas

const sText = JSON.stringify(oEmployee);  // object -> JSON string (methods are dropped)
const oBack = JSON.parse(sText);          // JSON string -> object (error if invalid)
  • In UI5: new JSONModel({ employees: aEmployees }) and bind {/employees} – see SAPUI5 › 04 · Data, Binding & Navigation.

Part 10 – Array methods (map, filter, reduce …)

const aItems = [
{ name: "Pen",   price: 2,   qty: 10 },
{ name: "Lamp",  price: 25,  qty: 1 },
{ name: "Chair", price: 120, qty: 2 }
];
const aNames  = aItems.map((o) => o.name);                        // ["Pen", "Lamp", "Chair"]
const aCheap  = aItems.filter((o) => o.price < 30);               // Pen and Lamp
const fTotal  = aItems.reduce((f, o) => f + o.price * o.qty, 0);  // 285
const oLamp   = aItems.find((o) => o.name === "Lamp");            // the Lamp object
const bAnyBig = aItems.some((o) => o.price > 100);                // true
const bAllOk  = aItems.every((o) => o.qty > 0);                   // true
const sList   = aItems                                            // "Pen, Chair"
.filter((o) => o.qty > 1)                                       // method chaining
.map((o) => o.name)
.join(", ");

Group

Methods

Change the array (mutating)

push() / pop() (end), unshift() / shift() (start), splice() (remove/insert anywhere), sort(), reverse(), fill(), copyWithin()

Return a new array

map(), filter(), slice(), concat(), flat(), flatMap(), toSorted(), toReversed(), toSpliced(), with(i, v) (copy with one element replaced)

Search

find(), findIndex(), findLast(), findLastIndex(), indexOf(), lastIndexOf(), includes(), at() (negative index from the end)

Test and aggregate

some(), every(), reduce(), reduceRight()

Loop and convert

forEach() (no return value), join(), toString(), entries(), keys(), values()

Static

Array.isArray(), Array.from() (from an iterable or array-like, e.g. a NodeList), Array.of()

Property

length

  • sort() sorts in place and compares as strings by default: [10, 9, 1].sort() gives [1, 10, 9]. Pass a compare function: aNums.sort((a, b) => a - b); for text use a.localeCompare(b). toSorted() returns a sorted copy.
  • Useful string methods: includes, startsWith, endsWith, split, trim, padStart, replaceAll, toUpperCase, slice.

Part 11 – The DOM, output and events

The browser gives JavaScript two main objects: window – the browser window and global object (location, history, localStorage, setTimeout, alert) – and document (window.document) – the DOM of the page (SAPUI5 › 01, Part 2).

const oTitle  = document.getElementById("title");         // one element by id
const aCards  = document.getElementsByClassName("card");  // live HTMLCollection
const aRadios = document.getElementsByName("payment");    // by name attribute
const oFirst  = document.querySelector(".card.active");   // first match, any CSS selector
const aAll    = document.querySelectorAll("ul > li");     // static NodeList of all matches

oTitle.textContent = "Orders";                            // set text (safe)
oTitle.classList.add("highlight");                        // add a CSS class
oTitle.style.color = "navy";                              // inline style
oTitle.dataset.orderId;                                   // reads data-order-id

const oLi = document.createElement("li");
oLi.textContent = "New order";
document.querySelector("ul").append(oLi);

Output

Way

Use

element.textContent = …

Write text into an element – safe

element.innerHTML = …

Write HTML – never with user input (XSS risk: injected scripts)

console.log(), console.error(), console.table()

Debug output in DevTools › Console

window.alert()

Blocking message box – only for quick tests

document.write()

Obsolete – overwrites the page, do not use

Events

const oButton = document.querySelector("#save");

oButton.addEventListener("click", (oEvent) => {
oEvent.preventDefault();     // stop the default action (e.g. form submit)
console.log(oEvent.target);  // element that was clicked
});

// Event delegation: one listener on the parent handles all children
document.querySelector("ul").addEventListener("click", (oEvent) => {
const oLi = oEvent.target.closest("li");
if (oLi) {
console.log("clicked", oLi.textContent);
}
});
  • Common events: click, dblclick, input, change, submit, keydown, focus, blur, mouseover, load, DOMContentLoaded.
  • Events bubble from the target up to document; stopPropagation() stops that. Listeners can also run in the capturing phase (top-down) with { capture: true }.

Plain DOM

SAPUI5

document.getElementById("x")

this.byId("x") in the controller – returns the control, not the DOM element

addEventListener("click", fn)

press=".onPress" in the XML view, or oButton.attachPress(fn, this)

event.target, input.value

oEvent.getSource(), oEvent.getParameter("value")

element.textContent = …

Data binding text="{/title}" or oText.setText(…)

alert(), console.log()

MessageToast.show(), MessageBox.error(), sap/base/Log

  • UI5 apps should not change the DOM directly – the next re-rendering would overwrite it. Use control APIs, binding and models. oControl.getDomRef() exists for rare cases (custom controls).

Part 12 – Asynchronous JavaScript: callbacks, promises, async/await, fetch

Callbacks

A callback is a function passed as an argument to another function, which calls it later – for example when a timer ends or data arrives. Nested callbacks quickly become unreadable ("callback hell"), which is why promises were introduced.

// OData V2 model in UI5 – callback style
oModel.read("/OrderSet", {
success: (oData) => this.showOrders(oData.results),
error:   (oError) => this.showError(oError)
});

Promises

A Promise is an object that stands for the future result of an asynchronous operation. The producing code (which takes time) creates it and later resolves or rejects it; the consuming code registers what should happen with the result.

Promise states pending, fulfilled, rejected, and consuming with then/catch or await

State

Meaning

pending

Initial state – still running

fulfilled

Completed successfully – has a value (resolve(value) was called)

rejected

Failed – has a reason, usually an Error (reject(error) was called or an error was thrown)

settled

Fulfilled or rejected – final, never changes again

// Producing code: wrap a callback API in a promise
function wait(iMs) {
return new Promise((resolve) => setTimeout(resolve, iMs));
}
function checkStock(sProduct) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (sProduct) {
resolve({ product: sProduct, stock: 12 });
} else {
reject(new Error("No product given"));
}
}, 500);
});
}

// Consuming code: each then() returns a new promise -> chaining
checkStock("Pen")
.then((oResult) => oResult.stock)
.then((iStock) => console.log("Stock:", iStock))
.catch((oError) => console.error(oError.message))  // catches errors of the whole chain
.finally(() => console.log("done"));

Method

Result

p.then(onFulfilled, onRejected)

Runs on success (second function optional, runs on failure); returns a new promise

p.catch(onRejected)

Runs on failure anywhere earlier in the chain

p.finally(fn)

Runs in both cases (hide the busy indicator)

Promise.all([p1, p2])

Fulfils with all values when all fulfil; rejects as soon as one rejects

Promise.allSettled([…])

Waits until all are settled; gives the status and value/reason of each

Promise.any([…])

Fulfils with the first fulfilled one; rejects only if all reject

Promise.race([…])

Settles like the first one to settle (e.g. timeout races)

Promise.resolve(v) / Promise.reject(e)

An already fulfilled / rejected promise

async / await

async and await make promise code read like synchronous code. An async function always returns a promise; await pauses that function (not the whole page) until a promise settles and returns its value – or throws its error.

async function getGreeting() {
return "Hello";                       // wrapped in Promise.resolve("Hello")
}
getGreeting().then((sText) => console.log(sText));

async function showStock() {
try {
const oResult = await checkStock("Pen");  // waits without blocking the UI
console.log(oResult.stock);
} catch (oError) {
console.error(oError.message);            // rejected promise -> exception
}
}

async function loadAll() {
// Start both requests at once, then wait for both (parallel, not one after the other)
const [aOrders, aCustomers] = await Promise.all([loadOrders(), loadCustomers()]);
return { aOrders, aCustomers };
}
  • await works inside async functions and at the top level of ES modules.
  • Two awaits in a row run one after the other; use Promise.all when the calls are independent.
  • Promises in UI5: Fragment.load() and this.loadFragment(), sap.ui.require wrapped in a promise, OData V4 oContext.requestObject(), oModel.submitBatch(), oBinding.create(…).created().

fetch and AJAX

AJAX (Asynchronous JavaScript and XML) means calling the server from JavaScript without reloading the page – today mostly with JSON. The modern API is fetch(), which returns a promise; the older API is XMLHttpRequest.

async function loadBooks() {
const oResponse = await fetch("/odata/v4/catalog/Books?$top=10", {
headers: { Accept: "application/json" }
});
if (!oResponse.ok) {                   // fetch only rejects on network errors,
throw new Error(`HTTP ${oResponse.status}`); // so check the HTTP status yourself
}
const oData = await oResponse.json();  // parse the JSON body
return oData.value;                    // OData V4 puts the rows in "value"
}

await fetch("/api/orders", {             // POST with a JSON body
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ customer: "Acme", qty: 3 })
});
  • In UI5 you rarely call fetch yourself: ODataModel (V2/V4) handles URLs, $batch, CSRF tokens and errors, and JSONModel.loadData(url) loads JSON files. jQuery.ajax is legacy.

Part 13 – Modules: ES modules, CommonJS and sap.ui.define

A module is one file with its own scope that exports what others may use and imports what it needs. Three module systems matter for a UI5 developer:

// ES modules (standard) – formatter.js
export function formatAmount(fValue) {
return fValue.toFixed(2);
}
export default { formatAmount };

// main.js – loaded with <script type="module" src="main.js">
import { formatAmount } from "./formatter.js";
// CommonJS (classic Node.js) – math.js
module.exports = { add: (a, b) => a + b };

// app.js
const { add } = require("./math");
// UI5 module definition – webapp/model/formatter.js
sap.ui.define([
"sap/ui/core/format/NumberFormat"  // dependencies: UI5 module paths, no ".js"
], (NumberFormat) => {               // factory: receives them in the same order
"use strict";
const oFormat = NumberFormat.getFloatInstance({ maxFractionDigits: 2 });
return {                           // the return value is the module's export
amount(fValue) {
return oFormat.format(fValue);
}
};
});

// Load a module later, only when it is needed (lazy loading)
sap.ui.require(["sap/m/MessageBox"], (MessageBox) => {
MessageBox.information("Loaded on demand");
});

ES modules

CommonJS

UI5 modules

Define

export

module.exports

sap.ui.define([deps], factory)

Use

import … from

require()

dependency list / sap.ui.require([…], cb)

Loading

Asynchronous

Synchronous

Asynchronous (AMD-like)

Where

Browsers, modern Node.js ("type": "module")

Node.js

SAPUI5 / OpenUI5 apps

  • Module names are paths relative to a namespace: my/orders/model/formatter maps to webapp/model/formatter.js through the resource roots.
  • Legacy: jQuery.sap.declare / jQuery.sap.require and access through globals such as sap.m.MessageBox.show() are replaced by sap.ui.define / sap.ui.require. With the UI5 Tooling you can also write ES classes or TypeScript, which is transpiled into sap.ui.define modules.
Legacy synchronous loading with jQuery.sap.require and globals versus modern asynchronous sap.ui.define modules, the preload bundle and the UI5 linter
  • Never load synchronously: jQuery.sap.require and sap.ui.requireSync fetch the file with a synchronous request that freezes the browser. They are deprecated and removed in UI5 2.x. Declare the dependency in sap.ui.define, or load it later with the asynchronous sap.ui.require([...], callback).
  • sap.ui.require("sap/m/MessageBox") with a single string (no array) loads nothing: it only returns the module if it is already loaded, otherwise undefined. Use it to probe, never to load.
  • The old synchronous factories have promise-based successors: XMLView.create, Fragment.load / loadFragment, Component.create, Lib.load. Full list → see SAPUI5 › 03 · SAPUI5 Fundamentals, Part 10.

Part 14 – Debugging in the browser DevTools

Action

ABAP debugger

Chrome / Edge DevTools

Step into (go into the called function)

F5

F11

Step over (run the line, stay here)

F6

F10

Step out / return to the caller

F7

Shift+F11

Continue to the next breakpoint

F8

F8

UI5-specific tools

Tool

What it does

URL parameter sap-ui-debug=true

Loads the non-minified (readable) UI5 sources – slower, for debugging only

Ctrl+Alt+Shift+P

Technical Information dialog: UI5 version, loaded libraries, debug sources, starts the Support Assistant

Ctrl+Alt+Shift+S

Diagnostics window: control tree, properties, bindings

UI5 Inspector (browser extension)

Control tree, properties and bindings of the selected control

Support Assistant

Checks the app against best-practice rules (performance, deprecated APIs, accessibility)

sap/base/Log

UI5 logging API (Log.error("…")) instead of console.log in app code

  • Static checks before running: ESLint, and the UI5 linter (@ui5/linter) for deprecated APIs and global access.

Part 15 – jQuery

jQuery is a small open-source JavaScript library ("write less, do more") that wraps common multi-line tasks – finding elements, changing them, events, animations and AJAX – into one-line methods. It was created when browsers behaved very differently. Today the same is possible with native APIs (querySelector, classList, fetch), and new projects rarely add jQuery. You load it from a local file or a CDN.

  • Features: HTML/DOM manipulation, CSS manipulation, event methods, effects and animations, AJAX, utilities.

Syntax and selectors

Basic syntax: $(selector).action() – $ accesses jQuery, (selector) finds elements with CSS selector syntax (plus some jQuery-only selectors), action() does something with all of them.

$(function () {                                    // run when the DOM is ready
$("p").hide();                                   // element selector: all <p>
$(".intro").addClass("highlight");               // class selector
$("#firstName").val("Anna");                     // id selector, set an input value
$("input[type=text]").css("color", "navy");      // attribute selector

$("#save").on("click", function () {             // event handler
$(this).text("Saved").prop("disabled", true);  // chaining
});

$.ajax({ url: "/api/orders", method: "GET", dataType: "json" })
.done((aOrders) => console.log(aOrders))
.fail((oXhr) => console.error(oXhr.status));
});

jQuery

Native JavaScript

$("#x")

document.getElementById("x")

$(".card")

document.querySelectorAll(".card")

.text(), .html(), .val()

textContent, innerHTML, value

.addClass(), .removeClass(), .toggleClass()

classList.add(), .remove(), .toggle()

.attr(), .css()

getAttribute() / setAttribute(), style

.append(), .remove()

append(), remove()

.on("click", fn), .off()

addEventListener(), removeEventListener()

.find(), .parent(), .children(), .each()

querySelectorAll(), parentElement, children, forEach()

.hide(), .show(), .fadeIn(), .slideToggle()

hidden / CSS classes and transitions

$.ajax(), $.getJSON()

fetch()

jQuery and UI5

  • SAPUI5 historically shipped with jQuery and its core used it internally; old apps used the jQuery.sap.* helpers (jQuery.sap.require, jQuery.sap.log, jQuery.sap.delayedCall …).
  • Legacy: the jQuery.sap.* APIs are deprecated since UI5 1.58 and removed in UI5 2.x. Replacements live in sap/base/* (e.g. sap/base/Log, sap/base/util/deepClone), sap/ui/dom/* and sap/ui/util/*.
  • Modern UI5 code does not use jQuery – the global jQuery is not a public API for apps, and the UI5 linter reports its use. Old code such as oControl.$() (jQuery-wrapped DOM) becomes getDomRef().

Part 16 – Node.js, npm and the UI5 Tooling

Node.js is a JavaScript runtime environment – not a framework. It takes Chrome's V8 engine out of the browser and adds an event loop with non-blocking I/O and APIs for files, network and processes, so JavaScript can run on servers and developer machines. It can check user input, validate data, send e-mail, look up databases, run business logic and call external APIs. Frameworks run on Node.js: Express, and SAP CAP (@sap/cds).

Node.js runtime, npm, project files and the SAP tools built on them
  • Install the LTS (long-term support) version – up to Node.js 26 even major numbers become LTS and odd ones are short-lived; from Node.js 27 every major becomes LTS. Check the version each tool requires (engines in its package.json).
  • Node.js includes npm, the package manager. Check both with node -v and npm -v.

npm basics

Command

Effect

npm init -y

Creates a package.json with default values

npm install (npm i)

Installs everything listed in package.json into node_modules/

npm install <pkg>

Adds a runtime dependency (dependencies)

npm install -D <pkg>

Adds a development-only tool (devDependencies), e.g. @ui5/cli

npm install -g <pkg>

Installs a command globally (prefer local devDependencies + scripts)

npm ci

Clean, exact install from package-lock.json (build servers)

npm run <script> / npm start

Runs a script defined in package.json

npx <command>

Runs a package's command without installing it globally

npm outdated, npm update

Shows / installs newer allowed versions

{
"name": "my-orders",
"version": "1.0.0",
"private": true,
"scripts": {
"start": "ui5 serve --open index.html",
"build": "ui5 build --clean-dest",
"lint": "ui5lint"
},
"devDependencies": {
"@ui5/cli": "^4.0.0",
"@ui5/linter": "^1.0.0"
}
}
  • Version ranges (semantic versioning MAJOR.MINOR.PATCH): ^4.0.0 allows 4.x.x, ~4.0.0 allows 4.0.x, 4.0.0 exactly that version.
  • Commit package.json and package-lock.json (exact versions for everyone); never commit node_modules/ – list it in .gitignore.
  • "type": "module" in package.json makes .js files ES modules; otherwise Node.js treats them as CommonJS.
// server.js – minimal HTTP server with only Node.js built-ins
const http = require("node:http");

http.createServer((oReq, oRes) => {
oRes.writeHead(200, { "Content-Type": "application/json" });
oRes.end(JSON.stringify({ message: "Hello from Node.js" }));
}).listen(3000, () => console.log("http://localhost:3000"));

UI5 Tooling

The UI5 Tooling (@ui5/cli) is the official Node.js-based command-line tool for UI5 projects: a local development server, the production build (bundling Component-preload.js, minifying) and project configuration in ui5.yaml.

# ui5.yaml
specVersion: "4.0"
metadata:
name: my.orders
type: application
framework:
name: SAPUI5        # or OpenUI5
version: "1.120.0"  # a maintained UI5 version
libraries:
- name: sap.m
- name: sap.ui.core
- name: themelib_sap_horizon

Command

Effect

ui5 init

Creates a ui5.yaml for an existing project

ui5 use SAPUI5@<version>

Sets the framework and version

ui5 add sap.m sap.f

Adds UI5 libraries to ui5.yaml

ui5 serve

Starts the local development server (default port 8080)

ui5 build

Builds the app into dist/ for deployment

  • Extensions (custom middleware) add live reload or proxies to back-end systems for ui5 serve.
  • SAP now calls the tool UI5 CLI (same npm package @ui5/cli, documentation at https://ui5.github.io/cli); many projects and blogs still say UI5 Tooling. In depth – ui5.yaml, middlewares, custom tasks, TypeScript → see SAPUI5 › 05 · UI5 Tooling, TypeScript & Custom Controls.

SAP Fiori tools and CAP

  • SAP Fiori tools – extensions for SAP Business Application Studio and VS Code: the application generator (Fiori elements and freestyle templates), guided development, page editor and preview with mock data. Their npm package @sap/ux-ui5-tooling provides fiori run and fiori deploy. Details: SAP Fiori › 04 · SAP Fiori Tools & Flexible Programming Model and SAP Fiori › 03 · SAP Fiori Elements.
  • SAP CAP (Cloud Application Programming Model) on Node.js: npm i -g @sap/cds-dk, cds init, cds watch (starts the service, default port 4004). CDS models become OData V4 services that UI5 and Fiori elements apps consume. SAP npm packages are on the public npm registry.
  • Legacy: SAP Web IDE was the former browser IDE – replaced by SAP Business Application Studio.

Part 17 – Interview questions

1. JavaScript is single-threaded – how can it do asynchronous work?

Your code runs on one thread, but slow operations (timers, HTTP, I/O) are handed to the runtime. When they finish, their callbacks go into a queue, and the event loop runs them when the call stack is empty – all microtasks (promise callbacks) first, then one task. That is concurrency through non-blocking I/O, not parallel execution.

2. What is the difference between var, let and const? What is the Temporal Dead Zone?

var is function-scoped, hoisted with the value undefined and can be re-declared. let and const are block-scoped and cannot be re-declared; const also cannot be re-assigned (object content can still change). All declarations are hoisted, but let/const/class stay uninitialised until their line – access before it throws a ReferenceError; that region is the TDZ. Use const by default, let if needed.

3. What is the difference between == and ===?

== converts types before comparing ("1" == 1 is true); === compares value and type without conversion. Always use === / !==.

4. How is this determined? What changes with arrow functions?

By the call: method call → the object; plain call → undefined in strict code (global object in sloppy code); new → the new instance; call/apply/bind → the given object. Arrow functions have no own this and use the surrounding one – ideal for callbacks inside UI5 controller methods, replacing var that = this and .bind(this).

5. What is a closure? Give a UI5 example.

A function that keeps access to variables of the scope it was created in, even after that scope has finished. Every sap.ui.define factory is one: helper variables defined in the factory are private to the module but usable by all its methods.

6. What is a Promise, and how do async/await relate to it?

A Promise represents the future result of an async operation: pending, then fulfilled (with a value) or rejected (with a reason); once settled it never changes. Consume it with then/catch/finally. An async function always returns a promise, and await pauses only that function until the promise settles – a rejection becomes an exception for try/catch. Run independent calls together with await Promise.all([...]); allSettled, any and race cover the other combinations.

7. What is the difference between a JavaScript object and JSON?

An object is a live value in memory and can contain functions, undefined and unquoted keys. JSON is a text format: keys and strings in double quotes, only strings, numbers, booleans, null, objects and arrays, no comments. Convert with JSON.stringify and JSON.parse.

8. Explain map, filter and reduce.

All three loop over an array without changing it. map returns a new array with each element transformed, filter returns the elements that pass a test, reduce combines all elements into one value (sum, object, grouped result).

9. What is the difference between ES modules and sap.ui.define?

ES modules are the language standard (import/export). sap.ui.define is UI5's asynchronous AMD-like module system: a dependency array of UI5 module paths and a factory function whose return value is the module. sap.ui.require loads modules on demand. UI5 TypeScript/ES class code is transpiled into sap.ui.define.

10. Is UI5 built on jQuery? Should you use jQuery in UI5 apps?

UI5 historically shipped with and used jQuery, but the jQuery.sap.* APIs are deprecated (since 1.58) and removed in UI5 2.x. Modern apps use UI5 modules (sap/base/*, sap/ui/dom/*), control APIs and native JavaScript – not jQuery.

11. What is Node.js and why does a UI5 developer need it?

Node.js is a JavaScript runtime (V8 + event loop + system APIs), not a framework. UI5 developers need it for npm and the tools built on it: UI5 Tooling (ui5 serve, ui5 build, ui5.yaml), SAP Fiori tools (fiori run, generator), the UI5 linter, and SAP CAP back ends (cds watch).

12. How do you debug a UI5 app?

F12 › Sources with breakpoints (F10 over, F11 into, Shift+F11 out, F8 continue) or a debugger; statement; the Network tab for OData calls; sap-ui-debug=true for readable UI5 sources; Ctrl+Alt+Shift+P (technical information, Support Assistant) and Ctrl+Alt+Shift+S (diagnostics); the UI5 Inspector extension.

13. Why must UI5 code load asynchronously, and how do you find old synchronous code?

A synchronous request blocks the only JavaScript thread, so the page freezes until the file arrives; browsers also deprecate synchronous XHR on the main thread. UI5 therefore loads modules asynchronously (sap.ui.define, sap.ui.require([...], cb), promise-based factories, data-sap-ui-async="true") and bundles the app into Component-preload.js. The UI5 linter (ui5lint) finds deprecated synchronous APIs, jQuery.sap.* and global access; the Support Assistant reports synchronous loading at runtime.

🏠 Start Here · ◀ 01 · HTML5 & CSS3 · 03 · UI5 Fundamentals ▶ · Sections: CORE ABAP | OOPS ABAP | ABAP on HANA | Clean Core | RAP | ABAP Points | SAP Fiori | SAPUI5 | Mobile Development (MDK) | BTP Foundations | BTP Development | CAP | SAP Build | ABAP on BTP | Integration Suite | SAP Business AI | SAP BASIS | Security | SAP SDLC

Functional: FICO ABAP | TRM ABAP | VIM | SAP BIS | SD ABAP | MM ABAP | PP ABAP | QM ABAP | PM ABAP | PS ABAP | EWM | TM ABAP | GTM ABAP | EHS ABAP | HR ABAP | BW | SAP Datasphere | SAP Business Data Cloud | SAP MDG | SAP Analytics Cloud | SAP Ariba | SAP CX | SAP IBP