MIT Weblab笔记 - JavaScript Basis

Introduction

  • Adding a Javascript file to HTML: <script src="snake.js"></script> inside <head> section.
  • Any code that is not inside a function will run as soon as the script is loaded.
  • Any functions that are called in the global code will be executed in the order they appear.
  • When both files are included in the HTML with <script> tags, they share the same global scope. This allows functions and variables defined in one file to be accessible in the other.

Run Javascript

1
node code.js

Triggering Javascript

Inline Event Handlers

1
<button onclick="buttonClicked()">Click Me</button>
1
2
3
function buttonClicked() {
alert("Button clicked!");
}

or

1
<button onclick="alert('Button clicked!')">Click Me</button>

The onclick attribute in the <button> tag specifies JavaScript code to run when the button is clicked.

Event Listeners

1
2
3
4
5
6
7
<button id="myButton">Click Me</button>

<script>
document.getElementById("myButton").addEventListener("click", function () {
alert("Button clicked!");
});
</script>
  • document.getElementById('myButton'): Selects the HTML element with the id myButton and returns a reference to the button element.
  • .addEventListener: Attaches an event handler to the selected element.
1
2
3
window.addEventListener("keydown", (event) => {
console.log(event.key);
});
  • window: The global window object represents the window containing the DOM document.

Page Load

1
2
3
4
5
<script>
window.onload = function () {
console.log("Page loaded!");
};
</script>
  • The code inside window.onload runs when the entire page has finished loading.

Timers

1
2
3
4
5
6
7
setTimeout(function () {
alert("This alert appears after 3 seconds");
}, 3000);

setInterval(function () {
console.log("This message appears every 2 seconds");
}, 2000);

Syntax

Data Types

Primitive Types:

  • boolean (true, false)
  • number (12, 1.3, -45.6, 0)
  • string (“Hello”)
  • null
  • undefined

Variables

1
2
3
var name = "John Doe";
let age = 30;
const isStudent = true;
  • var: Declares a variable that can be globally or functionally scoped.
  • let: Declares a block-scoped variable, which means it is limited to the {} to which it is defined.
  • const: Declares a block-scoped variable that cannot be reassigned.

Operaters

  • ===: Compares two values for equality without performing type conversion.
  • ==: Forcing the arguments to be of the same type before comparing them.
1
2
3
5 == "5"; // true
5 === "5"; // false
"hello" === "hello"; // true

=== can only compare primitive types! For objects, === compares references to them.

1
2
3
let arr1 = [1, 2, 3];
let arr2 = [1, 2, 3];
arr1 === arr2; // false

Arrays

1
2
3
4
5
6
let colors = ["red", "green", "blue"]; // initialize
console.log(colors[1]); // "green"
colors[2] = "white";
colors.pop(); // remove the last
colors.push("black"); // add to the back
colors.unshift("purple"); // add to the front

Conditional Statements

1
2
3
4
5
6
7
8
9
let time = 20;

if (time < 12) {
console.log("Good morning!");
} else if (time < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}

Loops

1
2
3
for (let i = 0; i < 5; i++) {
console.log("Number: " + i);
}
1
2
3
4
5
let i = 0;
while (i < 5) {
console.log("Number: " + i);
i++;
}

Objects

1
2
3
4
5
6
7
8
9
10
11
12
// Objects is key-value pairs inside a {}
let person = {
firstName: "Songlin",
lastName: "Zhao",
age: 30,
};
console.log(person.age); // 30

// object destructing: obtain multiple properties at once
const { firstName, lastName } = person;
console.log(firstName); // "Songlin"
console.log(lastName); // "Zhao"
1
2
3
4
5
6
// Array of objects
const snakeBody = [
{ x: 10, y: 11 },
{ x: 10, y: 12 },
{ x: 10, y: 13 },
];

Copying two objects

1
2
3
4
5
let arr = [1, 2, 3];
let copyArr = [...arr];

let obj = { name: "Eric" };
let copyObj = { ...obj };

Functions

1
2
3
4
5
const addOne = (num) => {
const result = num + 1;
return result;
};
console.log(addOne(4)); // Output: 5
  • Function is unmodifiable, so use const functionName
  • (parameters) => {function contents}

Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Person {
// Constructor method to initialize the object
constructor(name, age) {
this.name = name;
this.age = age;
}

displayDetails() {
console.log(`Name: ${this.name}, Age: ${this.age}`);
}

// Static method
static greet() {
console.log('Hello!');
}
}

const person1 = new Person('Alice', 30);

person1.displayDetails(); // Output: Name: Alice, Age: 30

Person.greet(); // Output: Hello!

Advanced

Callback Functions

Pass functions as parameters: Convert array of Celsius to Fahrenheit.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const modifyArray = (arr, func) => {
const newArr = [];
for (let i = 0; i < arr.length; i++) {
newArr.push(func(arr[i]));
}
return newArr;
};

const T2F = (tempC) => {
return (tempC * 9) / 5 + 32;
};

const tempsC = [0, 25, 100];
const tempsF1 = modifyArray(tempsC, T2F);
const tempsF2 = modifyArray(tempsC, (tempC) => (tempC * 9) / 5 + 32); // directly put the function in the parameter
  • When directly putting the function in the parameter, the function is like (tempC) => (tempC * 9) / 5 + 32, with no curly braces {} after arrow =>.
  • When using {}, the return value should be specified by the return keyword.

map()

1
2
3
4
5
const myArray = [1, 2, 3, 4, 5];
const newArray = myArray.map((num) => {
return num * 3;
}); // newArray = [3,6,9,12,15]
const newArray = myArray.map((num) => num * 3); // another way to do this
  • map() creates a new array.
  • map() applies the callback function to every element of the array.

filter()

1
2
let values = [-1, -2, 3, 4, 5];
const filteredArray = values.filter(x => x > 0); // filteredArray = [3,4,5]
  • filter() creates a new array.
  • filter() selects the element which passes the “test”.

MIT Weblab笔记 - JavaScript Basis
https://thiefcat.github.io/2024/06/27/MIT-Weblab/JavaScript/
Author
小贼猫
Posted on
June 27, 2024
Licensed under