Andrei Fidelman

5+y experience with JavaScript

2+y experience coaching Front-End technologies

2+y hiring experience

Senior Front-End Developer at Ataccama

https://www.linkedin.com/in/andrei-fidelman

Today's Plan

10:00 - 12:00: Fundamental JavaScript building blocks 👋

12:00 - 13:00: Lunch Break 🍕

13:00 - 14:45: Advanced JavaScript blocks 🏋️‍♀️

14:45 - 15:00: Coffee break ☕️

15:00 - 17:30: Work in the project 👩‍💻

17:30 - 18:00: Final Discussion 🏁

What is JavaScript?

Behavior

Appearance

Content

JavaScript capabilities in browser

  • Add content into HTML, change existing content, change styles

  • React on User interactions: mouse clicks, cursor moving, key presses.

  • Send requests to web-pages, download and upload files

  • Show messages, keep cookies

  • Remember data

  • Access to microphone and camera

Basic JavaScript blocks

Variable

var age = 18
age = 19

let weight = 75
weight = 80

const birthday = '1.12.1990'
birthday = '1.12.2020' // Error

Basic JavaScript blocks

Data Types

type possible values example
boolean true/false const booleanVar = true
number Integeres const num = 2
null reference to a non-existent value let nullValue = null
string text const name = 'Andrei'
🙅‍♂️ symbol
 
represents an unique identifier
 
const sym = Symbol('sym')
 
object
 
data in key-value pairs and the methods to work with it
 
const user = {name: "Jake"};
 

Basic JavaScript blocks

Operators

mark name example with a = 7 and b = 2
+ Addition console.log(a + b) // 9
- Subtraction console.log(a - b) // 5
* Multiplication console.log(a * b) // 14
/ Division console.log(a / b) // 3.5
% Modulo console.log(a % b) // 1
 
** Exponentiation console.log(a ** b) // 49

Basic JavaScript blocks

Scope

console.log(x) // Error
let x = 1

Basic JavaScript blocks

Exercises

  1. Mobile Screens
    • A wine glass making machine creates one mobile screen in 5 minutes.

      • How many mobile screens does it make in an hour?

      • How many Mobile screens does it make in a day if it can only work for 7 hours?

  2. Study time
    • In the Bootcamp each week you spend 7 hours for 4 days and 3 hours for one day attending the classes. Compute the total number of hours you attend per one week and save it to a variable classHours. Make this variable a constant.

    • Let's say that every week you spend another 30% of the weekly class hours by self-studying. Compute the total number of weekly study hours and save it into a variable studyHours.

    • Compute the total number of study hours throughout the whole Bootcamp assuming that all 12 weeks have the same sum of study hours. Save the result in a variable called totalStudyTime.

    • Create a string that could eventually be displayed somewhere on the Bootcamp's website saying something like:
      Total study time: 400 hours
      Put the content of the totalStudyTime variable as the correct value inside the string. Save it in a variable studyMessage.
  3. Currency exchange
    • The current exchange rate from Czech crowns to euro is 25.695. Get a value from the user in euros and output equivalent value in Czech crowns.

Functions

function sayHi() {
  console.log('Hi')
}

sayHi() // 'Hi'



function sayHiTo(name) {
  console.log(`Hi, ${name}`)
}

sayHi() // 'Hi, undefined'
sayHi('Andrei') // 'Hi, Andrei'
const height = 170

function getMySize() {
  const weight = 80
  console.log(age, weight)
}

getMyAge()
console.log(height)
console.log(weight)

Functions

Exercises

We know from geometry that the sum of all angles in every triangle is equal to 180. Create a function that asks the user for three angles and it checks whether there can exist a triangle with these three angles.

Browser API

alert('hi! I am alert')
const promptValue = prompt('hi! I am prompt. What is your name?')

If/else

The if/else statement is one of the most common control structure you'll deal with on a daily basis in your future programmer's life.

If/else

Comparison

5 < 6 // true
6 > 5 // true
6 >= 6 // true
5 <= 5 // true
5 == 5 // true
5 == '5' // true ❗️
5 === '5' // false
5 != 4 // true
'hi' !== 'hello' // true
!true // false
true // true
0 // false
'' // false
'hi' // true
undefined // false
null // false
-1 // true
[] // true
{} // true
Number('1') // 1
+'1' // 1
Number({}) // NaN

const age = 11
age.toString() // '11'

Boolean(0) // false
!!'hi' // true

If/else

Syntax

let drinkBeer;
const myAge = 40;

