User:ZUZU/Study/Web01: Difference between revisions
(→Day1) Tag: Manual revert |
|||
(49 intermediate revisions by the same user not shown) | |||
Line 129: | Line 129: | ||
== WEEK 7 == | == WEEK 7 == | ||
====Basics JavaScript==== | ====Basics JavaScript==== | ||
=====The placement of JavaScript within an HTML ===== | =====The placement of JavaScript within an HTML ===== | ||
Line 151: | Line 151: | ||
<syntaxhighlight lang="bash"> | <syntaxhighlight lang="bash"> | ||
node example.js | node example.js | ||
</syntaxhighlight> | |||
===== 5 primitive data types ===== | |||
{| class="wikitable" | |||
|- | |||
! Name !! Description !! Sample | |||
|- | |||
| style="text-align: center"| '''string''' | |||
| style="width:300px" | a sequence of characters enclosed in single quotes (') or double quotes (") used to represent text data | |||
| <syntaxhighlight lang="JavaScript">let greeting = 'Hello, world!'; | |||
console.log(typeof greeting); // Output: string | |||
let name = "Zuzu S"; | |||
console.log(typeof name); // Output: string | |||
</syntaxhighlight> | |||
|- | |||
| style="text-align: center"|'''number''' | |||
| Numeric data, can be integers or floating-point numbers | |||
|<syntaxhighlight lang="JavaScript"> | |||
let age = 30; | |||
console.log(typeof age); // Output: number | |||
let pi = 3.14; | |||
console.log(typeof pi); // Output: number | |||
</syntaxhighlight> | |||
|- | |||
| style="text-align: center"|'''boolean''' | |||
|a logical value, either true or false. | |||
|<syntaxhighlight lang="JavaScript"> | |||
let isAdult = true; | |||
console.log(typeof isAdult); // Output: boolean | |||
let hasPermission = false; | |||
console.log(typeof hasPermission); // Output: boolean | |||
</syntaxhighlight> | |||
|- | |||
| style="text-align: center"|'''null''' | |||
|a variable has no value or points to nothing | |||
|<syntaxhighlight lang="JavaScript">let car = null; | |||
console.log(typeof car); // Output: object | |||
</syntaxhighlight> | |||
|- | |||
| style="text-align: center"|'''undefined''' | |||
|a variable that has been declared but has not been assigned a value, it is the default value of variables in JavaScript that have not been initialized. | |||
|<syntaxhighlight lang="JavaScript">let x; | |||
console.log(typeof x); // Output: undefined | |||
let y = undefined; | |||
console.log(typeof y); // Output: undefined | |||
</syntaxhighlight> | |||
|- | |||
|} | |||
===== comparison operators ===== | |||
<syntaxhighlight lang="JavaScript"> | |||
//Equal (==):Checks if two values are equal in terms of value, but does not check for data type. | |||
console.log(5 == 5); // true | |||
console.log(5 == '5'); // true (coerced to the same type) | |||
console.log(5 == 7); // false | |||
//rict Equal (===):Checks if two values are equal in both value and data type. | |||
console.log(5 === 5); // true | |||
console.log(5 === '5'); // false (different types) | |||
//Not Equal (!=) | |||
console.log(5 != 7); // true | |||
console.log(5 != 5); // false | |||
//Strict Not Equal (!==) | |||
console.log(5 !== '5'); // true (different types) | |||
console.log(5 !== 5); // false | |||
//Greater Than (>) and Greater Than or Equal To (>=) | |||
console.log(5 > 3); // true | |||
console.log(5 >= 5); // true | |||
</syntaxhighlight> | </syntaxhighlight> | ||
===== var,let,const ===== | ===== var,let,const ===== | ||
'''var''': variables | '''var''': variables is function-scoped. That they are accessible anywhere within the function or global scope in which they are declared. | ||
<syntaxhighlight lang="JavaScript"> | <syntaxhighlight lang="JavaScript"> | ||
function example() { | function example() { | ||
Line 196: | Line 273: | ||
console.log(person); // Output: { name: 'John', age: 31 } | console.log(person); // Output: { name: 'John', age: 31 } | ||
// person = {}; // Error: Assignment to constant variable | // person = {}; // Error: Assignment to constant variable | ||
</syntaxhighlight> | |||
===== Common JavaScript Syntax Symbol ===== | |||
Syntax | |||
<syntaxhighlight lang="JavaScript"> | |||
//this function finds the GCD of two numbers | |||
const greatestCommonDivisor = (a, b) => {//Curly braces denote where blocks begin and end. | |||
while (b !== 0) { | |||
const temp = b;//Every statement in JavaScript ends with a semicolon; | |||
b = a % b; | |||
a = temp; | |||
} | |||
return a; | |||
} | |||
const x = 50; | |||
const y = 15; | |||
const gcd = greatestCommonDivisor(x, y);//output:5 | |||
</syntaxhighlight> | |||
{| class="wikitable" | |||
|- | |||
! Symbol !! Description !! Sample | |||
|- | |||
| rowspan="3" style="text-align: center"| '''( )''' | |||
| '''Function Invocation''': Call a function and execute its code, use parentheses after the function name with optional arguments inside. | |||
| <syntaxhighlight lang="JavaScript">function example() { | |||
let x = 10; | |||
if (true) { | |||
let y = 20; | |||
console.log(x); // Output: 10 | |||
console.log(y); // Output: 20 | |||
}</syntaxhighlight> | |||
|- | |||
| '''Grouping Expressions''': Parentheses can be used to group expressions and control the order of evaluation in complex expressions. | |||
| <syntaxhighlight lang="JavaScript">let result = (2 + 3) * 4; // Result: 20 | |||
}</syntaxhighlight> | |||
|- | |||
| '''Function Declarations and Definitions''': When declaring or defining functions, enclose the parameters and the function body within parentheses. | |||
| <syntaxhighlight lang="JavaScript">let add = (a, b) => { | |||
return a + b; | |||
}; | |||
</syntaxhighlight> | |||
|- | |||
| rowspan="2" style="text-align: center"| '''{ }''' | |||
| style="width:300px"| '''Function and Control Structures:''': Curly braces define the scope of function bodies, control structures like if, for, while loops, and blocks of code in general. | |||
| <syntaxhighlight lang="JavaScript">function example() { | |||
let x = 10; | |||
if (true) { | |||
let y = 20; | |||
console.log(x); // Output: 10 | |||
console.log(y); // Output: 20 | |||
}</syntaxhighlight> | |||
|- | |||
| '''Object Literals''': Define object literals, which are key-value pairs enclosed within curly braces. | |||
| <syntaxhighlight lang="JavaScript">let person = { | |||
name: 'John', | |||
age: 30 | |||
}; | |||
</syntaxhighlight> | |||
|- | |||
| rowspan="2" style="text-align: center"| '''[ ]''' | |||
| '''Array access''': Access elements in an array by their index. | |||
| <syntaxhighlight lang="JavaScript">const numbers1 = [1,2,3]; | |||
console.log(numbers1[0]);//Output: 1 | |||
</syntaxhighlight> | |||
|- | |||
| '''Computed property names''': in object literals, the value of propertyName is used as the property name for the person object. | |||
| <syntaxhighlight lang="JavaScript">const propertyName = 'name'; | |||
const person = { | |||
[propertyName]:'John' | |||
}; | |||
console.log(person.name);// Output: John | |||
</syntaxhighlight> | |||
|- | |||
|} | |||
===== Template Strings ===== | |||
a convenient way to create strings | |||
<syntaxhighlight lang="JavaScript"> | |||
const username = "KK"; | |||
const age = 30; | |||
console.log(`My name is ${username} and I am ${age} years old.`); // Output: My name is KK and I am 30 years old. | |||
const hello = `My name is ${username} and I am ${age} years old.`; | |||
console.log(hello); // Output: My name is KK and I am 30 years old. | |||
</syntaxhighlight> | |||
===== String Operations===== | |||
various methods to manipulate strings | |||
<syntaxhighlight lang="JavaScript"> | |||
const s = "hello world"; | |||
console.log(s.length); // Output: 11 | |||
console.log(s.toLowerCase()); // Output: hello world | |||
console.log(s.toString()); // Output: hello world | |||
console.log(s.substring(1, 5).toUpperCase()); // Output: ELLO | |||
console.log(s.split("")); // Output: ["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"] | |||
const k = "under,make,call"; | |||
console.log(k.split(",")); // Output: ["under", "make", "call"] | |||
</syntaxhighlight> | |||
===== Arrays ===== | |||
Arrays are used to store multiple values in a single variable and can hold different types of data, including numbers, strings, and even other arrays. | |||
<syntaxhighlight lang="JavaScript"> | |||
const fruits = ["apple", "pear", "banana"]; | |||
//add to end | |||
fruits.push("mango"); | |||
console.log(fruits); // Output: ["apple", "pear", "banana", "mango"] | |||
//add at beginning | |||
fruits.unshift("grapes"); | |||
console.log(fruits); // Output: ["grapes", "apple", "pear", "banana", "mango"] | |||
//remove from end | |||
fruits.pop(); | |||
console.log(fruits); // Output: ["grapes", "apple", "pear", "banana"] | |||
console.log(fruits.indexOf("mango")); // Output: -1 (as "mango" is no longer in the array after pop) | |||
console.log(Array.isArray(fruits)); // Output: true | |||
console.log(fruits[1]); // Output: apple | |||
</syntaxhighlight> | |||
===== Array Declaration ===== | |||
<syntaxhighlight lang="JavaScript"> | |||
// Array Declaration | |||
const todos = [ | |||
{ | |||
id: 1, | |||
text: "Take out trash", | |||
inCompleted: true, | |||
}, | |||
{ | |||
id: 2, | |||
text: "Meeting with boss", | |||
inCompleted: true, | |||
}, | |||
{ | |||
id: 3, | |||
text: "Dentist appt", | |||
inCompleted: true, | |||
}, | |||
]; | |||
// Accessing Array Elements | |||
console.log(todos[1].text); // Output: Meeting with boss | |||
//Replace | |||
todos[1].text = "Shopping"; | |||
// JSON Serialization | |||
//Convert the todos array into a JSON string and store it in the constant variable todoJSON. | |||
const todoJSON = JSON.stringify(todos); | |||
console.log(todoJSON); | |||
</syntaxhighlight> | |||
===== Object ===== | |||
a collection of '''name:value''' pairs | |||
<syntaxhighlight lang="JavaScript"> | |||
const person = { | |||
firstName: "KK", | |||
lastName: "ÖO", | |||
age: 30, | |||
hobbies: ["music", "movies"], | |||
address: { | |||
street: "50 main st", | |||
city: "Boston", | |||
state: "MA" | |||
} | |||
}; | |||
//Accessing properties | |||
console.log(person.firstName); // Output: KK | |||
console.log(person.["hobbies"]); // Output: ['music', 'movies'] | |||
// Object destructuring | |||
// A shorthand to obtain multiple properties at once | |||
const { firstName, lastName, address: { city } } = person; | |||
console.log(firstName); // Output: KK | |||
console.log(lastName); // Output: ÖO | |||
console.log(city); // Output: Boston | |||
// Property assignment | |||
person.email = "kk@gmail.com"; | |||
console.log(person) // Output: Complete person object with added email property | |||
</syntaxhighlight> | |||
===== Object references ===== | |||
Object variables are references, they do not store the object's data directly but store a reference to the location where the object's data is stored. | |||
<syntaxhighlight lang="JavaScript"> | |||
let person1 = { name: "kk" }; | |||
let person2 = { name: "kk" }; | |||
console.log(person1 === person2); // Output: false | |||
</syntaxhighlight> | |||
===== JS Function Syntax ===== | |||
Functions are values that are stored in memory, just like strings, integers, objects, and other data types. This means we can assign variables to point to functions. | |||
<syntaxhighlight lang="JavaScript"> | |||
//Basic syntax | |||
(parameters) => { body }; | |||
//here is a function to find the greatest common divisor of a and b | |||
(a, b) => { | |||
while (b !== 0) { | |||
const temp = b; | |||
b = a % b; | |||
a = temp; | |||
} | |||
return a; | |||
} | |||
//we could assign the function to a variable,we could name variable:greatestCommonDivisor,and then use const to point to the function | |||
const greatestCommonDivisor = (a, b) => { | |||
const temp | |||
b = a % b; | |||
a = temp; | |||
} | |||
return a; | |||
};//end with a semicolon because it's a variable | |||
</syntaxhighlight> | |||
===== Copying arrays and objects ===== | |||
One way is to use the spread operator (...) | |||
<syntaxhighlight lang="JavaScript"> | |||
const originalArray = [1, 2, 3]; | |||
const copyArray = [...originalArray]; | |||
const originalObject = { key1: 'value1', key2: 'value2' }; | |||
const copyObject = { ...originalObject }; | |||
</syntaxhighlight> | |||
===== Conditional Statements (if-else) ===== | |||
Extract values from objects and assign them to variables | |||
<syntaxhighlight lang="JavaScript"> | |||
if (U === 10) { | |||
console.log("U is 10"); | |||
} else if (U > 10) { | |||
console.log("U is greater than 10"); | |||
} else { | |||
console.log("U is less than 10"); // Output: U is less than 10 | |||
} | |||
</syntaxhighlight> | |||
===== Ternary Operator ===== | |||
a shorthand for an if-else statement | |||
<syntaxhighlight lang="JavaScript"> | |||
/* | |||
Syntax: condition ? expression1 : expression2 | |||
If the condition evaluates to true, expression1 is executed; otherwise, expression2 is executed. | |||
In this case, e > 10 is the condition. If e is greater than 10, "red" is assigned to color1; otherwise, "blue" is assigned. | |||
*/ | |||
const e = 10; | |||
const color1 = e > 10 ? "red" : "blue"; | |||
console.log(color1); // Output: blue | |||
</syntaxhighlight> | |||
===== Switch Statement ===== | |||
<syntaxhighlight lang="JavaScript"> | |||
switch (color2) { | |||
case "red": | |||
console.log("color2 is red"); | |||
break; | |||
case "blue": | |||
console.log("color2 is blue"); | |||
break; | |||
default: | |||
console.log("color2 is not red or blue"); | |||
} | |||
</syntaxhighlight> | |||
===== For Loops ===== | |||
iterate through indices | |||
<syntaxhighlight lang="JavaScript"> | |||
for (let i = 0; i <= 10; i++) { | |||
console.log(`For Loop Number:${i}`); | |||
} | |||
/* | |||
Output: | |||
For Loop Number:0 | |||
For Loop Number:1 | |||
For Loop Number:2 | |||
For Loop Number:3 | |||
For Loop Number:4 | |||
For Loop Number:5 | |||
For Loop Number:6 | |||
For Loop Number:7 | |||
For Loop Number:8 | |||
For Loop Number:9 | |||
For Loop Number:10 | |||
*/ | |||
const todos = [ | |||
{ | |||
id: 1, | |||
text: "Take out trash", | |||
inCompleted: true, | |||
}, | |||
{ | |||
id: 2, | |||
text: "Meeting with boss", | |||
inCompleted: true, | |||
}, | |||
{ | |||
id: 3, | |||
text: "Dentist appt", | |||
inCompleted: true, | |||
}, | |||
]; | |||
for (let i = 0; i < todos.length; i++) { | |||
console.log(todos[i].text); | |||
} | |||
/* | |||
Output: | |||
Take out trash | |||
Meeting with boss | |||
Dentist appt | |||
*/ | |||
for (let todo of todos) { | |||
console.log(todo.text); | |||
console.log(todo.id); | |||
} | |||
/* | |||
Output: | |||
Take out trash | |||
1 | |||
Meeting with boss | |||
2 | |||
Dentist appt | |||
3 | |||
*/ | |||
</syntaxhighlight> | |||
===== While Loops ===== | |||
<syntaxhighlight lang="JavaScript"> | |||
//While | |||
let j = 0; | |||
while (j < 5) { | |||
console.log(`While Loop Number:${j}`); | |||
j++; | |||
} | |||
/* | |||
Output: | |||
While Loop Number:0 | |||
While Loop Number:1 | |||
While Loop Number:2 | |||
While Loop Number:3 | |||
While Loop Number:4 | |||
*/ | |||
</syntaxhighlight> | |||
===== Falsy Value ===== | |||
null, undefined, 0, an empty string "", NaN, and false are falsy value,all other values are considered truthy. | |||
===== Logical Operators ===== | |||
{| class="wikitable" | |||
|- | |||
! Operators !! Description !! Sample | |||
|- | |||
|style="text-align: center"| <syntaxhighlight lang="JavaScript">&&</syntaxhighlight> | |||
|style="text-align: center"|AND | |||
|<syntaxhighlight lang="JavaScript"> | |||
console.log(true && true); // Output: true | |||
console.log(true && false); // Output: false | |||
console.log(false && true); // Output: false | |||
console.log(false && false); // Output: false | |||
</syntaxhighlight> | |||
|- | |||
|style="text-align: center"| <syntaxhighlight lang="JavaScript">||</syntaxhighlight> | |||
|style="text-align: center"|OR | |||
|<syntaxhighlight lang="JavaScript"> | |||
console.log(true || true); // Output: true | |||
console.log(true || false); // Output: true | |||
console.log(false || true); // Output: true | |||
console.log(false || false); // Output: false | |||
</syntaxhighlight> | |||
|- | |||
|style="text-align: center"| <syntaxhighlight lang="JavaScript">!</syntaxhighlight> | |||
|style="text-align: center"|NOT | |||
|<syntaxhighlight lang="JavaScript"> | |||
console.log(!true); // Output: false | |||
console.log(!false); // Output: true | |||
</syntaxhighlight> | |||
|- | |||
|} | |||
== WEEK 8 == | |||
=== matter.js === | |||
====Reference ==== | |||
*[https://brm.io/matter-js/ Homepage of mattter.js] | |||
*[https://www.awwwards.com/websites/matterjs/ Matter.js Website examples] | |||
*[https://brm.io/matter-js/demo/#svg SVG effect example] | |||
*reference<code><script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.18.0/matter.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script></code>in<head>section | |||
== WEEK 9 == | |||
=== Arrow functions Call back Map Fliter=== | |||
====Arrow functions==== | |||
Basic syntax: | |||
<syntaxhighlight lang="JavaScript"> | |||
const functionName = (parameters) => { | |||
// function body | |||
}; | |||
</syntaxhighlight> | |||
Sample: | |||
<syntaxhighlight lang="JavaScript"> | |||
const add = (a, b) => { | |||
return a + b; | |||
}; | |||
console.log(add(2, 3)); // Output: 5 | |||
</syntaxhighlight> | |||
====Array prototype methods==== | |||
<syntaxhighlight lang="JavaScript"> | |||
const numbers = [1, 2, 3, 4, 5]; | |||
// 1. Map: Double each number | |||
const doubledNumbers = numbers.map((num) => num * 2); | |||
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10] | |||
// 2. Filter: Keep only the even numbers | |||
const evenNumbers = numbers.filter((num) => num % 2 === 0); | |||
console.log(evenNumbers); // Output: [2, 4] | |||
</syntaxhighlight> | </syntaxhighlight> | ||
== Appendix == | == Appendix == | ||
=== Git Basic === | |||
# Navigate to the target directory, use<code>git init</code>turns current directory into git repo | |||
# Stage Changes:Use<code>git add . </code>to add all changes in the current directory and its subdirectories | |||
# Commit the Changes:<code>git commit -m "Some commit message here"</code> | |||
# View the commit log<code>git log</code> | |||
# Handy commands see branches:<code>git branch</code> switch to existing branch:<code>git checkout [branch-name]</code>create and checkout new branch:<code>git checkout -b [branch-name]</code> | |||
=== Punctuation Mark === | === Punctuation Mark === | ||
{| class="wikitable" | {| class="wikitable" |
Latest revision as of 18:58, 9 March 2024
WEEK 12
Saturday 9 December
basic HTML Structure
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My First HTML Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<!-- Content of the page goes here -->
</body>
compare Block-Level Elements&Inline Elements
Block-Level Elements | Inline Elements | |
---|---|---|
Structure | Each block-level element generate a block-level container that takes up the full width available. | They do not create a new line,they flow within the context. |
Examples | <div> , <p> , <h1> to <h6> , <ul> , <table>
|
<span> , <a> , <strong> , <img> , <br>
|
Header Section
<!-- Header Section -->
<header>
<h1>Website Name</h1>
<nav>
<!-- Navigation Links -->
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
</header>
<!-- Footer Section -->
<footer>
<p>© 2023 Website Name. All rights reserved.</p>
</footer>
WEEK 13
Wednesday 13 December
Add Links
<!-- title attribute -->
<a href="https://www.examples.com title="Example webpage">Look at examples</a>
<!-- target attribute -->
<a href="https://www.example.com" target="_self">open on the same page</a>
<a href="https://www.example.com" target="_blank">open in new tab</a>
<!-- relative paths -->
<a href="/about">About Us</a>
<a href="/">Home</a>
<!-- link to E-mail -->
<a href=mailto:information@example@.com>Email Us</a>
<!-- link to Sections within the Same Page -->
<h1 id="top">Header1</h1>
<a href="#top">Go back to Top</a>
Add Images
<!-- basic syntax -->
<img src="example/imagines.jpg" alt="example image">
<!--width and height Attributes -->
<img src="example.jpg" alt="An example image" width="300" height="200">
<!-- add image as link -->
<a href="https://www.example.com">
<img src="example/imagines.jpg" alt="Description of the image">
</a>
Thursday 14 December
Basic Structure of CSS
/* Element Selector */
p {
color: blue;
}
/* Class Selector */
.highlight {
background-color: yellow;
}
/* ID Selector */
#header {
font-size: 24px;
}
3 Feb
Basic Properties of CSS
WEEK 7
Basics JavaScript
The placement of JavaScript within an HTML
<!-- Inside <head> tags, allows the browser to load the script before rendering the page content -->
<head>
<script src="script.js"></script>
</head>
<!-- Inside <body> tags before closing </body> tag allow the page content to load before executing the scripts-->
<body>
<!-- Page content -->
<script src="script.js"></script>
</body>
Use Node.js
Node.js is a runtime environment that could run JavaScript code outside of a web browser, on servers or other devices.Open your terminal,navigate to the directory
node example.js
5 primitive data types
Name | Description | Sample |
---|---|---|
string | a sequence of characters enclosed in single quotes (') or double quotes (") used to represent text data | let greeting = 'Hello, world!';
console.log(typeof greeting); // Output: string
let name = "Zuzu S";
console.log(typeof name); // Output: string
|
number | Numeric data, can be integers or floating-point numbers | let age = 30;
console.log(typeof age); // Output: number
let pi = 3.14;
console.log(typeof pi); // Output: number
|
boolean | a logical value, either true or false. | let isAdult = true;
console.log(typeof isAdult); // Output: boolean
let hasPermission = false;
console.log(typeof hasPermission); // Output: boolean
|
null | a variable has no value or points to nothing | let car = null;
console.log(typeof car); // Output: object
|
undefined | a variable that has been declared but has not been assigned a value, it is the default value of variables in JavaScript that have not been initialized. | let x;
console.log(typeof x); // Output: undefined
let y = undefined;
console.log(typeof y); // Output: undefined
|
comparison operators
//Equal (==):Checks if two values are equal in terms of value, but does not check for data type.
console.log(5 == 5); // true
console.log(5 == '5'); // true (coerced to the same type)
console.log(5 == 7); // false
//rict Equal (===):Checks if two values are equal in both value and data type.
console.log(5 === 5); // true
console.log(5 === '5'); // false (different types)
//Not Equal (!=)
console.log(5 != 7); // true
console.log(5 != 5); // false
//Strict Not Equal (!==)
console.log(5 !== '5'); // true (different types)
console.log(5 !== 5); // false
//Greater Than (>) and Greater Than or Equal To (>=)
console.log(5 > 3); // true
console.log(5 >= 5); // true
var,let,const
var: variables is function-scoped. That they are accessible anywhere within the function or global scope in which they are declared.
function example() {
var x = 10;
if (true) {
var y = 20;
}
console.log(x); // Output: 10
console.log(y); // Output: 20
}
let: variables declared with let are block-scoped, they are only accessible within the block (enclosed by curly braces)
function example() {
let x = 10;
if (true) {
let y = 20;
console.log(x); // Output: 10
console.log(y); // Output: 20
}
console.log(x); // Output: 10
console.log(y); // Error: y is not defined
}
const: means constant, variables declared with const are block-scoped like let, but they must be initialized with a value, and once declared, their value cannot be re-assigned.
function example() {
const x = 10;
// x = 20; // Error: Assignment to constant variable
console.log(x); // Output: 10
}
//for objects and arrays declared with const, their properties or elements can still be modified, but the variable itself cannot be re-assigned.
const person = {
name: 'John',
age: 30
};
person.age = 31; // Valid
console.log(person); // Output: { name: 'John', age: 31 }
// person = {}; // Error: Assignment to constant variable
Common JavaScript Syntax Symbol
Syntax
//this function finds the GCD of two numbers
const greatestCommonDivisor = (a, b) => {//Curly braces denote where blocks begin and end.
while (b !== 0) {
const temp = b;//Every statement in JavaScript ends with a semicolon;
b = a % b;
a = temp;
}
return a;
}
const x = 50;
const y = 15;
const gcd = greatestCommonDivisor(x, y);//output:5
Symbol | Description | Sample |
---|---|---|
( ) | Function Invocation: Call a function and execute its code, use parentheses after the function name with optional arguments inside. | function example() {
let x = 10;
if (true) {
let y = 20;
console.log(x); // Output: 10
console.log(y); // Output: 20
}
|
Grouping Expressions: Parentheses can be used to group expressions and control the order of evaluation in complex expressions. | let result = (2 + 3) * 4; // Result: 20
}
| |
Function Declarations and Definitions: When declaring or defining functions, enclose the parameters and the function body within parentheses. | let add = (a, b) => {
return a + b;
};
| |
{ } | Function and Control Structures:: Curly braces define the scope of function bodies, control structures like if, for, while loops, and blocks of code in general. | function example() {
let x = 10;
if (true) {
let y = 20;
console.log(x); // Output: 10
console.log(y); // Output: 20
}
|
Object Literals: Define object literals, which are key-value pairs enclosed within curly braces. | let person = {
name: 'John',
age: 30
};
| |
[ ] | Array access: Access elements in an array by their index. | const numbers1 = [1,2,3];
console.log(numbers1[0]);//Output: 1
|
Computed property names: in object literals, the value of propertyName is used as the property name for the person object. | const propertyName = 'name';
const person = {
[propertyName]:'John'
};
console.log(person.name);// Output: John
|
Template Strings
a convenient way to create strings
const username = "KK";
const age = 30;
console.log(`My name is ${username} and I am ${age} years old.`); // Output: My name is KK and I am 30 years old.
const hello = `My name is ${username} and I am ${age} years old.`;
console.log(hello); // Output: My name is KK and I am 30 years old.
String Operations
various methods to manipulate strings
const s = "hello world";
console.log(s.length); // Output: 11
console.log(s.toLowerCase()); // Output: hello world
console.log(s.toString()); // Output: hello world
console.log(s.substring(1, 5).toUpperCase()); // Output: ELLO
console.log(s.split("")); // Output: ["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]
const k = "under,make,call";
console.log(k.split(",")); // Output: ["under", "make", "call"]
Arrays
Arrays are used to store multiple values in a single variable and can hold different types of data, including numbers, strings, and even other arrays.
const fruits = ["apple", "pear", "banana"];
//add to end
fruits.push("mango");
console.log(fruits); // Output: ["apple", "pear", "banana", "mango"]
//add at beginning
fruits.unshift("grapes");
console.log(fruits); // Output: ["grapes", "apple", "pear", "banana", "mango"]
//remove from end
fruits.pop();
console.log(fruits); // Output: ["grapes", "apple", "pear", "banana"]
console.log(fruits.indexOf("mango")); // Output: -1 (as "mango" is no longer in the array after pop)
console.log(Array.isArray(fruits)); // Output: true
console.log(fruits[1]); // Output: apple
Array Declaration
// Array Declaration
const todos = [
{
id: 1,
text: "Take out trash",
inCompleted: true,
},
{
id: 2,
text: "Meeting with boss",
inCompleted: true,
},
{
id: 3,
text: "Dentist appt",
inCompleted: true,
},
];
// Accessing Array Elements
console.log(todos[1].text); // Output: Meeting with boss
//Replace
todos[1].text = "Shopping";
// JSON Serialization
//Convert the todos array into a JSON string and store it in the constant variable todoJSON.
const todoJSON = JSON.stringify(todos);
console.log(todoJSON);
Object
a collection of name:value pairs
const person = {
firstName: "KK",
lastName: "ÖO",
age: 30,
hobbies: ["music", "movies"],
address: {
street: "50 main st",
city: "Boston",
state: "MA"
}
};
//Accessing properties
console.log(person.firstName); // Output: KK
console.log(person.["hobbies"]); // Output: ['music', 'movies']
// Object destructuring
// A shorthand to obtain multiple properties at once
const { firstName, lastName, address: { city } } = person;
console.log(firstName); // Output: KK
console.log(lastName); // Output: ÖO
console.log(city); // Output: Boston
// Property assignment
person.email = "kk@gmail.com";
console.log(person) // Output: Complete person object with added email property
Object references
Object variables are references, they do not store the object's data directly but store a reference to the location where the object's data is stored.
let person1 = { name: "kk" };
let person2 = { name: "kk" };
console.log(person1 === person2); // Output: false
JS Function Syntax
Functions are values that are stored in memory, just like strings, integers, objects, and other data types. This means we can assign variables to point to functions.
//Basic syntax
(parameters) => { body };
//here is a function to find the greatest common divisor of a and b
(a, b) => {
while (b !== 0) {
const temp = b;
b = a % b;
a = temp;
}
return a;
}
//we could assign the function to a variable,we could name variable:greatestCommonDivisor,and then use const to point to the function
const greatestCommonDivisor = (a, b) => {
const temp
b = a % b;
a = temp;
}
return a;
};//end with a semicolon because it's a variable
Copying arrays and objects
One way is to use the spread operator (...)
const originalArray = [1, 2, 3];
const copyArray = [...originalArray];
const originalObject = { key1: 'value1', key2: 'value2' };
const copyObject = { ...originalObject };
Conditional Statements (if-else)
Extract values from objects and assign them to variables
if (U === 10) {
console.log("U is 10");
} else if (U > 10) {
console.log("U is greater than 10");
} else {
console.log("U is less than 10"); // Output: U is less than 10
}
Ternary Operator
a shorthand for an if-else statement
/*
Syntax: condition ? expression1 : expression2
If the condition evaluates to true, expression1 is executed; otherwise, expression2 is executed.
In this case, e > 10 is the condition. If e is greater than 10, "red" is assigned to color1; otherwise, "blue" is assigned.
*/
const e = 10;
const color1 = e > 10 ? "red" : "blue";
console.log(color1); // Output: blue
Switch Statement
switch (color2) {
case "red":
console.log("color2 is red");
break;
case "blue":
console.log("color2 is blue");
break;
default:
console.log("color2 is not red or blue");
}
For Loops
iterate through indices
for (let i = 0; i <= 10; i++) {
console.log(`For Loop Number:${i}`);
}
/*
Output:
For Loop Number:0
For Loop Number:1
For Loop Number:2
For Loop Number:3
For Loop Number:4
For Loop Number:5
For Loop Number:6
For Loop Number:7
For Loop Number:8
For Loop Number:9
For Loop Number:10
*/
const todos = [
{
id: 1,
text: "Take out trash",
inCompleted: true,
},
{
id: 2,
text: "Meeting with boss",
inCompleted: true,
},
{
id: 3,
text: "Dentist appt",
inCompleted: true,
},
];
for (let i = 0; i < todos.length; i++) {
console.log(todos[i].text);
}
/*
Output:
Take out trash
Meeting with boss
Dentist appt
*/
for (let todo of todos) {
console.log(todo.text);
console.log(todo.id);
}
/*
Output:
Take out trash
1
Meeting with boss
2
Dentist appt
3
*/
While Loops
//While
let j = 0;
while (j < 5) {
console.log(`While Loop Number:${j}`);
j++;
}
/*
Output:
While Loop Number:0
While Loop Number:1
While Loop Number:2
While Loop Number:3
While Loop Number:4
*/
Falsy Value
null, undefined, 0, an empty string "", NaN, and false are falsy value,all other values are considered truthy.
Logical Operators
Operators | Description | Sample |
---|---|---|
&&
|
AND | console.log(true && true); // Output: true
console.log(true && false); // Output: false
console.log(false && true); // Output: false
console.log(false && false); // Output: false
|
||
|
OR | console.log(true || true); // Output: true
console.log(true || false); // Output: true
console.log(false || true); // Output: true
console.log(false || false); // Output: false
|
!
|
NOT | console.log(!true); // Output: false
console.log(!false); // Output: true
|
WEEK 8
matter.js
Reference
- Homepage of mattter.js
- Matter.js Website examples
- SVG effect example
- reference
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.18.0/matter.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
in<head>section
WEEK 9
Arrow functions Call back Map Fliter
Arrow functions
Basic syntax:
const functionName = (parameters) => {
// function body
};
Sample:
const add = (a, b) => {
return a + b;
};
console.log(add(2, 3)); // Output: 5
Array prototype methods
const numbers = [1, 2, 3, 4, 5];
// 1. Map: Double each number
const doubledNumbers = numbers.map((num) => num * 2);
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
// 2. Filter: Keep only the even numbers
const evenNumbers = numbers.filter((num) => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]
Appendix
Git Basic
- Navigate to the target directory, use
git init
turns current directory into git repo - Stage Changes:Use
git add .
to add all changes in the current directory and its subdirectories - Commit the Changes:
git commit -m "Some commit message here"
- View the commit log
git log
- Handy commands see branches:
git branch
switch to existing branch:git checkout [branch-name]
create and checkout new branch:git checkout -b [branch-name]
Punctuation Mark
Punctuation Mark | English Name |
---|---|
. | Full Stop |
, | Comma |
; | Semicolon |
: | Colon |
' | Apostrophe /əˈpɒstrəfi/(Single Quote) |
" | Quotation Mark (Double Quote) |
` | Backtick |
( | Opening Parenthesis |
) | Closing Parenthesis |
[] | Square Bracket |
{} | Curly Brace |
/ | Forward Slash |
\ | Backslash |
* | Asterisk/ˈæstərɪsk/ |
& | Ampersand/ˈæmpəsænd/ |
# | Hash (Octothorpe) |
< | Less Than |
> | Greater Than |
| | Pipe (Vertical Bar) |
! | Exclamation Mark /ˌekskləˈmeɪʃn/ |
˜ | Tilde /ˈtɪldə/ |
- | Hyphen (Minus) |
_ | Underscore |
Set up automatic synchronization
Using automatic synchronization between Visual Studio Code and Firefox using GitHub and BrowserSync. -Set up a GitHub Repository
-Clone the Repository:
git clone https://github.com/blacktableone/SI23
-Install BrowserSync:
npm install -g browser-sync
-Navigate to project directory
-Initialize a package.json file:
npm init -y
-Install BrowserSync:
npm install browser-sync --save-dev
-Create a bs-config.js file in project directory:
code bs-config.js
-Add the following configuration to bs-config.js:
module.exports = {
server: {
baseDir: "./"
},
files: ["*.html", "*.css", "*.js"]
};
-In project directory,run BrowserSync:
browser-sync start --config bs-config.js