JS Basic to Use the Algo Visualization
Optional Learning Content
I have prepared visualization code for each problem in advance, and I even guide you through the article or comments on how to manipulate the visualization panel to observe the algorithm's execution process. So, even if you are not familiar with JavaScript, you can still benefit from the visualization panel accompanying each problem.
However, some readers may want to modify the preset code or test their own innovative ideas through visualization. For this, some basic knowledge of JavaScript is necessary, and this article is designed for those readers.
Since my Algorithm Visualization Panel currently only supports JavaScript, I have written a minimalist JS tutorial to introduce the basic usage of JS. The goal is to enable readers unfamiliar with JS to effectively use the algorithm visualization panel.
With the advancement of AI tools, you generally don't need to write JS from scratch. You can use AI tools to help translate code from other languages into JS. You just need to understand basic JS syntax to read the code. So, if you are familiar with any other programming language, spending 5 minutes on the following content will allow you to use the visualization panel effortlessly.
Basic JavaScript Syntax
Variable Declaration
Let's start with variable declaration in JavaScript. There are three ways to declare variables: var
, let
, and const
.
const
is used for constants, which cannot be modified once declared. This is mostly relevant in engineering code, and in algorithm code, its use is optional.
const a = 1;
// error will be thrown
a = 2;
Both var
and let
can declare regular variables, but the visibility of the variables they declare is different. var
is more of a legacy issue. In general, you can consider their effects to be the same in the visual panel.
let str = "hello world";
str = "world"
// output world
console.log(str);
if (true) {
// the str here and the str outside are two different variables
let str = "hello";
// output hello
console.log(str);
}
In my visualization code, the top-level functions are generally declared using var
. This is because the function signatures provided on LeetCode for JavaScript are declared with var
, so I have followed suit. However, if you want to change it to let
, that's perfectly fine as well.
Function Declaration
JavaScript function declarations are quite straightforward, like this:
function add(a, b) {
return a + b;
}
// output 3
console.log(add(1, 2));
The declaration of this function is the same as in other programming languages. However, in JavaScript, you might also see the following anonymous function declaration, which is essentially assigning an anonymous function to a variable. The usage is the same either way:
// replacing let with var will have the same effect
let add2 = function(a, b) {
return a + b;
}
// output 3
console.log(add2(1, 2));
// declare using ES6 arrow function
let add3 = (a, b) => {
return a + b;
}
// output 3
console.log(add3(1, 2));
Functions declared with the function
keyword and arrow functions declared with () => {}
have some key differences, mainly in how the this
pointer behaves within the function body. However, this feature is rarely used in algorithmic problems, so you can consider these two methods to be the same.
Loop Control
JavaScript's loop control is similar to other programming languages, with common loops being for
and while
.
Taking array traversal as an example, let's start with the most common method, using an index to traverse:
// traverse the array
let arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
// output 1 2 3 4 5
然后是用 for...of
方式,可以直接遍历元素:
// Traverse the array
let arr = [1, 2, 3, 4, 5];
for (let item of arr) {
console.log(item);
}
// Output 1 2 3 4 5
Use `for ... of` to Iterate Elements
Note that JavaScript uses of
to iterate over array elements, not in
. in
has other uses, but we rarely need it for algorithm problems, so I won't elaborate.
I know some other languages use in
to iterate over array elements, so I want to remind you not to get confused.
The while
loop is the same as in other languages. Here's a simple example:
let arr = [1, 2, 3, 4, 5];
let i = 0;
while (i < arr.length) {
console.log(arr[i]);
i++;
}
// output 1 2 3 4 5
Conditional Statements
The usage of if else
is exactly the same as in other languages, so there's not much to say. Here's a simple example:
let a = 1;
if (a === 1) {
console.log("a equals 1");
} else {
console.log("a does not equal 1");
}
Use `===` for Equality Checks
There's a small pitfall here regarding the difference between ==
and ===
in JavaScript. ==
checks for value equality, while ===
checks for both value and type equality.
In simple terms, just remember that ==, !=
in other languages correspond to ===, !==
in JavaScript. Avoid using ==, !=
in JavaScript.
Basic Data Structures in JavaScript
Strings
Strings in JavaScript are similar to those in other languages, with no special differences. Here's an example:
let str = "hello world";
// output 11
console.log(str.length);
// output h
console.log(str[0]);
// output true
console.log(str === "hello world");
// split the string
let arr = str.split(" ");
// output ["hello", "world"]
console.log(arr);
// get a substring, multiple methods are available
// output hello
console.log(str.substring(0, 5));
// output hello
console.log(str.slice(0, 5));
// output hello
console.log(str.substr(0, 5));
// concatenate strings
let str2 = "world";
// output hello world world
console.log(str + " " + str2);
Arrays
There are several ways to create an array:
let arr1 = [1, 2, 3, 4, 5];
let arr2 = new Array(1, 2, 3, 4, 5);
// create an array of length 5, each element is undefined
let arr3 = new Array(5);
// create an array of length 5, each element is 0
let arr4 = new Array(5).fill(0);
Common Operations on Arrays:
let arr = [1, 2, 3, 4, 5];
// get the length of the array
// output 5
console.log(arr.length);
// get an element of the array
// output 1
console.log(arr[0]);
// modify an element of the array
arr[0] = 100;
// copy all elements of the array to a new array
let arr2 = arr.slice();
// this is also a method to copy an array
let arr3 = [...arr];
// add an element to the end of the array
arr.push(6);
// remove the last element from the array
arr.pop();
// add an element 888 to the beginning of the array
// not commonly used, as algorithms generally avoid adding or
// removing elements from positions other than the end of the
arr.unshift(888);
// remove the first element from the array
// not commonly used, as algorithms generally avoid adding or
// removing elements from positions other than the end of the
arr.shift();
Alright, understanding the above basic operations is more than enough for you to use arrays in algorithm problems.
Hash Table
In simple terms, objects in JavaScript can be understood as hash tables because JavaScript objects consist of key-value pairs. However, with the introduction of the Map
type in ES6, we can be more formal and use the Map
type to create hash tables.
Basic operations of Map
:
let map = new Map();
// Add key-value pairs
map.set("a", 1);
map.set("b", 2);
map.set("c", 3);
// Retrieve key-value pairs
// Output 1
console.log(map.get("a"));
// Delete key-value pair
map.delete("a");
// Check if a key exists
// Output false
console.log(map.has("a"));
// Output true
console.log(map.has("b"));
// Iterate over key-value pairs
for (let key of map.keys()) {
console.log(key, map.get(key));
}
// Output b 2 and c 3
This should cover most of it. If you encounter a situation you can't handle, just refer to the documentation.
Hash Set
The Set
type introduced in ES6 is a hash set, used to store unique elements. The basic operations are as follows:
let set = new Set();
// Add elements
set.add(1);
set.add(2);
set.add(3);
// Delete an element
set.delete(1);
// Check if an element exists
// Output false
console.log(set.has(1));
// Output true
console.log(set.has(2));
// Traverse elements
for (let item of set) {
console.log(item);
}
// Output 2 and 3
Other Special Data Structures
In algorithm problems, you may also encounter special data structures such as linked lists, trees, binary heaps, etc. These data structures are not built-in to JavaScript. However, my algorithm visualization panel has implemented these special data structures. You can refer to my Introduction to the Algorithm Visualization Panel for specific usage.