JS Basic to Use the Algo Visualization
Since my Algorithm Visualization Panel currently only supports JavaScript, this tutorial is aimed not only at JavaScript beginners but also at readers using other programming languages, helping everyone quickly get started with the algorithm visualization panel.
For Readers Using Other Languages, This is Optional Content
I have pre-written the visualization code for each problem and will even tell you in the article or comments how to operate the visualization panel to observe the algorithm 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 my preset code or visualize their own creative ideas, in which case a basic understanding of JavaScript syntax is necessary. This article is prepared for those readers.
With the advancement of AI tools, you generally don't need to write JS from scratch. You can use AI tools to translate code from other languages into JS. You only need to understand basic JS syntax to comprehend the code. So, as long as you are familiar with any other programming language, spending five minutes on the following content will enable you to use the visualization panel effectively.
Basic JavaScript Syntax
Variable Declaration
Let's start with variable declaration in JavaScript, which can be done in three ways: var, let, const
.
const
is used to declare constants that cannot be modified once set. This is generally used 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 is equal to 1");
} else {
console.log("a is not equal to 1");
}
Difference Between ===
and ==
A common pitfall in JavaScript is understanding the difference between ==
and ===
. ==
returns true
if the values are equal, while ===
returns true
only if both the values and types are equal. Conversely, !=
returns true
if the values are not equal, and !==
returns true
if either the values or types are not equal.
For example, in JavaScript, both null
and undefined
represent empty values. null == undefined
is true
, but null === undefined
is false
.
This distinction is somewhat of a historical issue in JavaScript. In algorithmic contexts, this level of detail is rarely relevant, so you can often consider both as similar.
Basic Data Structures in JavaScript
Strings
Strings in JavaScript are similar to those in other languages, with nothing particularly special. 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.