0% found this document useful (0 votes)
3 views

Getting started with JS Part ONE

Uploaded by

AC Chandler
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Getting started with JS Part ONE

Uploaded by

AC Chandler
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Getting Started with Javascript

Part ONE
HTML

CSS

Javascript

Front-end
By the end of this class, you should:

● Feel comfortable working with Javascript variables and data types


● Feel comfortable working with numbers and strings in Javascript
● Feel comfortable working with conditionals (if-else and switch statements)
in Javascript
● Feel comfortable working with arrays and loops in Javascript
● Feel comfortable working with functions in Javascript
JS makes web pages interactive and dynamic
Demo: Using MDN for reference
Getting comfortable with strings
1 const firstName = “Nelly”;
2 const lastName = “Sugu”;
3 const fullName = firstName + “ ” + lastName; // string concatenation

Line 3 is the same as:


● const fullName = firstName.concat(“ ”, lastName); //concat() string function
● const fullName = `${firstName} ${lastName}`; // template literal

Syntaxes recap:
● const someString = “I am a string because I am inside of double quotes.”
● const anotherString = ‘I am also a string because I am inside of single
quotes’
● Template literal: `In a string you can embed a ${variableName} like this`
String: sequence of characters positioned by index from 0
const bootcampName = “TLG APPRENTI”
bootcampName: T L G A P P R E N T I

index: 0 1 2 3 4 5 6 7 8 9 10 11

● bootcampName[0] = ? ● bootcampName[bootcampName.length]= ?
○ “T” ○ undefined
● bootcampName[3] = ? ● bootcampName[bootcampName.length - 1]
○ “” =?
● bootcampName[12] = ? ○ “I”
○ undefined ● bootcampName.charAt(3) = ?
● bootcampName.length = ? ○ “”

○ 12 ● bootcampName.charAt(12) = ?
○ undefined
MDN String methods (20 min)
● concat()
● includes()
● indexOf()
● lastIndexOf()
● replace()
● slice()
● startsWith()
● endsWith()
● substring()
● toLowerCase()
● toUpperCase()
● trim()
You do: Practice with JS Numbers and Math (20 min)
● In your VSCode, practice using the following JS built-in functions

● Number.parseInt() ● Math.floor()
● Number.parseFloat() ● Math.ceil()
● Number.toFixed() ● Math.random()
● Number.toPrecision()
● Number.toString()
Conditionals: used to do something and not something else
User visits page

NO YES
Is logged in?

