Section 2. JavaScript Programming Language Overview

2.1. What Is the JavaScript Programming Language?

This section provides a foundational overview of the JavaScript programming language, tailored for its application in the context of data structures and algorithms. We will explore the core syntax, data types, and control flow mechanisms essential for implementing and understanding various data structures and algorithmic concepts. Special attention will be given to JavaScript’s dynamic nature and object-oriented capabilities, which play a crucial role in efficient algorithm design and data manipulation. This overview aims to equip readers with the necessary JavaScript skills to effectively follow the subsequent chapters on advanced data structures and algorithms.

Since this book takes a hybrid approach to the software implementation of algorithms, it is essential to briefly describe the fundamental concepts and constructs of its components: the visual algorithmic language DRAKON and the JavaScript programming language. This approach is particularly promising in the field of education, as it fosters the formation and development of algorithmic and computational thinking. It is also highly applicable in computer science, particularly in the study of data structures and algorithms.

This section assumes prior familiarity with basic programming concepts in at least one modern high-level language. At the same time, the description of JavaScript in this book is limited to the constructs necessary for understanding data structure algorithms.

This section focuses on the core programming constructs in JavaScript, such as variables, arrays, objects, maps, logical operators, loops, functions, recursion, and more. Special emphasis is placed on data types, both primitive and complex. JavaScript prototypes and closures are also briefly discussed, as they play a key role in the language.

JavaScript (JS) is a high-level, dynamically typed programming language that was originally created by Brendan Eich in 1995 while working at Netscape Communications. Unlike Go, JavaScript is an interpreted language with automatic memory management (garbage collection) and is primarily used for web development, although its use has expanded significantly in recent years.

Below are the most important features of JavaScript:

  • Lightweight and flexible – JavaScript is dynamically typed, meaning there is no need to explicitly define variable types. This makes it a flexible and beginner-friendly language.

  • Interpreted language – JavaScript code is executed line by line by an engine (V8, SpiderMonkey, or Chakra). This makes development more interactive but can also impact performance.

  • Prototype-based object model – JavaScript does not use classical OOP (like in Java or C++). Instead, it relies on prototypes and constructor functions. With the introduction of ES6 classes, JavaScript provides syntactic sugar for working with objects in an OOP-like style.

  • Asynchronous programming – JavaScript has non-blocking execution using callbacks, promises, and async/await. This makes it well-suited for handling asynchronous operations such as network requests.

  • Functional programming features – JavaScript supports higher-order functions, closures, and anonymous functions. Functions in JavaScript are first-class citizens, meaning they can be passed as arguments, returned from other functions, and stored in variables.

  • Event-driven and single-threaded – JavaScript relies on an event loop and asynchronous callbacks to manage concurrent operations.

  • Extensive ecosystem – JavaScript has a massive standard library and an even larger third-party ecosystem through npm (Node Package Manager). This makes it one of the most versatile languages in modern development.

While JavaScript was originally designed for client-side web development, it has grown into a general-purpose language thanks to Node.js, which allows JavaScript to run on servers, IoT devices, and even embedded systems.

2.2. Program Structure in JavaScript

JavaScript is a dynamically typed, interpreted programming language that is widely used for web development, backend services, and even desktop and mobile applications. A JavaScript program consists of a series of statements, functions, and modules that define its behavior.

Unlike some other programming languages, JavaScript does not require a package declaration or an explicit main() function. Instead, execution starts from the top of the script and proceeds line by line.

The basic structure of a JavaScript program can be organized as follows:

import fs from 'fs';

function main() {
console.log(`Hello, World!`);
}

main();

Here import fs from 'fs' – JavaScript allows importing external libraries or built-in modules.

Function definition (function main()) – Functions encapsulate logic and can be reused.

Execution order – The script runs from top to bottom, and functions are called explicitly.

JavaScript supports two types of comments:

// This is a single-line comment
/*
This is a multi-line comment.
It can span multiple lines.
*/

The specifics of organizing the structure of a JavaScript program in the DRAKON environment are presented in Section 3. We will only note that in DRAKON technology, the program is structured through the module() function, which is a container for the main logic of the program. Inside module(), the main() function is usually called, which controls the main process of code execution.

function module() {
function main() {
console.log("Hello, World!");
}

main(); // Call the main function
}

// Call the module
module();

2.3. Variables and Constants in JavaScript