if(myAge < 18) {
   drinkBeer = false;   
} else {
   drinkBeer = true;
}
  • A condition (myAge < 18)

  • The body of code that will be executed in case the condition stated in the "if block" is true (drinkBeer = false;)

  • The body of code that will be executed in case the condition stated in the "if block" is false which will then cause the "else block" to run (isGreaterThanFifty = true;)

If/else

Syntax

let drinkBeer
const myAge = 16
const beerIsNonAlcoholic = true

if(myAge > 18) {
   drinkBeer = true
} else if (beerIsNonAlcoholic) {
   drinkBeer = true
} else {
   dringBeer = false
}

If/else

Syntax

let drinkBeer
const myAge = 16
const beerIsNonAlcoholic = true

if(myAge > 18 || beerIsNonAlcoholic) { // OR
   drinkBeer = true
} else {
   dringBeer = false
}
let drinkBeer
const myAge = 16
const beerIsNonAlcoholic = true

if(myAge < 18 && !beerIsNonAlcoholic) { // AND
   drinkBeer = false
} else {
   dringBeer = true
}

If/else

Exercises

  1. Triangle
    • We know from geometry that the sum of all angles in every triangle is equal to 180. Create a function that asks the user for three angles and it checks whether there can exist a triangle with these three angles.
  2. Login
    • Create a function that will ask the user for their login and password. Check, that the password is equal to "sore-thumb-218" and if so, output "access granted." Otherwise, output "Nice try."

Switch/case

const periodOfTheDay = "afternoon";


switch(periodOfTheDay) {
 case "morning":
   console.log("good morning");
   break;
 case "afternoon":
   console.log("good afternoon");
   break;
 case "evening":
   console.log("good evening");
   break;
 default:
   console.log("hello there");   
}

Loops

A way to repeat the same code multiple times

The While Loop

While the condition is truthy, the code from the loop body is executed

while (condition) {
  // loop body
}

The While Loop

While the condition is truthy, the code from the loop body is executed

let i = 0

while (i < 3) {
  i++
}

console.log(i) // 2

The FOR Loop

for (begin; condition; step) {
  // loop body
}
for (var i = 0; i < 3; i++) {
  console.log(i)
}

The FOR Loop

for (var i = 0; i < 3; i++) {
  console.log(i)
}
begin i = 0 executes once upon entering the loop
condition i < 3 checked before every iteration. If false, the loop stops
body console.log(i) runs again and again while the condition is truthy
step i++ executes after the body on each iteration

The FOR Loop

Any of part of FOR can be skipped

let i =0

for (; i < 3; i++) {
  console.log(i)
}

The FOR Loop

Breaking the loop

for (let i = 0; i < 4; i++) {
  console.log(i) // 0 1 2
  if (i === 2) break
}

The FOR Loop

Continue to the next iteration

for (let i = 0; i < 4; i++) {
  if (i % 2 === 0) continue
  console.log(i) // 1 3
}

Loop

Summary

  • while – The condition is checked before each iteration;

  • do..while – The condition is checked after each iteration;

  • for (;;) – The condition is checked before each iteration.

Loop

Exercises

  1. Output even numbers from 0 to 10 (5mins)
  2. Repeat until the input is correct (10mins)
    • Write a loop which prompts for a number greater than 100.
    • If the visitor enters another number – ask them to input again.
    • The loop must ask for a number until either the visitor enters a number greater than 100 or cancels the input/enters an empty line.
    • Here we can assume that the visitor only inputs numbers.
    • There’s no need to implement a special handling for a non-numeric input in this task.

Arrays

Keeps data in order

Arrays

Creating

const users = []
const products = [‘apples’, ‘meat’, ‘milk’, ‘eggs’]

Arrays

Access

const products = [‘apples’, ‘meat’, ‘milk’, ‘eggs’]
console.log(products[0]) // apples
console.log(products[1]) // meat
console.log(products[3]) // eggs
console.log(products.length) // 4

Arrays

Basic methods: Add elements to the end

const products = []
console.log(products.length) // 0
products.push(‘meat’)
console.log(products.length) // 1

Arrays

Basic methods: Add elements to the start

const products = []
console.log(products.length) // 0
products.push(‘meat’)
console.log(products.length) // 1

products.unshift(‘apples’)
console.log(products.length) // 2
console.log(products) // ['apples', 'meat']

Arrays

Basic methods: Remove the last element

const products = []
console.log(products.length) // 0
products.push(‘meat’)
console.log(products.length) // 1

products.unshift(‘apples’)
console.log(products.length) // 2
console.log(products) // ['apples', 'meat']