Show Show
sign-in profile
page page
If-Else syntax
if (CONDITION1){ // Do this stuff when CONDITION1 is true }

else if (CONDITION2){ // Do this stuff when CONDITION1 is false but


CONDITION2 is true }

else { // When none of the conditions above has been met, do this stuff }
Switch-Case syntax
switch (valueToTest){

case possibleValue1:

// Do this stuff when valueToTest is possibleValue1

break;

default:

// Do this stuff when valueToTest hasn’t matched any of of the cases

break;

}
Code along: Message-By-Age (if-else) (15 min)
● Use the if-else conditional statements to create a web page that prompts a user
for their age and pops up an alert with a greeting message specific to their age.
Example greeting can be “hi toddler” (get creative). Below are the age groups.
○ [0 - 1 ] : baby
○ ]1 - 3 [ : toddler
○ [3 - 5 [ : preschooler
○ [5 - 12 [ : gradeschooler
○ [12 - 18 [ : teen
○ [18 - 21 [ : young adult
○ 21 and above : adult
● Bonus: Get the user’s age from an input field, run your script when the user clicks
a button on your page and display the message on the page instead of in an alert
pop-up box
Array: list of things arranged by index from 0
const myToys = [ “Jeep”, “motorcycle”, “yacht”, “private jet” ];

myToys:

index: 0 1 2 3

● myToys.length = ? ● myToys[myToys.length - 1] = ?
○ 4 ○ “private jet”
● myToys[myToys.length] = ? ● myToys[1] = ?
○ undefined ○ “motorcycle”
You do: Creating array and accessing items with index (10 min)

● In your Chrome Dev Tools Console, create a string variable named


hobbiesStr with all of your hobbies where hobbies are comma separated
● Look up the split() string method and use it to create an array of your hobbies
called hobbies
● Practice getting the number of items in your array
● Practice accessing any item in your array
Intro to array methods (20 min)
● includes()
● indexOf()
● join() (which string method is it the inverse of?)
● lastIndexOf()
● pop()
● push()
● reverse()
● shift()
● unshift()
● slice()
● splice()
Demo: From while loop to for-loop

SAME

idx++

idx = idx + 1
For loop has 4 main blocks
BLOCK 1 BLOCK 2 BLOCK 3

BLOCK 4

BLOCK 1 BLOCK 2 is the BLOCK 3 BLOCK 4


executes ONLY condition for executes EVERY executes OVER
ONCE before at executing BLOCK TIME after AND OVER as
the beginning 4. The loops stop BLOCK 4 has long as BLOCK 2
before any other running when executed is true
block BLOCK 2 is false
Other way to loop over an array or string: for/of
1 const numbers = [10, 20, 30]; 1 const country = “Bermuda”;
2 for (let num of numbers){ 2 for (let letter of country){
3 console.log(num); 3 console.log(letter);
4} 4}
5 // 10 5 // B
6 // 20 6 // e
7 // 30 7 // r
8 // m
9 // u
10 // d
11 // a
Loop the triangle
Write a loop that makes seven calls to console.log to output the following triangle

Hint: remember what the .length string method can do for you
FizzBuzz

Write a program that uses console.log to print all the numbers from 1 to 100, with two
exceptions. For numbers divisible by 3, print "Fizz" instead of the number, and for numbers
divisible by 5 (and not 3), print "Buzz" instead.

When you have that working, modify your program to print "FizzBuzz" for numbers that are
divisible by both 3 and 5 (and still print "Fizz" or "Buzz" for numbers divisible by only one of
those).
Chessboard (bonus)

Write a program that creates a string that represents an 8×8 grid, using newline characters to
separate lines. At each position of the grid there is either a space or a "#" character. The characters
should form a chessboard. Passing this string to console.log should show something like this:
Demo: Intro to JS functions
1 const array1 = [1, 2, 3];
2 let sum1 = 0;
array 1 let sum = 0; sum
3 for (let i = 0; i < array1.length; i++){ 2 for (let i=0; i < array.length; i++){
4 sum1 += array1[i]; 3 sum += array[i];
5 } 4}
6 console.log(sum1); // 6 5 return sum;
7
1 const array1 = [1, 2, 3]; function getSum(array){
8 const array2 = [9, 10, 11, 5];
2 const sum1 = let sum = 0;
9 let sum2 = 0; for (let i=0; i<array.length, i++){
10 for (let i = 0; i < array2.length; i++){ getSum(array1);
sum += array[i];
11 sum2 += array2[i]; 3 console.log(sum1); // 6 }
12 } 4 return sum;
13 console.log(sum2); // 35 5 const array2 = [9, 10, 11, 5]; }
6 const sum2 =
getSum(array2);
7 console.log(sum2); // 35
Demo: Syntax of JS Functions
// Function definition
function exampleFunc(arg1, arg2, arg3, …){ arg1
let output;
arg2 output
// Use arg1, arg2, arg3 to calculate output exampleFunc
return output; arg3
}

// Function call
exampleFunc( 1 , “Nelly” , [10,20,30] );

// Function definition
function anotherFunc( ){
// Takes NO arguments
randomNum
const randomNum = Math.random(); anotherFunc
return randomNum;
}

// Function call
anotherFunc();
Syntax of JS Functions (cont.)
// Function definition
function noArgsNoReturn( ){
// Takes NO arguments
const randomNum =
Math.random();
noArgsNoReturn
console.log(randomNum);
// Does not return anything
}
// Function call
noArgsNoReturn();
You do: Figure out what an arrow function is in JS
(10 min)
● Function declaration
● Function expression
● Anonymous function
Sum of range

Write a range function that takes two arguments, start and end, and returns an array containing
all the numbers from start up to (and including) end.

console.log(range(1, 10)) => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Next, write a sum function that takes an array of numbers and returns the sum of these numbers.

console.log(sum(range(1, 10))) => 55


Sum of range with step (bonus)
Modify your range function to take an optional third argument that indicates the “step” value used
when building the array. If no step is given, the elements go up by increments of one,
corresponding to the old behavior.

The function call range(1, 10, 2) should return [1, 3, 5, 7, 9].

Make sure it also works with negative step values so that range(5, 2, -1) produces [5, 4, 3,
2].
Array reverse
Arrays have a reverse method that changes the array by inverting the order in which its elements
appear.

Write two functions, reverseArray and reverseArrayInPlace.

reverseArray, takes an array as argument and produces a new array that has the same elements
in the inverse order.

reverseArrayInPlace, does what the reverse method does: it modifies the array given as
argument by reversing its elements.

Neither may use the standard reverse method.


Array reverse tests
console.log(reverseArray(["A", "B", "C"])) => ["C", "B", "A"];

let arrayValue = [1, 2, 3, 4, 5];

reverseArrayInPlace(arrayValue);

console.log(arrayValue) => [5, 4, 3, 2, 1]


Counting Bees

Write a function countBs that takes a string as its only argument and returns a number that
indicates how many uppercase “B” characters there are in the string.

Next, write a function called countChar that behaves like countBs, except it takes a second
argument that indicates the character that is to be counted (rather than counting only uppercase
“B” characters). Rewrite countBs to make use of this new function.

console.log(countBs(“BEEF boB”)) => 2

console.log(countChar(“Baby Barbara with a barbie”, “r”)) => 3


Review: Arrays, their syntax and indexes
● const siblingsAndRandomNumbers = [ 5, “Aimée”, 13, 0, “Liliane”, “Divine” ];
● const emptyArray = [ ];
● console.log(siblingsAndRandomNumbers[4]);
○ // “Liliane”
● console.log(siblingsAndRandomNumbers.length);
○ // 6
● siblingsAndRandomNumbers[4] = 36;
● console.log(siblingsAndRandomNumbers[4]);
○ // 36
You do: Rainbow color picker
● Our page will prompt the user for a color and if that color is one of the rainbow colors, it
will alert that color’s hex code.

● When the user enters an input that’s not one of the rainbow colors, our page will alert
them with a message (“Not a rainbow color”)

BONUS 1: Change the body’s background color to the chosen color

BONUS 2: When the user enters the word “random”, our page will generate them a random
color with a valid hex code (NOT just the rainbow colors, ANY color that’s valid in the whole
color spectrum) => #RRGGBB Where R, G, B are characters in 0 1 2 3 4 5 6 7 8 9 A B C D E
F

Bonus 3 : Get the color from an input field, run your script when the user clicks a button
on your page and display the message on the page instead of in an alert pop-up box
Review: Rainbow color picker (if-else)
● Syntax:

if (CONDITION1){ // Do this stuff when CONDITION1 is true }

else if (CONDITION2){ // Do this stuff when CONDITION1 is false but


CONDITION2 is true }

else { // When none of the conditions above has been met, do this stuff }

● = vs == vs ===
Popcorn: What did you retain
● What is a variable?
● When do you use a variable in Javascript?
● What are the primitive data types in Javascript?
● What is a string?
● How do you define a string in Javascript?
● How do you access a character in a string when you know its index?
● What are some string functions you remember and what do they do?
● What are arrays?
● When do you define an array in Javascript?
● How do you access an array element when you know its index?
Popcorn: What did you retain (cont.)
● What is a conditional statement and when do you use one?
● What are the 2 conditional statements in Javascript?
● What are loops and how do you them in Javascript?
● What is function?
● When do you use a function in Javascript?
● What is a function signature?
1-5 how comfortable do you feel:

● Working with Javascript variables and data types


● Working with numbers and strings in Javascript
● Working with conditionals (if-else and switch statements) in Javascript
● Working with arrays and loops in Javascript
● Working with functions in Javascript
Additional Resources
● W3School JS Practice Exercises (JS Variables, JS Operator, JS Data Types,
JS Functions, JS Strings, JS String Methods, JS Arrays, JS Array Methods,
JS Math, JS Comparisons, JS Conditions, JS Switch, JS For loops, JS While
loops, JS Break loops)
● For more practice, go to FreeCodeCamp, create an account and complete the
Basic Javascript section under the Javascript Algorithms And Data
Structures Certification module

You might also like