In JavaScript, variables are used to store data values, similar to other programming languages. However, JavaScript is dynamically typed, meaning you do not need to explicitly declare the type of a variable — it is determined automatically based on the assigned value.

JavaScript provides three ways to declare variables:

  • var – the traditional way (not recommended for modern code).

  • let – for block-scoped variables that can be reassigned.

  • const – for variables that cannot be reassigned after initialization.

A variable in JavaScript is declared using the let or const keyword, followed by an identifier (variable name).

let i = 10; // Integer
let s = "Hello"; // String
let f = true; // Boolean

Variables in JavaScript do not require type definitions, as types are inferred automatically.

let a = 25; // Number (integer)
let x = 32.5; // Number (floating point)
let z = "Enter a new value"; // String

If no initial value is assigned, JavaScript sets variables to undefined, unlike Go, which initializes them with default values.

In JavaScript, multiple variables can be declared and initialized in one line, separated by commas:

let a = 100, b = 200, c = 300;

JavaScript allows reassigning variables to different types:

let value = 10; // Initially a number
value = "text"; // Now a string
value = true; // Now a boolean

JavaScript allows implicit variable declaration (not recommended):

x = 2.5; // Automatically declared as a global variable (avoid this!)

Variable names in JavaScript must follow certain rules:

✅ Can contain letters, digits, $, and _ (but no spaces).

✅ Cannot start with a digit.

✅ Are case-sensitive (myVar and myvar are different).

✅ Use camelCase naming convention (userName, totalPrice).

Constants are declared using const, meaning their values cannot be changed after initialization:

const item = "name";
const n = 25;
const y = 45.5;

2.4. Input and Output

In JavaScript, input and output operations differ significantly from those in compiled languages. Since JavaScript was initially designed for the web, it does not have built-in functions for reading user input from the terminal. Similarly, JavaScript outputs data using console.log(), which prints values to the console.

2.4.1. Output in JavaScript

JavaScript provides several ways to display information:

a) Basic Output to Console

console.log("Hello"); // Output without a newline
console.log("Hello", 23); // Output multiple values with spaces
console.log(`The salary is $${32000}`); // Using template literals

It should be noted that console.log() automatically adds a newline unless specified otherwise.

b) Formatted Output Using console.log()

JavaScript provides formatted output:

console.log("Hello %d", 23); // Equivalent to Go's fmt.Printf("Hello %d", 23)
console.log("Name: %s, Salary: %d", "Smith", 32000);

c) Using Template Literals (Recommended)

Template strings provide an easy way to interpolate variables and expressions into strings.

let name = "Smith";
let salary = 32000;
console.log(`The salary of ${name} is $${salary}`);

Template literals (`) automatically replace variables inside ${}.

2.4.2. Input in JavaScript

JavaScript does not have built-in input functions for reading user data from the terminal. Instead, input depends on the execution environment:

a) Input in the Browser (Using prompt())

In client-side JavaScript, prompt() can be used to get user input:

let name = prompt("Enter last name:");
let salary = prompt("Enter salary:");
console.log(`Salary of ${name} is $${salary}`);

The function prompt() always returns a string, so numbers must be converted using parseInt() or parseFloat():

let salary = parseInt(prompt("Enter salary:"));

b) Input in Node.js (Using readline)

If running JavaScript in Node.js, we use the readline module to handle user input:

const readline = require("readline");

const q = readline.createInterface({
input: process.stdin,
output: process.stdout
});

q.question("Enter last name: ", function(name) {
q.question("Enter salary: ", function(salary) {
console.log(`Salary of ${name} is $${salary}`);
q.close();
});
});

To Summarize:

Feature JavaScript (Browser) JavaScript (Node.js)

Output (Console)

console.log()

console.log()

Formatted Output

Template literals (`)

