Variables

  • declare JavaScript variables with var, let or const.
  • If the value of the variable can change, like a total, use let. If the value is set, like prices, use const. Variables can hold any data type.
  • Once a variable has been declared, it cannot be used again - error will pop up
var x = 5;
var y = 6;
var z = x + y;

z
11

Data types- there are 8 JS data types.

  • List a few data types that you already know

    Strings

Numbers

Boolean

1. String: a series of characters, written with single or double quotes

let text = "Mort";
text
'Mort'
let text2 = 'Yeung';
text2
'Yeung'

2. Number: can be integers or decimals.

  • You can also have exponential notation for large/small numbers
  • Can be defined using variables
  • Built in object Number - can do various functions on numbers
  • Special value of Infinity and -Infinity

3. Bigint: used to store integer values that are too big to be represented by a normal JS number

  • JavaScript integers are only accurate up to 15 digits
  • Are created by appending n to an integer
  • BigInt values can be compared
  • Cannot be used with bitwise operators
const c = 12389012345;
const BigC = BigInt(789012345123);

const typeBigC = typeof BigC;
typeBigC
evalmachine.<anonymous>:2
const BigC = BigInt(789012345123);
             ^

ReferenceError: BigInt is not defined
    at evalmachine.<anonymous>:2:14
    at ContextifyScript.Script.runInThisContext (vm.js:25:33)
    at Object.runInThisContext (vm.js:97:38)
    at run ([eval]:1020:15)
    at onRunRequest ([eval]:864:18)
    at onMessage ([eval]:828:13)
    at emitTwo (events.js:106:13)
    at process.emit (events.js:191:7)
    at process.nextTick (internal/child_process.js:758:12)
    at _combinedTickCallback (internal/process/next_tick.js:73:7)

4. Boolean: true or false, used in conditional testing

  • Can be used in logical operations
  • Comparison values can return boolean
Boolean(10 > 9)
let a = 2;
let b = 5;
let boolean = b > a;
boolean

Write a boolean statement that outputs true

5. Undefined: a variable without a value, has the value undefined/empty values

  • Declared variable without assignment
  • When accessed, it will return undefined
  • typeof operator can check if a variable is undefined
  • If a variable has not been declared, it is not undefined and will give ReferenceError
let name;  
name
grade = undefined;

6. Null: represents the intentional absence of any object value

  • variable is empty at the moment and may have a value later
  • Differs from undefined in that null is explicitly set
    • Deliberate absence of value
  • Is also a false value
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 myObjects = {
    [mySymbol]: 'Hello World'
  };
  
  console.log(myObjects[mySymbol]);

Edit/add to the code above so that it outputs "Hello World"

8. Object: an unordered collection of key-value pairs. Each key-value pair is called a property.

  • object: written with curly braces {}, name:value pairs
  • array: written with square brackets, separated by commas

Object

  • Identify the name/keys in the object below: name, breed, age, oolor
  • 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

  • We use const to declare variables whose value can be initialized only at the time of declaration.
  • Const means that the identifier cannot be reassigned.
  • "Constant" Variable
  • Only accessible in block it is assigned
const cost1 = 2;
const cost2 = 11;
let totalCost = cost1 + cost2;

totalCost

Conditionals: control behavior, decides whether or not pieces of code can run.

  • If: if a condition is true it is used to specify execution for a block of code.
  • Else: if the same condition is false it specifies the execution for a block of code.
  • Else If: new test if the first condition is false.
if (10 > 5) {
    var outcome = "True";
}

outcome;
'True'
if ("red" === "blue") {
    var outcome = "if block";
} else {
    var outcome = "else block";
}
outcome;
'else block'
let temperature = 54
if (temperature < 70) {
    cast = "Chilly";
  } else if (temperature < 60) {
    cast = "Cold";
  } else {
    cast = "Warm";
  }

cast
'Chilly'

Create a conditional statement about how you would greet someone based on the time of day.

let timeOfDay = "afternoon";
if (timeOfDay == "morning") {
    greeting = "Good Morning";
  } else if (timeOfDay == "afternoon") {
    greeting = "Good Afternoon";
  } else if (timeOfDay == "evening") {
    greeting = "Good Evening";
  }

greeting
'Good Afternoon'

Functions:

  • defining: define with function + functionName(parameter) { function code }. It can be unnamed/anonymous can be defined based on a condition.
  • calling: simply put the function name with a parameter and semicolon, or a function can call itself (recursive)

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

  1. Where do you store the JavaScript Code?
    • Javascript Code is stored within the <script> tags in HTML code. JavaScript files are stored with a .js extension
  2. How do you import a JS file into HTML?
    • A JS file can be imported using the src attribute inside script tag. An example would be <script src="JavaScript.JS==js"></script>
  3. What is onClick?
    • onClick is a JavaScript event that only occurs when an element - such as a button or piece of text - is clicked on by the user. It generally causes a function to respond, or some other action. For example, when a button is clicked, the color changes color (like the light and dark mode toggle on the SASS lesson)
  4. What tag do you use to write JavaScript code?
    • The <script> tags are used to write JavaScript code within HTML code.

Hacks

  1. Add notes in this notebook
  2. Complete the code portions, questions, and prompts throughout the notebook
  3. Extra Credit: code a small JavaScript game
let Score = 0;
const WrongAnswers = "Wrong Answer";
var Answers1 = prompt("What is 5+2");
var Answers2 = prompt("What is the capital of the United States");
var Answers3 = prompt("When did World War II end?");

if (Answers1 == "7") {
    Score = Score + 1;
} 

if (Answers2 == "Washington D.C.") {
    Score = Score + 1;
} 

(Score/3 * 100) + "%";
'100%'