products.pop()
console.log(products.length) // 1
console.log(products) // ['apples']

Arrays

Basic methods: Remove the first element

const products = []
console.log(products.length) // 0
products.push(‘meat’)
console.log(products.length) // 1

products.unshift(‘apples’)
console.log(products.length) // 2
console.log(products) // ['apples', 'meat']

products.shift()
console.log(products.length) // 1
console.log(products) // ['meat']

Arrays

Basic methods: Remove an element

const products = ['apples', 'meat', 'potato']
products.splice(1, 1)

console.log(['apples', 'potato'])

Arrays

Loop

const products = ['apples', 'meat']

// 👎
for (let i = 0; i < products.length; i++) {
  console.log(i) // 0 1
  console.log(products[i]) // apples meat
}

// 👍
for (let i in products) {
  console.log(i) // 0 1
  console.log(products[i]) // apples meat
} 

// 👍
for (let product of products) {
  console.log(product) // apples meat
} 

Arrays

Exercises

  1. Basic array manipulations with [5,-2,3,6,4,6,1,8,3]
    • Output the number of items in the array to the console.

    • Output the number at index 8 to the console.

    • Output the number which is exactly in the middle of the array.

    • Output the last item.

    • Delete the item at index 3 and 4

  2. Array operations

    • Create an array styles with items “Jazz” and “Blues”.

    • Append “Rock-n-Roll” to the end.

    • Replace the value in the middle by “Classics”. Your code for finding the middle value should work for any arrays with odd length.

    • Strip off the first value of the array and show it.

    • Prepend Rap and Reggae to the array.

    • Remove `Rock-n-Roll`

  3. Sum input numbers ⭐️
    • Asks the user for values using prompt and stores the values in the array.

    • Finishes asking when the user enters a non-numeric value, an empty string, or presses “Cancel”.

    • Calculates and returns the sum of array items.

Objects

To store keyed collection of various data

Objects

Literal and properties

const data = {}

const user = {
  name: ‘John’,
  age: 30
}

console.log(user.age) // 30

user.isAdmin = true

delete user.age

user["liked birds"] = true

const key = "name"
console.log(user.key) // undefined
console.log(user[key]) // 'John'

const fruit = prompt("Which fruit to buy?", "apple");
const bag = {
  [fruit]: 5, // the name of the property is taken from the variable fruit
};
console.log( bag.apple ); // 5

Objects

Property existence

const user = {};
console.log(user.noSuchProperty === undefined); // true means "no such property"

user.name = undefined
console.log(user.name === undefined); // true but the property does exist
console.log("noSuchProperty" in user) // true as well

Objects

Loop

const  user = {
  name: "John",
  age: 30,
  isAdmin: true
};

for (let key in user) {
  console.log(key);  // name, age, isAdmin
  console.log(user[key]); // John, 30, true
}

Objects and Arrays

Referenced Type of Data

Objects and Arrays

Summary

They store properties (key-value pairs), where:

  • Property keys must be strings or symbols (usually strings).

  • Values can be of any type.

To access a property, we can use:

  • The dot notation: obj.property.

  • Square brackets notation obj["property"]. Square brackets allow to take the key from a variable, like obj[varWithKey].

Additional operators:

  • To delete a property: delete obj.prop.

  • To check if a property with the given key exists: "key" in obj.

  • To iterate over an object: for (let key in obj) loop.

What we’ve studied in this topic is called a “plain object”, or just Object.

There are many other kinds of objects in JavaScript:

  • Array to store ordered data collections,

  • Date to store the information about the date and time,

  • Error to store the information about an error.

  • …And so on.

Objects and Arrays

Exercises

  1. Hello object
    • Create an empty object user.

    • Add the property name with the value John.

    • Add the property surname with the value Smith.

    • Change the value of the name to Pete.

    • Remove the property name from the object.

  2. Sum object properties for

    const salaries = {

      John: 100,

      Ann: 160,

      Pete: 130

    }

  3. Multiply numeric properties by 2 for

    const menu = {

      width: 200,

      height: 300,

      title: "My menu"

    };

  4. Map to names for

    let john = { name: "John", age: 25 };
    let pete = { name: "Pete", age: 30 };
    let mary = { name: "Mary", age: 28 };

    let users = [ john, pete, mary ];

    let names = /* ... your code */

    alert( names ); // John, Pete, Mary

     

Final Project 🏁

Thank you

Made with ❤️ by Andrei Fidelman and data4you

deck

By Andrei Fidelman

deck

  • 189