Template literals (`)

Basic Input

prompt()

readline module

Number Input

parseInt(prompt())

parseInt(input)

2.5. Decision-Making Operators in JavaScript

In programming, decision-making operators allow a program to choose different execution paths based on conditions. JavaScript provides several control structures for decision-making:

  • Conditional branching: if-else, switch-case

  • Loops for repeating actions: for, while, do-while

  • Control flow statements: break, continue, return

2.5.1. Conditional Statement if-else

The if-else statement allows executing different blocks of code depending on a condition.

Syntax of if-else in JavaScript:

if (condition) {
// Code executes if the condition is true
} else {
// Code executes if the condition is false
}

For single-line conditions, curly braces {} can be omitted.

Example of if-else Usage:

let ID = "Apple";

if (ID === "Apple") {
console.log("Enter your login and password");
} else if (ID === "Google") {
console.log("Your operating system is not supported");
} else {
console.log("Input error");
}

Key Points:

  • Use === instead of == to check for equality (strict comparison).

  • The else if block allows multiple conditions.

  • The else block executes if none of the conditions are met.

A representation of this construct in DRAKON technology is shown in the next section.

2.5.2. switch Statement

The switch statement provides a simpler way to compare a variable with multiple values.

Syntax of switch-case in JavaScript:

switch (expression) {
case value1:
// Code for case 1
break;
case value2:
// Code for case 2
break;
default:
// Code if no cases match
}

The break statement prevents fall-through execution.

Example of switch-case Usage:

let ID = "Apple";

switch (ID) {
case "Apple":
console.log("Enter your username and password");
break;
case "Google":
console.log("Your operating system is not supported");
break;
default:
console.log("Input error");
}

Key Points:

  • The switch statement checks the ID variable.

  • The break statement ensures only one case executes.

  • The default block runs if none of the cases match.

2.5.3. Loops in JavaScript

JavaScript supports multiple loop types for repeating actions.

a) Classic for Loop

for (let i = 0; i < 8; i++) {
console.log(i);
}

b) while Loop (Preconditioned Loop)

Executes as long as the condition is true:

let count = 10;

while (count > 0) {
console.log(count);
count--;
}

c) do-while Loop

Ensures the loop executes at least once, even if the condition is false.

let num = 5;

do {
console.log(num);
num--;
} while (num > 0);

To Summarize:

Feature JavaScript Equivalent

Conditional statement

if-else

Multiple condition checking

switch-case

Loop with counter

for loop

Loop with condition

while loop

Guaranteed execution loop

do-while loop

2.6. Looping Through Ranges in JavaScript

In JavaScript, loops allow iterating over collections such as arrays, objects, and maps. JavaScript provides several ways to loop through a range of values or iterate over arrays, objects, and maps.

2.6.1. Iterating Over Arrays Using for-of

JavaScript provides the for-of loop to iterate over arrays and other iterable objects.

Syntax of for-of in JavaScript:

for (let element of iterable) {
// Code to execute for each element
}

Example: Summing an Array

let nums = [2, 3, 4];
let sum = 0;

for (let num of nums) {
sum += num;
}

console.log("Sum:", sum);

2.6.2. Iterating Over an Array with Indexes (forEach)

If we need both the index and value, we can use forEach:

let nums = [2, 3, 4];

nums.forEach((num, index) => {
if (num === 3) {
console.log("Index:", index);
}
});

2.6.3. Iterating Over Objects Using for-in

JavaScript does not have a built-in range keyword, but it provides for-in to iterate over object properties (similar to key-value pairs).

Example: Iterating Over an Object

let capitals = {
France: "Paris",
Germany: "Berlin"
};

for (let key in capitals) {
console.log(`${key} -> ${capitals[key]}`);
}

2.6.4. Iterating Over Maps Using forEach() and for-of

For Map objects, we use forEach() or for-of with .entries().

Example: Iterating Over a Map

let capitals = new Map([
["France", "Paris"],
["Germany", "Berlin"]
]);

for (let [key, value] of capitals.entries()) {
console.log(`${key} -> ${value}`);
}

2.6.5. Iterating Over Keys Only

If we only need the keys:

for (let key of capitals.keys()) {
console.log("Key:", key);
}

To Summarize:

JavaScript Construct Usage

for-of

Iterating over arrays (values only)

forEach()

Iterating over arrays with index and value

for-in

Iterating over object keys

.entries() with for-of

Iterating over maps (key-value pairs)

.keys() with for-of

Iterating over map keys only

2.7. Data Types in JavaScript

Data types define the kind of values that variables can store in a program. They also determine the operations that can be performed on the data.

JavaScript has dynamic typing, meaning that variables do not have a fixed type but are assigned a type based on their value.

The main categories of data types in JavaScript include:

  • Primitive Types: Numbers, strings, booleans, null, undefined, Symbol, and BigInt

  • Reference Types: Objects, arrays, functions, and maps

2.7.1. Primitive Data Types

a) Numeric Data Types

JavaScript uses a single Number type for both integers and floating-point values.

Example: Declaring Numeric Variables

let integerNumber = 42; // Integer
let floatingPoint = 3.14; // Floating-point number

JavaScript also supports BigInt, a special type for working with very large integers.

let bigNumber = 9007199254740993n; // BigInt type (suffix 'n' is required)

Numeric Limits

The maximum and minimum values for numbers are stored in constants:

console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
console.log(Number.MIN_SAFE_INTEGER); // -9007199254740991
console.log(Number.MAX_VALUE); // 1.7976931348623157e+308
console.log(Number.MIN_VALUE); // 5e-324

Key Points:

  • Number type covers both integers and floating-point values.

  • BigInt allows working with very large integers beyond Number.MAX_SAFE_INTEGER.

  • JavaScript automatically converts between integer and floating-point when needed.

b) String Variables and Constants

A string in JavaScript is a sequence of characters enclosed in single quotes ('), double quotes ("), or backticks (` for template literals).

