Javascript Refresher
These notes serve as a JavaScript refresher, and for me a gentle introduction to JavaScript coming from Python.
1. JavaScript in Web Pages
1.1. Adding JavaScript to a Page
Javascript is supported natively by the browser, so we can add it directly to the html of a webpage.
We can add it either in the body of the <script>
tag, or preferably as a separate .js
file that’s then called as the src
parameter of the script tag.
The defer
parameter means the script won’t be called until the rest of the body is loaded.
The type=module
parameter means the JavaScript file will be treated as a module rather than executed as a script.
1.2. React Projects Use a Build Process.
JSX is not natively supported by the browser, so a build tool transforms it to regular JavaScript.
It also minifies the project to optimise the size and loading times.
2. Imports and Exports
We need to use the export
keyword to make a function or variable available outside of that file. Each file can have at most one default
export.
The import
keyword then lets us use this.
Use curly braces for the import unless it is a default export. If it is a default export, you assign your own name to the imported variable. The path to import from is in single or double quotes, with the file extension in plain JS. In React, some build tools automatically populate the file extension so you don’t need it.
We can group the imports if there are many by using starred imports.
import * as utils from “./utils.js”;
Then use utils.blah
to use those imported values.
We can also alias individual imported variables with the as
keyword.
3. Variables
The primitives in JavaScript are: string, number, boolean, null, undefined.
The are also complex types built in: object, array.
Variables are defined with the let
keyword. Camel case is most common in JS.
Constants are defined with the const
keyword. They cannot be reassigned. Prefer const where it is appropriate, to be clear about your intentions that this should not be reassigned.
Older versions of JavaScript did not make this distinction and used var
in all cases. This is discouraged now.
4. Operators
These include add, subtract, divide, multiply.
These can be defined on any types, not just numbers.
Triple equals ===
is used to compare values.
5. Functions
Functions can be defined using “regular” syntax or “arrow” syntax.
Regular syntax:
function sum(a, b) {
return a + b;
}
Arrow function syntax:
const sum = (a, b) => {a + b};
The function can then be invoked as
sum(1, 3)
We can set default values of variables as
const sum = (a, b = 1) => {a + b};
Functions can be passed as props to other functions. This is helpful when defining components which we want to pass state setters or other handler functions to (functional components are ultimately just functions themselves).
We can also define functions inside of other functions. This is helpful when we want the function to be scoped only to the outer function, not defined globally. This is again used a lot in React since we may want to define functions with our (functional) components.
6. Objects
Objects are key-value pairs. The value for a given key can be accessed with .
, for example:
.key1 obj
Objects can also have methods. These are functions defined inside the object.
const obj = {
name: “Gurp”,
method1: greet() {return “Hello “ + this.name}
}.greet() obj
Class instances are essentially objects like above. If we want to create a reusable class, we can formally define a class.
class User (
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return “Hello “ + this.name;
}
)
const user1 = new User("Gurp", 30);
Objects (and, by extension, arrays) are passed by reference. So when we modify the object, it does not create a new object, it mutates the original. The memory address is stored as a constant, not the value. So if we create an object as a const
, we can modify it without reassigning it.
7. Arrays
Arrays are technically a special case of object.
const array1 = [1, 2, 3, 4];
There are some built-in utility methods of arrays that are particularly helpful/common:
Method | Example | Docs |
---|---|---|
push | array1.push(5); |
push docs |
map | const squares = array1.map((item) => item * 2); |
map docs |
find | const found = array1.find((element) => element > 3); |
find docs |
findIndex | arr.findIndex((item) => item===2) |
findIndex docs |
filter | const result = array1.filter((item) => item > 2); |
filter docs |
reduce | const summedArray = array1.reduce((accumulator, currentValue) => accumulator + currentValue); |
reduce docs |
concat | const array3 = array1.concat(array2); |
concat docs |
slice | array1.slice(1,3) // returns [2, 3] |
slice docs |
splice | months.splice(4, 1, 'May'); // Replaces 1 element at index 4 |
splice docs |
8. Destructuring
Array destructuring allows us to pick out the values of an array rather than assigning them one-by-one.
const [firstName, lastName] = ["Gurp", "Johl"]
instead of
const nameArray = ["Gurp", "Johl"]
const firstName = nameArray[0]
const lastName = nameArray[1]
Similarly, we can destructure objects too. We can also alias the keys with a :
, as in the example below where the name
key is aliased to userName
.
const {name: userName, age} = {name: 'Gurp', age: 30}
instead of
const userObj = {name: 'Gurp', age: 30}
const userName = userObj.name
const age = userObj.age
9. Spread Operator
The spread operator pulls out values of arrays and objects. This is useful for merging multiple arrays, e.g.
const arrayA = [1, 2, 3]
const arrayB = [4, 5, 6]
const mergedArray = [...arrayA, ...arrayB]
The same applies to merging objects.
10. Control Structures
If-else clauses work similarly to other languages:
if userName === "Gurp" {
// Do something
else {
} // Do something else
}
For loops again are similar, although the syntax looks a bit janky at first compared to Python:
const hobbies = ["Sports", "Music"];
for (const hobby of hobbies) {
console.log(hobby);
}
References
- MDN docs
- Section 2 of “React: The Complete Guide” Udemy course