diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 000000000..cb4b7ac2a Binary files /dev/null and b/.DS_Store differ diff --git a/HYF-JS1-Week3HW b/HYF-JS1-Week3HW new file mode 160000 index 000000000..26b1d5106 --- /dev/null +++ b/HYF-JS1-Week3HW @@ -0,0 +1 @@ +Subproject commit 26b1d51060a65b7530c7cd3cd2171114ed46d9a8 diff --git a/Week3/1.js b/Week3/1.js new file mode 100644 index 000000000..2a299b342 --- /dev/null +++ b/Week3/1.js @@ -0,0 +1,15 @@ +let myString = "hello,this,is,a,difficult,to,read,sentence"; +console.log(myString); +console.log(myString.length); +let myNewString = myString.replace(/,/g, " "); +console.log(myNewString); + +/*1. Strings! + +Consider the following string: + +let myString = "hello,this,is,a,difficult,to,read,sentence"; +1.1 Add the string to your file and log it. +1.2 Log the length of myString. +1.3 The commas make that the sentence is quite hard to read. Find a way to remove the commas from the string and replace them with spaces. +1.4 Log myString to see if you succeeded.*/ diff --git a/Week3/2.js b/Week3/2.js new file mode 100644 index 000000000..409eb2b27 --- /dev/null +++ b/Week3/2.js @@ -0,0 +1,47 @@ +let favoriteAnimals = ["blowfish", "capricorn", "giraffe"]; +favoriteAnimals.push("turtle"); +console.log(favoriteAnimals); +favoriteAnimals.splice(1, 0, "meerkat"); +console.log( + 'the new value of my array will be: "blowfish", "meerkat", "capricorn", "giraffe", "turtle"' +); +console.log(favoriteAnimals); +console.log("The array has a length of: ", favoriteAnimals.length); +favoriteAnimals.splice(3, 1); +console.log(favoriteAnimals); + +var meerkatIndex = favoriteAnimals.indexOf("meerkat"); +console.log(meerkatIndex); + +console.log('The item you are looking for is at index: ', meerkatIndex); + +/* var found = favoriteAnimals.find(function(element) { + return element = "meerkat"; +}); + +console.log(found); + +favoriteAnimals.filter(x => x.id === 'meerkat'); */ + +/* +var index = favoriteAnimals.indexOf("meerkat"); +if (index > -1) { + favoriteAnimals.splice(index, 1); +} +console.log(favoriteAnimals);*/ + +/* 2. Arrays! + +Consider the following array: + +let favoriteAnimals = ["blowfish", "capricorn", "giraffe"]; +2.1 Add a statement that adds Mauro's favorite animal 'turtle' to the existing array. +2.2 Log your new array! +2.3 Now add Jim's favorite animal to the array, it's 'meerkat', but make sure it will be placed after 'blowfish' and before 'capricorn'. +2.4 Write a console.log statement that explains in words you think the new value of the array is. +2.5 Log your new array! +2.6 Log the length of the array, add a message: 'The array has a length of: ' (here you should show the length of the array). +2.7 Jason does not like 'giraffe', delete this animal from the array. +2.8 Again log your new array. +2.9 Now if unlike Jim, you don't like 'meerkat' and you want to delete it from the array, but you don't know the position or the index of the item in the array, how can you find it? +2.10 Log the index of 'meerkat'. Add a message so it says: 'The item you are looking for is at index: ' (here you should show the index of the item). */ diff --git a/Week3/3.js b/Week3/3.js new file mode 100644 index 000000000..57f6249d6 --- /dev/null +++ b/Week3/3.js @@ -0,0 +1,181 @@ + + +// 1) Create a function that takes 3 arguments and returns the sum of the these arguments + +function hallelujah(a,b,c) { + return a + b + c +}; + +console.log(hallelujah(14, 24, 71)); + +// 2) Create a function named colorCar that receives a color, and prints out, 'a red car' for example. + +function colorCar(color) { + return 'a ' + color + ' car' +} + +console.log(colorCar('red')); + +// 3) Create an object and a function that takes the object as a parameter +// and prints out all of its properties and values. + +let myCar = { + year: '2006', + color: 'Black', + make: 'Toyota', + model: 'Prius', + motto: 'is the best car of the world :)', +}; + +function myCarSpecs(myCar) { + console.log(myCar); +} +myCarSpecs(myCar); + +// 4) Create a function named vehicleType that receives a color, and a code, 1 for car, 2 for motorbike. +// And prints 'a blue motorbike' for example when called as vehicleType("blue", 2) + +// I actually need to study this more. I got help on this but not entirely sure about the way I did it. +// Can you please let me know if there is any alternative way of doing this? + +const vehicleCategory = { + 1 : 'car', + 2 : 'motorbike', +}; + function vehicleType(color,type) { + console.log("a " + color + " " + vehicleCategory[type] ); +} + +vehicleType("blue", 2); + +// 5) Can you write the following without the if statement, but with just as a single line with console.log(...);? + +// if (3 === 3) { +// console.log("yes"); +// } else { +// console.log("no"); +// } + +console.log(3 === 3 ? "yes" : "no"); + +// 6) Create a function called vehicle, like before, +// but takes another parameter called age, so that vehicle("blue", 1, 5) prints 'a blue used car' + +const vehicleCategory2 = { + 1 : ' used ', + 2 : 'motorbike', + 3 : 'yatch', + 4 : 'speedboat', + 5 : 'car' +}; + function vehicle(color,age,type) { + console.log("a " + color + vehicleCategory2[1] + vehicleCategory2[5] ); +} + +vehicle("blue", 1, 5); + +// haha please write the proper way of doing this. I feel like I manipulated the system :) + + +// 7) Make a list of vehicles, you can add "motorbike", "caravan", "bike", or more. + +let myListOfVehicles = ["motorbike", "caravan", "bike", "car", "yatch", "jet-ski"] + +console.log(myListOfVehicles); + + +// 8) How do you get the third element from that list? + +console.log(myListOfVehicles[2]); + +// 9) Change the function vehicle to use the list of question 7. So that vehicle("green", 3, 1) +//prints "a green new bike". + +function newVehicle(color, category, age) { + if (age <= 4) { + age = "new"; + } else { + age = "used"; + } + console.log("a " + color + " " + age + " " + myListOfVehicles[3]); +} + +newVehicle("green", 3, 1); + + +// 10) Use the list of vehicles to write an advertisement. So that it prints something like: +//"Amazing Joe's Garage, we service cars, motorbikes, caravans and bikes.". (Hint: use a for loop.) + +// I HAVE NO ANSWER FOR THIS QUESTION. + +// // Hint, the output should be correct English with all the punctuation in place +// (that's the challenge). So plurals for the vehicle types, commas followed by a single space, +// the word and to replace the final comma and closed off by a period. + +// 11) What if you add one more vehicle to the list, can you have that added to the +// advertisement without changing the code for question 10? + +// I HAVE NO ANSWER FOR THIS QUESTION. + +// 12) Create an empty object. + +let emptyObject = { }; + +console.log(emptyObject); + +// 13) Create an object that contains the teachers that you have had so far for the different modules. + +emptyObject.teachers = 'Philipp & Rob, Unmesh & Bonan, Yash'; + +console.log(emptyObject.teachers); + +// 14) Add a property to the object you just created that contains the languages that they have taught you. + +emptyObject.classes = 'HTML & CSS, Git, Javascript' + +console.log(emptyObject); + + +// 15) Write some code to test two arrays for equality using == and ===. Test the following: + +let x = [1, 2, 3]; +let y = [1, 2, 3]; +let z = y; +// What do you think will happen with x == y, x === y and z == y and z == x? Prove it! + +console.log(x == y); // false, different memory locations? +console.log(x === y); // false, different memory locations? +console.log(z == y); // true, same type +console.log (z == x); // false, different types ? + +// The == equality operator converts the operands if they are not of the same type, +//then applies strict comparison. If both operands are objects, +//then JavaScript compares internal references which are equal +//when operands refer to the same object in memory. + +// The identity operator returns true if the operands are strictly equal (see above) with no type conversion. + + +// Don't cheat! Seriously - try it first. + +// Check out this Fiddle. You need to open your browser’s Developer Tools to see the console output. + +//Press the Run button in the upper right corner to run the code. + +// More insights from this Stack Overflow question. + +// 16) Take a look at the following code: + +// let o1 = { foo: "bar" }; +// let o2 = { foo: "bar" }; +// let o3 = o2; +// Show that changing o2 changes o3 (or not) and changing o1 changes o3(or not). + +// Does the order that you assign (o3 = o2 or o2 = o3) matter? + +// 17) What does the following code return? (And why?) + +// let bar = 42; +// typeof typeof bar; +// ‘Coerce' means to try to change - so coercing var x = '6' to number means +// trying to change the type to number temporarily. \ No newline at end of file diff --git a/Week3/README.md b/Week3/README.md index 569799a7b..aea42418c 100644 --- a/Week3/README.md +++ b/Week3/README.md @@ -1,40 +1,216 @@ -# Reading material for the third lecture: +# HackYourFuture +HYF JavaScript 1 / Week 2 classwork + +## Topics + +• Simple Data Types Recap + +• Arrays + +• Objects + +• Operators + +• Functions(basics) + +### Simple Data Types Recap + +JavaScript has following simple data types or also known as _primitive_ types. + +- boolean + +- null + +- undefined + +- number + +- string + +- symbol + +MDN defines a [primitive type](https://developer.mozilla.org/en-US/docs/Glossary/Primitive) as data type that has no methods or properties. This means that a string created like below doesn't have any methods or properties attached to it. + +```JavaScript +const str1 = "Wait, what?"; +const str2 = "If I don't have any properties how do I get length using str1.length?"; +const str3 = "JavaScript is crazy. I want to go home and scream!!"; ``` -In week three we will discuss the following topics: -• Git work flow -• Advanced data types [Objects] -• Conditions -• Statements vs Expressions -• Loops (for/while) -• Functions + +Let's take a deep breath and try to understand what is happening. + +1. Apart from `null` and `undefined`, each primitive type(`string`, `number` and `boolean`) has a corresponding wrapper object. Find more info about it [here](https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/String), [here](https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Number) and [here](https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Boolean). This means, I can also create a string in JavaScript like below: + + ```JavaScript + const str1 = new String('Hello World'); + // and is equivalent to + const str2 = 'Hello World'; + ``` + +2. JavaScript as a language is weakly typed. This means that whenever your code wants to perform an operation with invalid datatypes(such as find length of a primitive string), JavaScript will try to find a best match for this scenario. This mechanism is also called, as mentioned above, **coercion**. + +This is why when we try to find length of a primitive string like below + +```JavaScript +const str = 'Hello World'; +console.log(str.length); +``` + +JavaScript will try to do a coercian between primitives and objects. In this case, the primitive string is coerced to the string object in order to access its length property. Type coercian can happens other way round as well. For example, in the below snippet, string objects are coerced to primitives to concatenate them. + +```JavaScript +const str1 = new String('Hello '); +const str2 = new String('World'); +const str3 = str1 + str2; + +console.log(str3); +``` + +#### Important + +All primitives are immutable, i.e., they cannot be altered. It is important not to confuse a primitive itself with a variable assigned a primitive value. The variable may be reassigned a new value, but the existing value can not be changed in the ways that objects, arrays, and functions can be altered. For example, + +```JavaScript +let str = 'Hello World'; +console.log(str); // Hello World +str.toUpperCase(); +console.log(str); // Hello World + +str = str.toUpperCase(); +console.log(str); // HELLO WORLD ``` +### Arrays + +Arrays are one of the complex data types in JavaScript which represent a collection of values(could be both simple or complex or a combination of both). + +- How do we create an array? + + ```JavaScript + const arr1 = [1,2,3,4]; + const arr2 = new Array(); + ``` + + However, it isn't recommended to use the second approach while creating arrays. This is because it has a lot of caveats. For example, + + ```JavaScript + const arr1 = new Array(); // [] + const arr2 = new Array('a','b'); // ['a','b'] + const arr3 = new Array(20); // empty array of 20 items + const arr4 = new Array(20, 21); // [20,21] + ``` + +- Array index and length? + + We can access a particular element of an array using the following approach. + + ```JavaScript + const arr1 = ['a','b','c','d','e']; + arr1[0]; // 'a' + arr1[1]; // 'b' + arr1[2]; // 'c' + arr1[3]; // 'd' + arr1[4]; // 'e' + ``` + + and can find out the length of an array using `arr1.length` property. + +- Commonly used array methods + + - [push()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) - add items to the end of an array + + ```JavaScript + const arr = ['one','two','three']; + arr.push('four'); + console.log(arr); // ['one','two','three','four'] + arr.push('five', 'six'); + console.log(arr); // ['one','two','three','four','five','six'] + ``` + + - [unshift()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift) - add items to the beginning of an array + + ```JavaScript + const arr = [1,2,3,4]; + arr.unshift(5); + console.log(arr); // [5,1,2,3,4] + arr.unshift(6,7); + console.log(arr); // [6,7,5,1,2,3,4] + ``` + + - [shift()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift) - remove items from the beginning of an array + + ```JavaScript + const arr = [1,2,3,4]; + arr.shift(); + console.log(arr) // [2,3,4] + ``` + + - [pop()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop) - remove items from the end of an array + + ```JavaScript + const arr = [1,2,3,4]; + arr.pop(); + console.log(arr) // [1,2,3] + ``` + + - [splice()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) - remove or replace elements from an array + + ```JavaScript + // const spliceExample = array.splice(start[, deleteCount[, item1[, item2[, ...]]]]); + const months = ['Jan', 'March', 'April', 'May']; + months.splice(1,1); + console.log(months); // ['Jan', 'April', 'May'] + + months.splice(2,1,'June'); + console.log(months); // ['Jan', 'April', 'June'] + ``` + +### Objects + +An object is a collection of related data and/or functionality (which usually consists of several variables and functions — which are called properties and methods). Properties and methods exist as key:value pairs. For example, a `person` could be considered as an object with properties such as `name`, `age`, `dateOfBirth` etc. + +```JavaScript +// An empty object +const obj = {}; + +const person = { + name: 'Yash Kapila', + age: 29, + gender: 'M', + greeting() { console.log('Hello World'); } +}; +``` + +Similar to accessing an array's _elements_ using `index`, we can access _properties_ of an object. There are two ways of accessing properties of an object. + +1. dot notation(`object.property`) + + ```JavaScript + // While using the dot notation, `name` should be a valid key inside `person` object + + console.log(person.name); // Yash Kapila + console.log(person.noproperty); // undefined + ``` -> :boom: IMPORTANT: The concepts of these weeks are extremely important, and require very careful reading. -> Make sure you understand these concepts as well as you can, as they are crucial to programming and your ability to do well in our program! +2. bracket notation(`object['property']`) -### Here are resources that we like you to read as a preparation for the coming lecture: + ```JavaScript + // While using brackets notation, `'name'` should be EVALUATED to a valid key inside `person` object -- [Array](http://javascript.info/array) -- [Loops](http://javascript.info/while-for) -- [Functions](http://javascript.info/function-basics) -- [Scope](https://github.com/HackYourFuture/fundamentals/blob/master/fundamentals/scope.md) -- [Objects](http://javascript.info/object) -- [Conditions](http://javascript.info/ifelse) -- [Expressions vs statements](https://www.youtube.com/watch?v=WVyCrI1cHi8) + console.log(person['name']); // Yash Kapila + console.log(person['noproperty']); // undefined -#### Git work flow -- Check out this video of Daan to see how we use Git Workflow to hand in Homework (from now on): https://www.youtube.com/watch?v=-o0yomUVVpU&index=2&list=PLVYDhqbgYpYUGxRdtQdYVE5Q8h3bt6SIA + // Or a variable could be used to refer to a key inside the `person` object + const key = 'name'; + console.log(person[key]); // Yash Kapila; `key` here EVALUATES to `name` which is a valid key in person + ``` -### Review +### Operators -Review the topics of week 2: +- https://github.com/HackYourFuture/fundamentals/blob/master/fundamentals/operators.md +- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators -- [Variables](./../../../../fundamentals/blob/master/fundamentals/variables.md) -- [Values](./../../../../fundamentals/blob/master/fundamentals/values.md) -- [Operators](./../../../../fundamentals/blob/master/fundamentals/operators.md) -- [Special characters and their names](./../../../../fundamentals/blob/master/fundamentals/names_of_special_characters.md) -- [Naming conventions](./../../../../fundamentals/blob/master/fundamentals/naming_conventions.md) +### Functions(basics) -_Please go through the material and come to class prepared!_ +- https://github.com/HackYourFuture/fundamentals/blob/master/fundamentals/functions.md diff --git a/Week3/homework/README.md b/Week3/homework/README.md new file mode 100644 index 000000000..bf8d3bec2 --- /dev/null +++ b/Week3/homework/README.md @@ -0,0 +1,70 @@ +# Homework Exercises + +## Strings + +1. Consider the following string: + + ```JavaScript + const myString = "hello,this,is,a,difficult,to,read,sentence"; + ``` + + - Add the string to your file and log it. + - Log the length of myString. + - The commas make that the sentence is quite hard to read. Find a way to remove the commas from the string and __replace__ them with spaces. + +2. Consider the following string: + + ```JavaScript + const str = 'dlroW olleH'; + ``` + + - The string doesn't make any sense. Find a way to _reverse_ this string so that it becomes readable. + +## Arrays + +1. Consider the following array: + + ```JavaScript + const favoriteAnimals = ["blowfish", "capricorn", "giraffe"]; + ``` + + - Add a statement that adds your favorite animal say 'turtle' to the existing array. + - Explain in a comment what do you think the new array will look like. + - Log your new array. + - Now add another favorite animal to the array but make sure it is placed after 'blowfish' and before 'capricorn'. + - Explain in a comment what do you think the new array will look like. + - Log your new array. + - Delete 'giraffe' from the array. + +## Operators + +1. Consider the following snippet: + + ```JavaScript + 0 == '0'; // true + 0 == []; // true + "0" == []; // false + ``` + + - Mathematically, if `a == b` and `b == c`, then `a == c`. Can you explain in your words why this is not true for the above snippet? + +2. Consider the following snippet: + + ```JavaScript + const x = [1, 2, 3]; + const y = [1, 2, 3]; + const z = y; + ``` + + - What do you think will happen with `x == y`, `x === y` and `z === y` and `z == x`? Try to think of answer first before running it on browser. Also, explain in your words why this happens? + +3. Consider the following snippet: + + ```JavaScript + const o1 = { foo: "bar" }; + const o2 = { foo: "bar" }; + const o3 = o2; + ``` + + - Show that changing o2 changes o3 (or not) and changing o1 changes o3(or not). + - Does the order that you assign (o3 = o2 or o2 = o3) matter? diff --git a/Week3/index.html b/Week3/index.html new file mode 100644 index 000000000..c3311b1a0 --- /dev/null +++ b/Week3/index.html @@ -0,0 +1,15 @@ + + +
+ + + +