Declaring String Variables

let greeting = "Hello, World"; // Double quotes
let name = 'John'; // Single quotes
let message = `Hello, ${name}`; // Template literals (ES6+)

Key Features:

  • Strings are immutable (modifying a string creates a new string).

  • Template literals allow embedding variables using ${} inside backticks (`).

String Length and Character Access:

console.log(greeting.length); // 12
console.log(greeting[0]); // 'H'
console.log(greeting.charCodeAt(0)); // Unicode code of 'H' (72)

Unicode Representation (Hex Output)

To get the hexadecimal representation of characters:

for (let i = 0; i < greeting.length; i++) {
console.log(greeting.charCodeAt(i).toString(16));
}

Key Features:

  • The length property returns the number of characters in a string.

  • charCodeAt(i) provides the Unicode value of a character.

c) Boolean Variables and Constants

Boolean values are either true or false. They are commonly used in comparisons and conditional logic.

Declaring Boolean Variables

let isJavaScriptFun = true;
let isWeekend = false;

Boolean Expressions:

let x = 5, y = 8;
console.log("x == y:", x == y); // false
console.log("x != y:", x != y); // true
console.log("x < y:", x < y); // true
console.log("x > y:", x > y); // false
console.log("x <= y:", x <= y); // true
console.log("x >= y:", x >= y); // false

Key Features:

  • Booleans are mainly used for conditional logic (if statements, loops, etc.).

  • The comparison operators (==, !=, <, >, ⇐, >=) return boolean values.

Summary of Primitive Data Types:

Data Type Example Description

Number

let x = 10;

Holds integer or floating-point values.

BigInt

let y = 12345678901234567890n;

Used for extremely large integers.

String

let s = "Hello";

Sequence of characters.

Boolean

let isTrue = true;

Holds true or false.

Undefined

let x;

Variable is declared but not assigned a value.

Null

let y = null;

Represents an intentional absence of value.

2.8. Composite Data Types in JavaScript

JavaScript provides composite data types to store and manipulate collections of data and complex structures. The most commonly used composite types are:

  • Arrays – Ordered collections of elements.

  • Objects – Key-value pairs that represent complex data structures.

  • Maps – Key-value storage with enhanced capabilities.

2.8.1. Arrays

An array is an ordered collection of elements, where each element is indexed numerically, starting from 0. Arrays in JavaScript are dynamic, meaning they can grow and shrink in size.

Declaring and Initializing Arrays

let numbers = [10, 20, 30, 40]; // Array with 4 elements
console.log(numbers[0]); // Access first element (10)
console.log(numbers.length); // Array length (4)

Key Features:

  • Arrays are zero-indexed (array[0] is the first element).

  • The .length property returns the number of elements.

  • Arrays can store multiple types of values:

let mixedArray = [42, "text", true, null];

Adding and Removing Elements

let fruits = ["Apple", "Banana"];
fruits.push("Orange"); // Add element to the end
fruits.pop(); // Remove last element
fruits.unshift("Grapes"); // Add to the beginning
fruits.shift(); // Remove first element
console.log(fruits);

📌 JavaScript arrays are flexible – they can grow, shrink, and store mixed data types.

2.8.2. Objects

An object is a collection of key-value pairs, where each key is a property that stores a value.

Declaring an Object

let employee = {
firstName: "Max",
lastName: "Smith",
age: 42,
phone: 123456789,
salary: 34000,
address: "Amarillo"
};

console.log(`Employee: ${employee.firstName} ${employee.lastName}`);
console.log(`Salary: $${employee.salary}`);

Key Features:

  • Properties are accessed using dot notation (object.property) or bracket notation (object["property"]).

  • Objects store heterogeneous data (unlike arrays).

Updating and Adding Properties

employee.age = 43; // Updating a property
employee.department = "IT"; // Adding a new property
console.log(employee);

2.8.3. Map

let capitals = new Map([
["France", "Paris"],
["Germany", "Berlin"]
]);

console.log(capitals.get("France")); // Access value by key
capitals.set("Spain", "Madrid"); // Add new key-value pair
console.log(capitals);

Maps vs. Objects:

  • Objects use only strings as keys, while Maps can use any type of key.

  • Maps maintain key order, whereas objects do not guarantee order.

Summary of Composite Data Types:

Data Type Example Description

Array

let arr = [1, 2, 3];

Ordered collection of elements.

Object

let obj = { name: "Max" };

Collection of key-value pairs.

Map

let map = new Map();

Advanced key-value storage.

2.9. Inheritance, Encapsulation, and Polymorphism in JavaScript

2.9.1. General Features of OOP

Inheritance, encapsulation, and polymorphism are the three pillars of object-oriented programming (OOP) that play a key role in modern programming languages. They help create more modular, flexible, and maintainable code.

Core OOP Principles and Their Roles:

Inheritance

  • Allows creating new classes (subclasses) based on existing ones (superclasses), inheriting their properties and methods.

  • Promotes code reuse and the creation of class hierarchies.

  • In JavaScript, inheritance is implemented through prototypes or using classes (ES6).

Encapsulation

  • Hides internal implementation details of a class and provides access to them only through public methods.

  • Protects data from unauthorized access and enhances code reliability.

  • In JavaScript, encapsulation is achieved through closures or modules.

Polymorphism

  • Enables objects of different classes with a common interface to behave differently.

  • Makes code more flexible and adaptable to changes.

  • In JavaScript, polymorphism is implemented through dynamic typing and method overriding.

2.9.2. Implementing OOP Principles Using Factory Functions

Factory functions provide a flexible and powerful way to implement OOP principles in JavaScript. Using factory functions helps to prevent the problems of classical prototypical inheritance. With the help of factory functions, you can use object composition, which in many cases is a more flexible solution than inheritance.

Encapsulation with Factory Functions

In this book, the specified OOP principles are implemented based on the use of factory functions.

function createPerson(name, age) {
let _name = name; // private variable
let _age = age; // private variable

return {
getName: function() {
return _name;
},
getAge: function() {
return _age;
},
setAge: function(newAge) {
if (newAge > 0 && newAge < 150) {
_age = newAge;
}
}
};
}

const person = createPerson("Ivan", 30);
console.log(person.getName()); // Output: Ivan
person.setAge(31);
console.log(person.getAge()); // Output: 31
// console.log(person._age); // Error: _age is not accessible from outside

Composition (Alternative to Inheritance) with Factory Functions

const canBark = (state) => ({
bark: () => console.log("Woof!")
});

const canWalk = (state) => ({
walk: () => console.log("Walking...")
});

const createDog = (name) => {
let state = {
name: name
};
return Object.assign(
{},
state,
canBark(state),
canWalk(state)
);
};

const dog = createDog("Bobik");
dog.bark(); // Output: Woof!
dog.walk(); // Output: Walking...

Polymorphism with Factory Functions

const createCircle = (radius) => ({
calculateArea: () => Math.PI * radius * radius
});

const createSquare = (side) => ({
calculateArea: () => side * side
});

function printArea(shape) {
console.log("Area:", shape.calculateArea());
}

const circle = createCircle(5);
const square = createSquare(4);

printArea(circle); // Output: Area: 78.53981633974483
printArea(square); // Output: Area: 16

2.10. Summary

This section provided a comprehensive overview of the JavaScript programming language and the DRAKON visual algorithmic language, establishing the practical foundation for implementing data structures and algorithms in this book.

JavaScript’s core syntax, dynamic typing, flexible object model, and functional programming capabilities (such as first-class functions and closures) make it a versatile tool for algorithm design. We explored both class-based and object-composition paradigms, alongside essential control structures and asynchronous primitives (Promises, async/await).

In parallel, the DRAKON language introduces a visual, structured methodology for algorithm specification, minimizing cognitive load and preventing common flow-control errors. Together with JavaScript, this hybrid approach bridges high-level algorithmic reasoning with robust, modern software implementation.

With the core language mechanics and visual modeling principles established, we are fully prepared to proceed to concrete data structure implementations, algorithmic analysis, and performance optimization in the upcoming sections.