JavaScript Lesson notes
Javascript lesson notes.
- Variables
- Data types- there are 8 JS data types.
- 1. String: a series of characters, written with single or double quotes
- 2. Number: can be integers or decimals.
- 3. Bigint: used to store integer values that are too big to be represented by a normal JS number
- 4. Boolean: true or false, used in conditional testing
- 5. Undefined: a variable without a value, has the value undefined/empty values
- 6. Null: represents the intentional absence of any object value
- 7. Symbol: used to represent unique values that can be used as identifiers/keys in objects.
- 8. Object: an unordered collection of key-value pairs. Each key-value pair is called a property.
- Const
- Conditionals: control behavior, decides whether or not pieces of code can run.
- Functions:
- Iteration:
- JavaScript in HTML - Questions
- Hacks
var x = 5;
var y = 6;
var z = x + y;
z
let text = "Mort";
text
let text2 = 'Yeung';
text2
let number = 1234567890123456789012345n;
let Largenum = BigInt(1234567890123456789012345)
let typeLargenum = typeof Largenum;
typeLargenum
Largenum
Boolean(10 > 9)
Write a boolean statement that outputs true.
Boolean(50000 == 50000)
let name;
name
grade = undefined;
let result;
result = Boolean(undefined);
console.log(result); // false
result = Boolean(null);
console.log(result); // false
7. Symbol: used to represent unique values that can be used as identifiers/keys in objects.
- They are also used to create private properties and methods in classes.
- unique and immutable, so they can be used as unique identifiers in objects and classes.
- useful for creating constants that can be shared across different parts of your code.
// Create a Symbol
const mySymbol = Symbol();
console.log(mySymbol);
// expected output: Symbol()
const myObject = {
[mySymbol]: 'Hello World'
};
console.log(myObject);
Edit/add to the code above so that it outputs "Hello World"
Object
- Identify the name/keys in the object below: name, breed, age, color
- Identify the values in the object below: "Elly", "Rottweiler", 4, "black"
const dogs = {name: "Elly", breed:"Rottweiler", age:4, color:"black"}
dogs
Array
const songs = ["Love Story", "Blank Space", "I Knew You Were Trouble"];
songs
const cost1 = 2;
const cost2 = 11;
let totalCost = cost1 + cost2;
totalCost
if (10 > 5) {
var outcome = "True";
}
outcome;
if ("red" === "blue") {
var outcome = "if block";
} else {
var outcome = "else block";
}
outcome;
let temperature = 54
if (temperature < 70) {
cast = "Chilly";
} else if (temperature < 60) {
cast = "Cold";
} else {
cast = "Warm";
}
cast
Create a conditional statement about how you would greet someone based on the time of day.
function greeting(time) {
if (time < 5) {
console.log("What are you doing up this early?");
} else if (time < 12) {
console.log("Good morning!");
} else if (time < 17) {
console.log("Good afternoon.");
} else if (time < 20) {
console.log("Good evening.");
} else {
console.log("Goodnight!");
}
}
greeting(13)
Iteration:
- for loop: repeats until a specified condition evaluates to false
- do...while: repeats until a specified condition evaluates to false
- while statement: executes its statements as long as a specified condition evaluates to true
- label: provides a statement with an identifier that lets you refer to it later in the code. ex. you can use a label to identify a loop, and then use the break or continue statements to indicate whether a program should interrupt the loop or continue its execution
- break: used to terminate a loop, switch, or in conjunction with a labeled statement
- continue: can be used to restart a while, do-while, for, or label statement
- for...in: iterates a specified variable over all the enumerable properties of an object
- for...of statement creates a loop Iterating over iterable objects, invoking a custom iteration hook with statements to be executed for the value of each distinct property
JavaScript in HTML - Questions
- Where do you store the JavaScript Code?
JavaScript code can be stored in .js
files or between <script>
tags in HTML.
- How do you import a JS file into HTML?
<script src="scriptname.js"></script>
- What is onClick?
onClick describes the behavior or a certain element when it is clicked on.
- What tag do you use to write JavaScript code?
<script>
class NewClass {
constructor(thing1, thing2) { //rather than "__init__"
this.thing1 = thing1; //this. instead of self.
this.thing2 = thing2;
};
getThings() {
return [this.thing1, this.thing2];
}
}
obj = new NewClass("Thing1", "Thing2");
console.log(obj.getThings());
- JavaScript is intended to be used in tandem with HTML, so there are some functions that can be used on a webpage to receive user input:
-
prompt()
, for example, brings up a page on the site itself
-
- JavaScript actually CAN use the
for [thing] in [thing]
format with its for loop! It just works a little bit different, where it reads the key of each list item rather than each item's value. You can do something similar to a regular list below:
listex = ["Thing1", "Thing2", "Thing3"];
for (index in listex) {
console.log(listex[index]);
}
dictex = {att1:"Value1", att2:"Value2", att3:"Value3"};
for (key in dictex) {
console.log(key + ": " + dictex[key]);
}
- Complete the code portions, questions, and prompts throughout the notebook
Done.
- Extra Credit: code a small JavaScript game
I decided to code rock-paper-scissors. The raw JavaScript code is right below the game itself.
Choose rock, paper or scissors!
Current streak: 0
const sBox = document.getElementById('status-box');
const streakB = document.getElementById('current-streak');
var streak = 0;
var choice = 0;
var opposition = 0;
var oppList = ["rock", "paper", "scissors"]
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
function rock() {battle(0)}; //onclick function of rock button
function paper() {battle(1)}; //onclick function of paper button
function scissors() {battle(2)}; //onclick function of scissors button
function win(opp) {
streak += 1;
streakB.innerHTML = "Current streak: " + String(streak);
sBox.innerHTML = "I picked " + oppList[opp] + "... You won! Click a button to play again.";
}
function lose(opp) {
streak = 0;
streakB.innerHTML = "Current streak: 0";
sBox.innerHTML = "I picked " + oppList[opp] + ", so I win! Click a button to play again.";
}
function tie(opp) {
sBox.innerHTML = "I picked " + oppList[opp] + " too, so you keep your streak! Click a button to play again.";
}
function battle(choice) {
opposition = getRandomInt(3); //0 = rock, 1 = paper, 2 = scissors
if ((choice - opposition == -1) || (choice - opposition == 2)) {
lose(opposition);
return;
} else if ((choice - opposition == 1) || (choice - opposition == -2)) {
win(opposition);
return;
} else {
tie(opposition);
}
}