diff --git a/.gitignore b/.gitignore index e8317f9..35b0e83 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,12 @@ playground /playground .DS_Store test.js -day3.md \ No newline at end of file +day3.md +day4.md +day5.md +day6.md +day7.md +day8.md +day9.md +day10.md +01_02_03_days_backup.md \ No newline at end of file diff --git a/01_Day/Day -1 – 1.png b/01_Day/Day -1 – 1.png new file mode 100644 index 0000000..dd583c7 Binary files /dev/null and b/01_Day/Day -1 – 1.png differ diff --git a/01-Day/helloworld.js b/01_Day/helloworld.js similarity index 100% rename from 01-Day/helloworld.js rename to 01_Day/helloworld.js diff --git a/01-Day/index.html b/01_Day/index.html similarity index 100% rename from 01-Day/index.html rename to 01_Day/index.html diff --git a/01-Day/introduction.js b/01_Day/introduction.js similarity index 100% rename from 01-Day/introduction.js rename to 01_Day/introduction.js diff --git a/01-Day/main.js b/01_Day/main.js similarity index 100% rename from 01-Day/main.js rename to 01_Day/main.js diff --git a/01-Day/varaible.js b/01_Day/varaible.js similarity index 100% rename from 01-Day/varaible.js rename to 01_Day/varaible.js diff --git a/02_Day/02_day_data_types.md b/02_Day/02_day_data_types.md new file mode 100644 index 0000000..bc8c7c1 --- /dev/null +++ b/02_Day/02_day_data_types.md @@ -0,0 +1,937 @@ + +## Table of Contents + +[<< Day 1](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/readMe.md) | [Day 3 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/03_Day/03_booleans_operators_date.md) +-- + +![Thirty Days Of JavaScript](./day_1_2.png) + +- [πŸ“” Day 2](#%f0%9f%93%94-day-2) + - [Data types](#data-types) + - [Primitive Data Types](#primitive-data-types) + - [Non-Primitive Data Types](#non-primitive-data-types) + - [Numbers](#numbers) + - [Declaring number data types](#declaring-number-data-types) + - [Math Object](#math-object) + - [Random number generator](#random-number-generator) + - [Strings](#strings) + - [String Concatenation](#string-concatenation) + - [Concatenating using addition operator](#concatenating-using-addition-operator) + - [Long Literal Strings](#long-literal-strings) + - [Escape Sequences in string](#escape-sequences-in-string) + - [Template Literals(Template Strings)](#template-literalstemplate-strings) + - [String Methods](#string-methods) + - [Checking Data types and Casting](#checking-data-types-and-casting) + - [Checking data types](#checking-data-types) + - [Changing data type(Casting)](#changing-data-typecasting) + - [String to Int](#string-to-int) + - [String to Float](#string-to-float) + - [Float to Int](#float-to-int) +- [πŸ’» Day 2: Exercises](#%f0%9f%92%bb-day-2-exercises) + +# πŸ“” Day 2 + +## Data types + +In the previous section, we mentioned a little bit about data types. Data or values have data types. Data types describe the characteristics of data. Data types can be divided into two + +1. Primitive data types +2. Non-primitive data types(Object References) + +### Primitive Data Types + +Primitive data types in JavaScript includes: + + 1. Numbers - Integers, floats + 2. Strings - Any data under single or double quote + 3. Booleans - true or false value + 4. Null - empty value or no value + 5. Undefined - a declared variable without a value + +Non-primitive data types in JavaScript includes: + +1. Objects +2. Functions +3. Arrays + +Now, let us see what exactly mean primitive and non-primitive data types. +*Primitive* data types are immutable(non-modifiable) data types. Once a primitive data type is created we can not modify it. +**Example:** + +```js +let word = 'JavaScript' +``` + +If we try to modify the string stored in variable *word*, JavaScript will raise an error. Any data type under a single quote, double-quote, or backtick is a string data type. + +```js +word[0] = 'Y' +``` + +This expression does not change the string stored in the variable *word*. So, we can say that strings are not modifiable or immutable. +Primitive data types are compared by its values. Let us compare different data values. See the example below: + +```js +let numOne = 3 +let numTwo = 3 + +console.log(numOne == numTwo) // true + +let js = 'JavaScript' +let py = 'Python' + +console.log(js == py) //false + +let lightOn = true +let lightOff = false + +console.log(lightOn == lightOff) // false +``` + +### Non-Primitive Data Types + +*Non-primitive* data types are modifiable or mutable. We can modify the value of non-primitive data types after it gets created. +Let us see by creating an array. An array is a list of data values in a square bracket. Arrays can contain the same or different data types. Array values are referenced by their index. In JavaScript array index starts at zero. I.e., the first element of an array is found at index zero, the second element at index one, and the third element at index two, etc. + +```js +let nums = [1, 2, 3] +nums[0] = 10 + +console.log(nums) // [10, 2, 3] +``` + +As you can see, an array in which a non-primitive data type is mutable. Non-primitive data types can not be compared by value. Even if two non-primitive data types have the same properties and values, they are not strictly equal. + +```js +let nums = [1, 2, 3] +let numbers = [1, 2, 3] + +console.log(nums == numbers) // false + +let userOne = { +name:'Asabeneh', +role:'teaching', +country:'Finland' +} + +let userTwo = { +name:'Asabeneh', +role:'teaching', +country:'Finland' +} + +console.log(userOne == userTwo) +``` + +Rule of thumb, we do not compare non-primitive data types. Do not compare array, function, or object. +Non-primitive values are referred to as reference types because they are being compared by reference instead of value. Two objects are only strictly equal if they refer to the same underlying object. + +```js +let nums = [1, 2, 3] +let numbers = nums + +console.log(nums == numbers) // true + +let userOne = { +name:'Asabeneh', +role:'teaching', +country:'Finland' +} + +let userTwo = userOne + +console.log(userOne == userTwo) // true +``` + +If you have a hard time understanding the difference between primitive data types and non-primitive data types, you are not the only one. Calm down and just go to the next section and try to come back after some time. Now let us start the data types by number type. + +## Numbers + +Numbers are integers and decimal values which can do all the arithmetic operations. +Lets' see some examples of Numbers. + +### Declaring number data types + +```js +let age = 35 +const gravity = 9.81 //we use const for non-changing values, gravitational constant in m/s2 +let mass = 72 // mass in Kilogram +const PI = 3.14 // pi a geometrical constant + +//More Examples +const boilingPoint = 100 // temperature in oC, boiling point of water which is a constant +const bodyTemp = 37 // oC average human body temperature, which is a constant + +console.log(age, gravity, mass, PI, boilingPoint, bodyTemp) +``` + +### Math Object + +In JavaScript the Math Object provides a lots of methods to work with numbers. + +```js +const PI = Math.PI + +console.log(PI) // 3.141592653589793 + +// Rounding to the closest number +// if above .5 up if less 0.5 down rounding + +console.log(Math.round(PI)) // 3 to round values to the nearest number + +console.log(Math.round(9.81)) // 10 + +console.log(Math.floor(PI)) // 3 rounding down + +console.log(Math.ceil(PI)) // 4 rounding up + +console.log(Math.min(-5, 3, 20, 4,5, 10)) // -5, returns the minimum value + +console.log(Math.max(-5, 3, 20, 4,5, 10)) // 20, returns the maximum value + +const randNum = Math.random() // creates random number between 0 to 0.999999 +console.log(randNum) + +// Let us create random number between 0 to 10 + +const num = Math.floor(Math.random () * 11) // creates random number between 0 and 10 +console.log(num) + +//Absolute value +console.log(Math.abs(-10)) //10 + +//Square root +console.log(Math.sqrt(100)) // 10 + +console.log(Math.sqrt(2)) //1.4142135623730951 + +// Power +console.log(Math.pow(3, 2)) // 9 + +console.log(Math.E) // 2.718 + +// Logarithm +//Returns the natural logarithm of base E of x, Math.log(x) +console.log(Math.log(2)) // 0.6931471805599453 +console.log(Math.log(10)) // 2.302585092994046 + +// Trigonometry +Math.sin(0) +Math.sin(60) + +Math.cos(0) +Math.cos(60) +``` + +#### Random number generator + +The JavaScript Math Object has a random() method number generator which generates number from 0 to 0.999999999... + +```js +let randomNum = Math.random() // generates 0 to 0.999 +``` + +Now, let us see how we can use random() method to generate a random number between 0 and 10 inclusive. + +```js +let randomNum = Math.random() // generates 0 to 0.999 +let numBtnZeroAndTen = randomNum * 11 + +console.log(numBtnZeroAndTen) // this gives: min 0 and max 10.99 + +let randomNumRoundToFloor = Math.floor(numBtnZeroAndTen) +console.log(randomNumRoundToFloor) // this gives between 0 and 10 +``` + +## Strings + +Strings are texts, which are under **_single_** or **_double_** quote. To declare a string, we need a variable name, assignment operator, a value under a single quote, double-quote, or backtick. +Lets' see some examples of string: + +```js +let space = ' ' // an empty space string +let firstName = 'Asabeneh' +let lastName = 'Yetayeh' +let country = 'Finland' +let city = 'Helsinki' +let language = 'JavaScript' +let job = 'teacher' +``` + +### String Concatenation + +Connect two or more strings together is called concatenation. + +```js +// Declaring different variables of different data types +let space = ' ' +let firstName = 'Asabeneh' +let lastName = 'Yetayeh' +let country = 'Finland' +let city = 'Helsinki' +let language = 'JavaScript' +let job = 'teacher' +``` + +```js +let fullName = firstName + space + lastName; // concatenation, merging two string together. +console.log(fullName); +``` + +```sh +Asabeneh Yetayeh +``` + +We can concatenate string in different ways. + +#### Concatenating using addition operator + +Concatenating using the addition operator is an old way. This way of concatenating is tedious and error-prone. It is good to know how to concatenate this way, but I strongly suggest to use the second way. + +```js +// Declaring different variables of different data types +let space = ' ' +let firstName = 'Asabeneh' +let lastName = 'Yetayeh' +let country = 'Finland' +let city = 'Helsinki' +let language = 'JavaScript' +let job = 'teacher' +let age = 250 +let fullName = firstName + space + lastName + +let personInfoOne = fullName + '. I am ' + age + '. I live in ' + country; // ES5 + +console.log(personInfoOne) +``` + +```sh +Asabeneh Yetayeh. I am 250. I live in Finland +``` + +#### Long Literal Strings + +A string could be a single character or paragraph or a page. If the string length is too big it does not fit in one line. We can use the backslash character (\) at the end of each line to indicate that the string will continue on the next line. +**Example:** + +```js +const paragraph = "My name is Asabeneh Yetayeh. I live in Finland, Helsinki.\ +I am a teacher and I love teaching. I teach HTML, CSS, JavaScript, React, Redux, \ +Node.js, Python, Data Analysis and D3.js for anyone who is interested to learn. \ +In the end of 2019, I was thinking to expand my teaching and to reach \ +to global audience and I started a Python challenge from November 20 - December 19.\ +It was one of the most rewarding and inspiring experience.\ +Now, we are in 2020. I am enjoying preparing the 30DaysOfJavaScript challenge and \ +I hope you are enjoying too." +console.log(paragraph) +``` + +#### Escape Sequences in string + +In JavaScript and other programming language \ followed by some characters is an escape sequence. Let's see the most common escape characters: + +- \n: new line +- \t: Tab means(8 spaces) +- \\\\: Back slash +- \\': Single quote (') +- \\":Double quote (") + +```js +console.log('I hope every one is enjoying the 30 Days Of JavaScript challenge.\nDo you ?') // line break +console.log('Days\tTopics\tExercises') +console.log('Day 1\t3\t5') +console.log('Day 2\t3\t5') +console.log('Day 3\t3\t5') +console.log('Day 4\t3\t5') +console.log('This is a back slash symbol (\\)') // To write a back slash +console.log('In every programming language it starts with \"Hello, World!\"') +console.log("In every programming language it starts with \'Hello, World!\'") +console.log('The saying \'Seeing is Believing\' is\'t correct in 2020') +``` + +#### Template Literals(Template Strings) + +To create a template string, we use two backticks. We can inject data as expression inside a template string. To inject data, we enclose the expression with a curly bracket({}) followed by a $ sign. See the syntax below. + +```js +//Syntax +`String literal text` +`String literal text ${expression}` +``` + +**Example: 1** + +```js +console.log(`The sum of 2 and 3 is 5`) // statically writing the data +let a = 2 +let b = 3 +console.log(`The sum of ${a} and ${b} is ${a + b}`) // injecting the data dynamically +``` + +**Example:2** + +```js +let firstName = 'Asabeneh' +let lastName = 'Yetayeh' +let country = 'Finland' +let city = 'Helsinki' +let language = 'JavaScript' +let job = 'teacher' +let age = 250 +let fullName = firstName + ' ' + lastName + +let personInfoTwo = `I am ${fullName}. I am ${age}. I live in ${country}.` //ES6 - String interpolation method +let personInfoThree = `I am ${fullName}. I live in ${city}, ${country}. I am a ${job}. I teach ${language}.` +console.log(personInfoTwo) +console.log(personInfoThree) +``` + +```sh +I am Asabeneh Yetayeh. I am 250. I live in Finland. +I am Asabeneh Yetayeh. I live in Helsinki, Finland. I am a teacher. I teach JavaScript. +``` + +Using a string template or string interpolation method, we can add expression, which could be a value or some operations(comparison, arithmetic operations, ternary operation). + +```js +let a = 2 +let b = 3 +console.log(`${a} is greater than ${b}: ${a > b}`) +``` + +```sh +2 is greater than 3: false +``` + +### String Methods + +Everything in JavaScript is an object. A string is a primitive data type that means we can not modify once it is created. The string object has many string methods. There are different string methods that can help us to work with strings. + +1. *length*: The string *length* method returns the number of characters in a string included empty space. + **Example:** + + ```js + let js = 'JavaScript' + console.log(js.length) // 10 + let firstName = 'Asabeneh' + console.log(firstName.length) // 8 + ``` + +2. *Accessing characters in a string*: We can access each character in a string using its index. In programming, counting starts from 0. The first index of the string is zero, and the last index is one minus the length of the string. + + ![Accessing sting by index](../images/string_indexes.png) + +Let us access different characters in 'JavaScript' string. + +```js +let string = 'JavaScript' +let firstLetter = string[0] + +console.log(firstLetter) // J + +let secondLetter = string[1] // a +let thirdLetter = string[2] +let lastLetter = string[9] + +console.log(lastLetter) // t + +let lastIndex = string.length - 1 + +console.log(lastIndex) // 9 +console.log(string[lastIndex]) // t +``` + +1. *toUpperCase()*: this method changes the string to uppercase letters. + +```js +let string = 'JavaScript' + +console.log(string.toUpperCase()) // JAVASCRIPT + +let firstName = 'Asabeneh' + +console.log(firstName.toUpperCase()) // ASABENEH + +let country = 'Finland' + +console.log(country.toUpperCase()) // FINLAND +``` + +4. *toLowerCase()*: this method changes the string to lowercase letters. + +```js +let string = 'JavasCript' + +console.log(string.toLowerCase()) // javascript + +let firstName = 'Asabeneh' + +console.log(firstName.toLowerCase()) // asabeneh + +let country = 'Finland' + +console.log(country.toLowerCase()) // finland +``` + +5. *substr()*: It takes two arguments, the starting index and number of characters to slice. + +```js +let string = 'JavaScript' +console.log(string.substr(4,6)) // Script + +let country = 'Finland' +console.log(country.substr(3, 4)) // land +``` + +6. *substring()*: It takes two arguments, the starting index and the stopping index but it doesn't include the stopping index. + +```js +let string = 'JavaScript' + +console.log(string.substring(0,4)) // Java +console.log(string.substring(4,10)) // Script +console.log(string.substring(4)) // Script + +let country = 'Finland' + +console.log(country.substring(0, 3)) // Fin +console.log(country.substring(3, 7)) // land +console.log(country.substring(3)) // land +``` + +7. *split()*: The split method splits a string at a specified place. + +```js +let string = '30 Days Of JavaScipt' + +console.log(string.split()) // ["30 Days Of JavaScript"] +console.log(string.split(' ')) // ["30", "Days", "Of", "JavaScript"] + +let firstName = 'Asabeneh' + +console.log(firstName.split()) // ["Asabeneh"] +console.log(firstName.split('')) // ["A", "s", "a", "b", "e", "n", "e", "h"] + +let countries = 'Finland, Sweden, Norway, Denmark, and Iceland' + +console.log(countries.split(',')) // ["Finland", " Sweden", " Norway", " Denmark", " and Iceland"] +console.log(countries.split(', ')) // Β ["Finland", "Sweden", "Norway", "Denmark", "and Iceland"] +``` + +8. *trim()*: Removes trailing space in the beginning or the end of a string. + +```js +let string = ' 30 Days Of JavaScript ' + +console.log(string) +console.log(string.trim(' ')) + +let firstName = ' Asabeneh ' + +console.log(firstName) +console.log(firstName.trim()) +``` + +```sh + 30 Days Of JavasCript +30 Days Of JavasCript + Asabeneh +Asabeneh +``` + +9. *includes()*: It takes a substring argument and it check if substring argument exists in the string. *includes()* returns a boolean. It checks if a substring exist in a string and it returns true if it exists and false if it doesn't exist. + +```js +let string = '30 Days Of JavaScript' + +console.log(string.includes('Days')) // true +console.log(string.includes('days')) // false +console.log(string.includes('Script')) // true +console.log(string.includes('script')) // false +console.log(string.includes('java')) // false +console.log(string.includes('Java')) // true + +let country = 'Finland' + +console.log(country.includes('fin')) // false +console.log(country.includes('Fin')) // true +console.log(country.includes('land')) // true +console.log(country.includes('Land')) // false +``` + +10. *replace()*: takes to parameter the old substring and new substring. + +```js +string.replace(oldsubstring, newsubstring) +``` + +```js +let string = '30 Days Of JavaScript' +console.log(string.replace('JavaScript', 'Python')) // 30 Days Of Python + +let country = 'Finland' +console.log(country.replace('Fin', 'Noman')) // Nomanland +``` + +11. *charAt()*: Takes index and it returns the value at that index + +```js +string.charAt(index) +``` + +```js +let string = '30 Days Of JavaScript' +console.log(string.charAt(0)) // 3 + +let lastIndex = string.length - 1 +console.log(string.charAt(lastIndex)) // t +``` + +12. *charCodeAt()*: Takes index and it returns char code(ASCII number) of the value at that index + +```js +string.charCodeAt(index) +``` + +```js +let string = '30 Days Of JavaScript' +console.log(string.charCodeAt(3)) // D ASCII number is 51 + +let lastIndex = string.length - 1 +console.log(string.charCodeAt(lastIndex)) // t ASCII is 116 + +``` + +13. *indexOf()*: Takes takes a substring and if the substring exists in a string it returns the first position of the substring if does not exist it returns -1 + +```js +string.indexOf(substring) +``` + +```js +let string = '30 Days Of JavaScript' + +console.log(string.indexOf('D')) // 3 +console.log(string.indexOf('Days')) // 3 +console.log(string.indexOf('days')) // -1 +console.log(string.indexOf('a')) // 4 +console.log(string.indexOf('JavaScript')) // 11 +console.log(string.indexOf('Script')) //15 +console.log(string.indexOf('script')) // -1 +``` + +14. *lastIndexOf()*: Takes takes a substring and if the substring exists in a string it returns the last position of the substring if it does not exist it returns -1 + +```js +string.lastIndexOf(index) +``` + +```js +let string = 'I love JavaScript. If you do not love JavaScript what else can you love.' + +console.log(string.lastIndexOf('love')) // 67 +console.log(string.lastIndexOf('you')) // 63 +console.log(string.lastIndexOf('JavaScript')) // 38 +``` + +15. *concat()*: it takes many substrings and creates concatenation. + +```js +string.concat(substring, substring, substring) +``` + +```js +let string = '30' +console.log(string.concat("Days", "Of", "JavaScript")) // 30DaysOfJavaScript + +let country = 'Fin' +console.log(country.concat("land")) // Finland +``` + +16. *startsWith*: it takes a substring as an argument and it checks if the string starts with that specified substring. It returns a boolean(true or false). + +```js +//syntax +string.startsWith(substring) +``` + +```js +let string = 'Love is the best to in this world' + +console.log(string.startsWith('Love')) // true +console.log(string.startsWith('love')) // false +console.log(string.startsWith('world')) // false + +let country = 'Finland' + +console.log(country.startsWith('Fin')) // true +console.log(country.startsWith('fin')) // false +console.log(country.startsWith('land')) // false +``` + +17. *endsWith*: it takes a substring as an argument and it checks if the string starts with that specified substring. It returns a boolean(true or false). + +```js +string.endsWith(substring) +``` + +```js +let string = 'Love is the best to in this world' + +console.log(string.endsWith('world')) // true +console.log(string.endsWith('love')) // false +console.log(string.endsWith('in this world')) // true + +let country = 'Finland' + +console.log(country.endsWith('land')) // true +console.log(country.endsWith('fin')) // false +console.log(country.endsWith('Fin')) // false +``` + +18. *search*: it takes a substring as an argument and it returns the index of the first match. + +```js +string.search(substring) +``` + +```js +let string = 'I love JavaScript. If you do not love JavaScript what else can you love.' +console.log(string.search('love')) // 2 +``` + +19. *match*: it takes a substring or regular expression pattern as an argument and it returns an array if there is match if not it returns null. Let us see how a regular expression pattern looks like. It starts with / sign and ends with / sign. + +```js +let string = 'love' +let patternOne = /love/ // with out any flag +let patternTwo = /love/gi // g-means to search in the whole text, i - case insensitive +``` + +Match syntax + +```js +// syntax +string.match(substring) +``` + +```js +let string = 'I love JavaScript. If you do not love JavaScript what else can you love.' +console.log(string.match('love')) +``` + +```sh +["love", index: 2, input: "I love JavaScript. If you do not love JavaScript what else can you love.", groups: undefined] +``` + +```js +let pattern = /love/gi +console.log(string.match(pattern)) // ["love", "love", "love"] +``` + +Let us extract numbers from text using regular expression. This is not regular expression section, no panic, we will cover regular expression in other section. + +```js +let txt = 'In 2019, I run 30 Days of Python. Now, in 2020 I super exited to start this challenge' +let regEx = /\d+/ + +// d with escape character means d not a normal d instead acts a digit +// + means one or more digit numbers, +// if there is g after that it means global, search everywhere. + +console.log(txt.match(regEx)) // ["2", "0", "1", "9", "3", "0", "2", "0", "2", "0"] +console.log(txt.match(/\d+/g)) // ["2019", "30", "2020"] +``` + +20. *repeat()*: it takes a number argument and it returned the repeated version of the string. + +```js +string.repeat(n) +``` + +```js +let string = 'love' +console.log(string.repeat(10)) // lovelovelovelovelovelovelovelovelovelove +``` + +## Checking Data types and Casting + +### Checking data types + +- Check Data types: To check the data type of a certain data type we use the _typeof_ and we also change one data type to another. + **Example:** + +```js +// Different python data types +// Let's declare different data types + +let firstName = 'Asabeneh' // string +let lastName = 'Yetayeh' // string +let country = 'Finland' // string +let city = 'Helsinki' // string +let age = 250 // number, it is not my real age, do not worry about it +let job // undefined, because a value was not assigned + +console.log(typeof 'Asabeneh') // string +console.log(typeof firstName) // string +console.log(typeof 10) // number +console.log(typeof 3.14) // number +console.log(typeof true) // boolean +console.log(typeof false) // boolean +console.log(typeof NaN) // number +console.log(typeof job) // undefined +console.log(typeof undefined) // undefined +console.log(typeof null) // object +``` + +### Changing data type(Casting) + +- Casting: Converting one data type to another data type. We use _parseInt()_, _parsefloat()_,_Number()_, _+ sign_, _str()_ + When we do arithmetic operations string numbers should be first converted to integer or float if not it returns an error. + +#### String to Int + +We can convert string number to a number. Any number inside a quote is a string number. An example of a string number: '10', '5', etc. +We can convert string to number using the following methods: + +- parseInt() +- Number() +- Plus sign(+) + +```js +let num = '10' +let numInt = parseInt(num) +console.log(numInt) // 10 +``` + +```js +let num = '10' +let numInt = Number(num) + +console.log(numInt) // 10 +``` + +```js +let num = '10' +let numInt = +num + +console.log(numInt) // 10 +``` + +#### String to Float + +We can convert string float number to a float number. Any float number inside a quote is a string float number. An example of a string float number: '9.81', '3.14', '1.44', etc. +We can convert string float to number using the following methods: + +- parseFloat() +- Number() +- Plus sign(+) + +```js +let num = '9.81' +let numFloat = parseFloat(num) + +console.log(numFloat) // 9.81 +``` + +```js +let num = '9.81' +let numFloat = Number(num) + +console.log(numFloat) // 9.81 +``` + +```js +let num = '9.81' +let numFloat = +num + +console.log(numInt) // 9.81 +``` + +#### Float to Int + +We can convert float numbers to integers. +We use the following method to convert float to int: + +- parseInt() + +```js +let num = 9.81 +let numInt = parseInt(num) + +console.log(numInt) // 9 +``` + +πŸŒ• You are awesome. You have just completed day 2 challenge and you are two steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle. + +# πŸ’» Day 2: Exercises + +1. Declare a variable name challenge and assign it to an initial value **'30 Days Of JavaScript'**. +2. Print the string on the browser console using __console.log()__ +3. Print the __length__ of the string on the browser console using _console.log()_ +4. Change all the string to capital letters using __toUpperCase()__ method +5. Change all the string to lowercase letters using __toLowerCase()__ method +6. Cut(slice) out the first word of the string using __substr()__ or __substring()__ method +7. Slice out the phrase *Days Of JavaScript* from *30 Days Of JavaScript*. +8. Use __substr__ to slice out the phase __because because because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__ +9. Check if the string contains a word __Script__ using __includes()__ method +10. Split the __string__ into __array__ using __split()__ method +11. Split the string 30 Days Of JavaScript at the space using __split()__ method +12. 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon' __split__ the string at the comma and change it to an array. +13. Change 30 Days Of JavaScript to 30 Days Of Python using __replace()__ method. +14. What is character at index 15 in '30 Days Of JavaScript' string use __charAt()__ method. +15. What is the character code of J in '30 Days Of JavaScript' string using __charCodeAt()__ +16. Use __indexOf__ to determine the position of the first occurrence of a in 30 Days Of JavaScript +17. Use __lastIndexOf__ to determine the position of the last occurrence of a in 30 Days Of JavaScript. +18. Use __indexOf__ to find the position of the first occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__ +19. Use __lastIndexOf__ to find the position of the last occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__ +20. Use __search__ to find the position of the first occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__ +21. Use __trim()__ to remove if there is trailing whitespace at the beginning and the end of a string.E.g ' 30 Days Of JavaScript '. +22. Use __startsWith()__ method with the string *30 Days Of JavaScript* make the result true +23. Use __endsWith()__ method with the string *30 Days Of JavaScript* make the result true +24. Use __match()__ method to find all the a’s in 30 Days Of JavaScript +25. Use __match()__ to count the number all because's in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__ +26. Use __concat()__ and merge '30 Days of' and 'JavaScript' to a single string, '30 Days Of JavaScript' +27. Use __repeat()__ method to print 30 Days Of JavaScript 2 times +28. ** 'Love is the best thing in this world. Some found their love and some are still looking for their love.' Count the number of word love in this sentence. +29. ** Calculate the total annual income of the person by extract the numbers from the following text. 'He earns 5000 euro from salary per month, 10000 euro annual bonus, 15000 euro online courses per month.' +30. ** Clean the following text and find the most frequent word(hint, use replace and regular express). + +```js + const sentence = '%I $am@% a %tea@cher%, &and& I lo%#ve %tea@ching%;. There $is nothing; &as& mo@re rewarding as educa@ting &and& @emp%o@wering peo@ple. ;I found tea@ching m%o@re interesting tha@n any other %jo@bs. %Do@es thi%s mo@tivate yo@u to be a tea@cher!? %Th#is 30#Days&OfJavaScript &is also $the $result of &love& of tea&ching' +``` + +31. Using console.log() print out the following statement. + +```sh +The quote 'There is no exercise better for the heart than reaching down and lifting people up.' by John Holmes teaches us to help to one another. +``` + +32. Using console.log() print out the following quote by Mother Teresa. + +```sh +"Love is not patronizing and charity isn't about pity, it is about love. Charity and love are the same -- with charity you give love, so don't just give money but reach out your hand instead." +``` + +33. Check if 'on' is found in both python and jargon +34. _I hope this course is not full of jargon_. Check if _jargon_ is in the sentence. +35. Generate a random number between 0 and 100 inclusive. +36. Generate a random number between 50 and 100 inclusive. +37. Generate a random number between 0 and 255 inclusive. +38. Access the 'JavaScript' string characters using a random number. +39. Use console.log() and escape characters to print the following pattern. + + ```js + 1 1 1 1 1 + 2 1 2 4 8 + 3 1 3 9 27 + 4 1 4 16 64 + 5 1 5 25 125 + ``` + +40. Check if typeof '10' is exactly equal to 10. If not make it exactly equal. +41. Check if parseInt('9.8') is equal to 10 if not make it exactly equal with 10. + +πŸŽ‰ CONGRATULATIONS ! πŸŽ‰ + +[<< Day 1](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/readMe.md) | [Day 3 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/03_Day/03_booleans_operators_date.md) diff --git a/02_Day/day_1_2.png b/02_Day/day_1_2.png new file mode 100644 index 0000000..0f6eefb Binary files /dev/null and b/02_Day/day_1_2.png differ diff --git a/02-Day/index.html b/02_Day/index.html similarity index 100% rename from 02-Day/index.html rename to 02_Day/index.html diff --git a/02-Day/main.js b/02_Day/main.js similarity index 100% rename from 02-Day/main.js rename to 02_Day/main.js diff --git a/02-Day/math_object.js b/02_Day/math_object.js similarity index 100% rename from 02-Day/math_object.js rename to 02_Day/math_object.js diff --git a/02-Day/non_primitive_data_types.js b/02_Day/non_primitive_data_types.js similarity index 100% rename from 02-Day/non_primitive_data_types.js rename to 02_Day/non_primitive_data_types.js diff --git a/02-Day/number_data_types.js b/02_Day/number_data_types.js similarity index 100% rename from 02-Day/number_data_types.js rename to 02_Day/number_data_types.js diff --git a/02-Day/primitive_data_types.js b/02_Day/primitive_data_types.js similarity index 100% rename from 02-Day/primitive_data_types.js rename to 02_Day/primitive_data_types.js diff --git a/02-Day/string_concatenation.js b/02_Day/string_concatenation.js similarity index 100% rename from 02-Day/string_concatenation.js rename to 02_Day/string_concatenation.js diff --git a/02-Day/string_data_types.js b/02_Day/string_data_types.js similarity index 100% rename from 02-Day/string_data_types.js rename to 02_Day/string_data_types.js diff --git a/02-Day/string_methods/accessing_character.js b/02_Day/string_methods/accessing_character.js similarity index 100% rename from 02-Day/string_methods/accessing_character.js rename to 02_Day/string_methods/accessing_character.js diff --git a/02-Day/string_methods/char_at.js b/02_Day/string_methods/char_at.js similarity index 100% rename from 02-Day/string_methods/char_at.js rename to 02_Day/string_methods/char_at.js diff --git a/02-Day/string_methods/char_code_at.js b/02_Day/string_methods/char_code_at.js similarity index 100% rename from 02-Day/string_methods/char_code_at.js rename to 02_Day/string_methods/char_code_at.js diff --git a/02-Day/string_methods/concat.js b/02_Day/string_methods/concat.js similarity index 100% rename from 02-Day/string_methods/concat.js rename to 02_Day/string_methods/concat.js diff --git a/02-Day/string_methods/ends_with.js b/02_Day/string_methods/ends_with.js similarity index 100% rename from 02-Day/string_methods/ends_with.js rename to 02_Day/string_methods/ends_with.js diff --git a/02-Day/string_methods/includes.js b/02_Day/string_methods/includes.js similarity index 100% rename from 02-Day/string_methods/includes.js rename to 02_Day/string_methods/includes.js diff --git a/02-Day/string_methods/index_of.js b/02_Day/string_methods/index_of.js similarity index 100% rename from 02-Day/string_methods/index_of.js rename to 02_Day/string_methods/index_of.js diff --git a/02-Day/string_methods/last_index_of.js b/02_Day/string_methods/last_index_of.js similarity index 100% rename from 02-Day/string_methods/last_index_of.js rename to 02_Day/string_methods/last_index_of.js diff --git a/02-Day/string_methods/length.js b/02_Day/string_methods/length.js similarity index 100% rename from 02-Day/string_methods/length.js rename to 02_Day/string_methods/length.js diff --git a/02-Day/string_methods/match.js b/02_Day/string_methods/match.js similarity index 100% rename from 02-Day/string_methods/match.js rename to 02_Day/string_methods/match.js diff --git a/02-Day/string_methods/repeat.js b/02_Day/string_methods/repeat.js similarity index 100% rename from 02-Day/string_methods/repeat.js rename to 02_Day/string_methods/repeat.js diff --git a/02-Day/string_methods/replace.js b/02_Day/string_methods/replace.js similarity index 100% rename from 02-Day/string_methods/replace.js rename to 02_Day/string_methods/replace.js diff --git a/02-Day/string_methods/search.js b/02_Day/string_methods/search.js similarity index 100% rename from 02-Day/string_methods/search.js rename to 02_Day/string_methods/search.js diff --git a/02-Day/string_methods/split.js b/02_Day/string_methods/split.js similarity index 100% rename from 02-Day/string_methods/split.js rename to 02_Day/string_methods/split.js diff --git a/02-Day/string_methods/starts_with.js b/02_Day/string_methods/starts_with.js similarity index 100% rename from 02-Day/string_methods/starts_with.js rename to 02_Day/string_methods/starts_with.js diff --git a/02-Day/string_methods/substr.js b/02_Day/string_methods/substr.js similarity index 100% rename from 02-Day/string_methods/substr.js rename to 02_Day/string_methods/substr.js diff --git a/02-Day/string_methods/substring.js b/02_Day/string_methods/substring.js similarity index 100% rename from 02-Day/string_methods/substring.js rename to 02_Day/string_methods/substring.js diff --git a/02-Day/string_methods/to_lowercase.js b/02_Day/string_methods/to_lowercase.js similarity index 100% rename from 02-Day/string_methods/to_lowercase.js rename to 02_Day/string_methods/to_lowercase.js diff --git a/02-Day/string_methods/to_uppercase.js b/02_Day/string_methods/to_uppercase.js similarity index 100% rename from 02-Day/string_methods/to_uppercase.js rename to 02_Day/string_methods/to_uppercase.js diff --git a/02-Day/string_methods/trim.js b/02_Day/string_methods/trim.js similarity index 100% rename from 02-Day/string_methods/trim.js rename to 02_Day/string_methods/trim.js diff --git a/03_Day/03_booleans_operators_date.md b/03_Day/03_booleans_operators_date.md new file mode 100644 index 0000000..486b810 --- /dev/null +++ b/03_Day/03_booleans_operators_date.md @@ -0,0 +1,624 @@ +## Table of Contents + +[<< Day 2](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/02_Day/02_day_data_types.md) | [Day 4 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/04_Day/04_day_conditionals.md) + +![Thirty Days Of JavaScript](./day_1_3.png) + +- [πŸ“” Day 3](#%f0%9f%93%94-day-3) + - [Booleans](#booleans) + - [Truthy values](#truthy-values) + - [Falsy values](#falsy-values) + - [Undefined](#undefined) + - [Null](#null) + - [Operators](#operators) + - [Assignment operators](#assignment-operators) + - [Arithmetic Operators](#arithmetic-operators) + - [Comparison Operators](#comparison-operators) + - [Logical Operators](#logical-operators) + - [Increment Operator](#increment-operator) + - [Decrement Operator](#decrement-operator) + - [Ternary Operators](#ternary-operators) + - [Operator Precendence](#operator-precendence) + - [Window Methods](#window-methods) + - [Window alert() method](#window-alert-method) + - [Window prompt() method](#window-prompt-method) + - [Window confirm() method](#window-confirm-method) + - [Date Object](#date-object) + - [Creating a time object](#creating-a-time-object) + - [Getting full year](#getting-full-year) + - [Getting month](#getting-month) + - [Getting date](#getting-date) + - [Getting day](#getting-day) + - [Getting hours](#getting-hours) + - [Getting minutes](#getting-minutes) + - [Getting seconds](#getting-seconds) + - [Getting time](#getting-time) +- [πŸ’» Day 3: Exercises](#%f0%9f%92%bb-day-3-exercises) + - [1. Exercises: Data types Part](#1-exercises-data-types-part) + - [2. Exercises: Arithmetic Operators Part](#2-exercises-arithmetic-operators-part) + - [3. Exercises: Booleans Part](#3-exercises-booleans-part) + - [4. Exercises: Comparison Operators](#4-exercises-comparison-operators) + - [5. Exercises: Logical Operators](#5-exercises-logical-operators) + - [6 Ternary Operator](#6-ternary-operator) + - [7. Exercises: Date time Object](#7-exercises-date-time-object) + +# πŸ“” Day 3 + +## Booleans + +A boolean data type represents one of the two values:_true_ or _false_. Boolean value is either true or false. The use of these data types will be clear when you start the comparison operator. Any comparisons return a boolean value which is either true or false. + +**Example: Boolean Values** + +```js +let isLightOn = true +let isRaining = false +let isHungry = false +let isMarried = true +let truValue = 4 > 3 // true +let falseValue = 3 < 4 // false +``` + +We agreed that boolean values are either true or false. + +### Truthy values + +- All numbers(positive and negative) are truthy except zero +- All strings are truthy +- The boolean true + +### Falsy values + +- 0 +- 0n +- null +- undefined +- NaN +- the boolean false +- '', "", ``, empty string + +It is good to remember those truthy values and falsy values. In later section, we will use them with conditions to make decision. + +## Undefined + +If we declare a variable and if we do not assign a value, the value will be undefined. In addition to this, if a function is not returning the value will be undefined. + +```js +let firstName +console.log(firstName) //not defined, because it is not assigned to a value yet +``` + +## Null + +```js +let empty = null +console.log(empty) // -> null , means no value +``` + +## Operators + +### Assignment operators + +An equal sign in JavaScript is an assignment operator. It uses to assign a variable. + +```js +let firstName = 'Asabeneh' +let country = 'Finland' +``` + +Assignment Operators + +![Assignment operators](../images/assignment_operators.png) + +### Arithmetic Operators + +Arithmetic operators are mathematical operators. + +- Addition(+): a + b +- Subtraction(-): a - b +- Multiplication(_): a _ b +- Division(/): a / b +- Modulus(%):a % b +- Exponential(**):a ** b + +```js +let numOne = 4 +let numTwo = 3 +let sum = numOne + numTwo +let diff = numOne - numTwo +let mult = numOne * numTwo +let div = numOne / numTwo +let remainder = numOne % numTwo +let powerOf = numOne ** numTwo + +console.log(sum, diff, mult, div, remainder, powerOf) // 7,1,12,1.33,1, 64 + +let PI = 3.14 +let radius = 100 // length in meter + +const gravity = 9.81 // in m/s2 +let mass = 72 // in Kilogram +const boilingPoint = 100 // temperature in oC, boiling point of water +const bodyTemp = 37 // body temperature in oC + +//Let us calculate area of a circle +const areaOfCircle = PI * radius * radius +console.log(areaOfCircle) // 314 m + +// Let us calculate weight of an object +const weight = mass * gravity +console.log(weight) // 706.32 N(Newton) + +//Concatenating string with numbers using string interpolation +/* + The boiling point of water is 100 oC. + Human body temperature is 37 oC. + The gravity of earth is 9.81 m/s2. + */ +console.log( + `The boiling point of water is ${boilingPoint} oC.\nHuman body temperature is ${bodyTemp} oC.\nThe gravity of earth is ${gravity} m / s2.` +) +``` + +### Comparison Operators + +In programming we compare values, we use comparison operators to compare two values. We check if a value is greater or less or equal to other value. + +![Comparison Operators](../images/comparison_operators.png) +**Example: Comparison Operators** + +```js +console.log(3 > 2) // true, because 3 is greater than 2 +console.log(3 >= 2) // true, because 3 is greater than 2 +console.log(3 < 2) // false, because 3 is greater than 2 +console.log(2 < 3) // true, because 2 is less than 3 +console.log(2 <= 3) // true, because 2 is less than 3 +console.log(3 == 2) // false, because 3 is not equal to 2 +console.log(3 != 2) // true, because 3 is not equal to 2 +console.log(3 == '3') // true, compare only value +console.log(3 === '3') // false, compare both value and data type +console.log(3 !== '3') // true, compare both value and data type +console.log(3 !== '3') // true, compare both value and data type +console.log(3 != 3) // false, compare only value +console.log(3 !== 3) // false, compare both value and data type +console.log(0 == false) // true, equivalent +console.log(0 == '') // true, equivalent +console.log(0 == ' ') // true, equivalent +console.log(0 === '') // false, not exactly the same +console.log(0 === false) // false, not exactly the same +console.log(1 == true) // true, equivalent +console.log(1 === true) // false, not exactly the same +console.log(undefined == null) // true +console.log(undefined === null) // true +console.log(NaN == NaN) // false, not equal +console.log(NaN === NaN) // false +console.log(typeof NaN) // number + +console.log('mango'.length == 'avocado'.length) // false +console.log('mango'.length != 'avocado'.length) // true +console.log('mango'.length < 'avocado'.length) // true +console.log('milk'.length != 'meat'.length) // false +console.log('milk'.length == 'meat'.length) // true +console.log('tomato'.length == 'potato'.length) // true +console.log('python'.length > 'dragon'.length) // false +``` + +Try to understand the above comparisons with some logic. Remember without any logic might be difficult. +JavaScript is some how a wired kind of programming language. JavaScript code run and give you a result but unless you are good at it may not be the desired result. The following [link](https://dorey.github.io/JavaScript-Equality-Table/) has an exhaustive list of comparison of data types. + +### Logical Operators + +The following symbols are the common logical operators: +&&(ampersand) , ||(pipe) and !(negation). +&& gets true only if the two operands are true. +|| gets true either of the operand is true. +! negates true to false, false to true. + +```js +//&& ampersand operator example + +const check = 4 > 3 && 10 > 5 // true and true -> true +const check = 4 > 3 && 10 < 5 // true and false -> false +const check = 4 < 3 && 10 < 5 // false and false -> false + +//|| pipe or operator, example + +const check = 4 > 3 || 10 > 5 // true and true -> true +const check = 4 > 3 || 10 < 5 // true and false -> true +const check = 4 < 3 || 10 < 5 // false and false -> false + +//! Negation examples + +let check = 4 > 3 // true +let check = !(4 > 3) // false +let isLightOn = true +let isLightOff = !isLightOn // false +let isMarried = !false // true +``` + +### Increment Operator + +In JavaScrip we use the increment operator to increase a value stored in a variable. The increment could be pre or post increment. Let us see each of them: + +1. Pre-increment + +```js +let count = 0 +console.log(++count) // 1 +console.log(count) // 1 +``` + +1. Post-increment + +```js +let count = 0 +console.log(count++) // 0 +console.log(count) // 1 +``` + +We use most of the time post-increment. At leas you should remember how to use post-increment operator. + +### Decrement Operator + +In JavaScrip we use the decrement operator to decrease a value stored in a variable. The decrement could be pre or post decrement. Let us see each of them: + +1. Pre-decrement + +```js +let count = 0 +console.log(--count) // -1 +console.log(count) // -1 +``` + +2. Post-decrement + +```js +let count = 0 +console.log(count--) // 0 +console.log(count) // -1 +``` + +#### Ternary Operators + +Ternary operator allows to write a condition. +Another way to write conditionals is using ternary operators. Look at the following examples: + +```js +let isRaining = true +isRaining + ? console.log('You need a rain coat.') + : console.log('No need for a rain coat.') +isRaining = false + +isRaining + ? console.log('You need a rain coat.') + : console.log('No need for a rain coat.') +``` + +```sh +You need a rain coat. +No need for a rain coat. +``` + +```js +let number = 5 +number > 0 + ? console.log(`${number} is a positive number`) + : console.log(`${number} is a number number`) +number = -5 + +number > 0 + ? console.log(`${number} is a positive number`) + : console.log(`${number} is a number number`) +``` + +```sh +5 is a positive number +-5 is a number number +``` + +### Operator Precendence + +I would like to recommend you to read about operator precendence from this [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence) + +## Window Methods + +### Window alert() method + +As you have seen at very beginning alert() method displays an alert box with a specified message and an OK button. It is a builtin method and it takes on argument. + +```js +alert(message) +``` + +```js +alert('Welcome to 30DaysOfJavaScript') +``` + +Do not use too much alert because it is destructing and annoying, use it just for to test. + +### Window prompt() method + +The window prompt methods display a prompt box with an input on your browser to take input values and the input data can be stored in a variable. The prompt() method takes two arguments. The second argument is optional. + +```js +prompt('required text', 'optional text') +``` + +```js +let number = prompt('Enter number', 'number goes here') +console.log(number) +``` + +### Window confirm() method + +The confirm() method displays a dialog box with a specified message, along with an OK and a Cancel button. +A confirm box is often used to ask permission from a user to do something. Window confirm() takes an string as an argument. +Clicking the OK yields true value, clicking the Cancel button yields false value. + +```js +const agree = confirm('Are you sure you like to delete? ') +console.log(agree) // result will be true or false based on what you click on the dialog box +``` + +These are not all the window methods we will have a separate section to go deep into window methods. + +## Date Object + +Time is an important thing. We like to know the time a certain activity or event. In JavaScript current time and date is created using JavaScript Date Object. The object we create using Date object provides many methods to work with date and time.The methods we use to get date and time information from a date object values are started with a word _get_ because it provide the information. +_getFullYear(), getMonths(), getDate(), getDay(), getHours(), getMinutes, getSeconds(), getMilliseconds(), getTime(), getDay()_ + +![Date time Object](../images/date_time_object.png) + +### Creating a time object + +Once we create time object. The time object will provide information about time. Let us create a time object + +```js +const now = new Date() +console.log(now) // Sat Jan 04 2020 00:56:41 GMT+0200 (Eastern European Standard Time) +``` + +We have created a time object and we can access any date time information from the object using the get methods we have mentioned on the table. + +### Getting full year + +Let's extract or get the full from a time object. + +```js +const now = new Date() +console.log(now.getFullYear()) // 2020 +``` + +### Getting month + +Let's extract or get the month from a time object. + +```js +const now = new Date() +console.log(now.getMonth()) // 0, because the month is January, month(0-11) +``` + +### Getting date + +Let's extract or get the date of the month from a time object. + +```js +const now = new Date() +console.log(now.getDate()) // 4, because the day of the month is 4th, day(0-31) +``` + +### Getting day + +Let's extract or get the day of the week from a time object. + +```js +const now = new Date() +console.log(now.getDay()) // 6, because the day is Saturday which is the 5th day, +// Getting the weekday as a number (0-6) +``` + +### Getting hours + +Let's extract or get the hours from a time object. + +```js +const now = new Date() +console.log(now.getHours()) // 0, because the time is 00:56:41 +``` + +### Getting minutes + +Let's extract or get the minutes from a time object. + +```js +const now = new Date() +console.log(now.getMinutes()) // 56, because the time is 00:56:41 +``` + +### Getting seconds + +Let's extract or get the seconds from a time object. + +```js +const now = new Date() +console.log(now.getSeconds()) // 41, because the time is 00:56:41 +``` + +### Getting time + +This method give time in milliseconds starting from January 1, 1970. It is also know as Unix time. We can get the unix time in two ways: + +1. Using _getTime()_ + +```js +const now = new Date() // +console.log(now.getTime()) // 1578092201341, this is the number of seconds passed from January 1, 1970 to January 4, 2020 00:56:41 +``` + +1. Using _Date.now()_ + +```js +const allSeconds = Date.now() // +console.log(allSeconds) // 1578092201341, this is the number of seconds passed from January 1, 1970 to January 4, 2020 00:56:41 +const timeInSeconds = new Date().getTime() +console.log(allSeconds == timeInSeconds) // true +``` + +Let us format these values to a human readable time format. +**Example:** + +```js +const now = new Date() +const year = now.getFullYear() // return year +const month = now.getMonth() + 1 // return month(0 - 11) +const date = now.getDate() // return date (1 - 31) +const hours = now.getHours() // return number (0 - 23) +const minutes = now.getMinutes() // return number (0 -59) +console.log(`${date}/${month}/${year} ${hours}:${minutes}`) // 4/1/2020 0:56 +``` + +πŸŒ• You have boundless energy. You have just completed day 3 challenge and you are three steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle. + +# πŸ’» Day 3: Exercises + +## 1. Exercises: Data types Part + +1. Declare firstName, lastName, country, city, age, isMarried, year variable and assign value to it +1. The JavaScript typeof operator uses to check different data types. Check the data type of each variables from question number 1. +1. Check if type of '10' is equal to 10 +1. Check if parseInt('9.8') is equal to 10 + +## 2. Exercises: Arithmetic Operators Part + +1. Write a script that prompt the user to enter base and height of the triangle and calculate an area of a triangle (area = 0.5 x b x h). + + ```sh + Enter base: 20 + Enter height: 10 + The area of the triangle is 50 + ``` + +1. Write a script that prompt the user to enter side a, side b, and side c of the triangle and and calculate the perimeter of triangle (perimeter = a + b + c) + + ```sh + Enter side a: 5 + Enter side b: 4 + Enter side c: 3 + The perimeter of the triangle is 12 + ``` + +1. Get length and width using prompt and calculate an area of rectangle (area = length x width and the perimeter of rectangle (perimeter = 2 x (length + width)) +1. Get radius using prompt and calculate the area of a circle (area = pi x r x r) and circumference of a circle(c = 2 x pi x r) where pi = 3.14. +1. Calculate the slope, x-intercept and y-intercept of y = 2x -2 +1. Slope is (m = y2-y1/x2-x1). Find the slope between point (2, 2) and point(6,10) +1. Compare the slope of above two questions. +1. Calculate the value of y (y = x^2 + 6x + 9). Try to use different x values and figure out at what x value y is 0. +1. Writ a script that prompt a user to enters hours and rate per hour. Calculate pay of the person? + + ```sh + Enter hours: 40 + Enter rate per hour: 28 + Your weekly earning is 1120 + ``` + +1. Write a script that prompt the user to enter number of years. Calculate the number of seconds a person can live. Assume some one lives just hundred years + + ```sh + Enter number of yours you live: 100 + You lived 3153600000 seconds. + ``` + +## 3. Exercises: Booleans Part + +Boolean value is either true or false. + +1. Write three JavaScript statement which provide truthy value. +1. Write three JavaScript statement which provide falsy value. + +## 4. Exercises: Comparison Operators + +Figure out the result of the following comparison expression first without using console.log(). After you decide the result confirm it using console.log() + +1. 4 > 3 +1. 4 >= 3 +1. 4 < 3 +1. 4 <= 3 +1. 4 == 4 +1. 4 === 4 +1. 4 != 4 +1. 4 !== 4 +1. 4 != '4' +1. 4 == '4' +1. 4 === '4' + Find the length of python and jargon and make a falsy comparison statement. + +## 5. Exercises: Logical Operators + +1. Figure out the result of the following expressions first without using console.log(). After you decide the result confirm it by using console.log() + 1. 4 > 3 && 10 < 12 + 2. 4 > 3 && 10 > 12 + 3. 4 > 3 || 10 < 12 + 4. 4 > 3 || 10 > 12 + 5. !(4 > 3) + 6. !(4 < 3) + 7. !(false) + 8. !(4 > 3 && 10 < 12) + 9. !(4 > 3 && 10 > 12) + 10. !(4 === '4') +2. There is no 'on' in both dragon and python + +## 6 Ternary Operator + +1. If the length of your name is greater than 7 say, your name is long else say your name is short. +1. Compare your first name length and your family name length and you should get this output. + +```js +let firstName = 'Asabeneh' +let lastName = 'Yetayeh' +``` + +```sh +//Output +Your first name, Asabeneh is longer than your family name, Yetayeh +``` + +1. Declare two variables _myAge_ and _yourAge_ and assign them initial values and myAge and yourAge. + Output: + + ```js + let myAge = 250 + let yourAge = 25 + ``` + + ```sh + //output + I am 225 years older than you. + ``` + +1. Using prompt get the year the user was born and if the user is 18 or above allow the user to drive if not tell the user to wait a certain amount of years. + +```sh +// if the age is 25 +You are 25. You are old enough to drive +// if the age is under 18 + You are 15. You will be allowed to drive after 3 years. +``` + +## 7. Exercises: Date time Object + +1. What is the year today? +1. What is the month today as a number? +1. What is the date today? +1. What is the day today as a number? +1. What is the hours now? +1. What is the minutes now? +1. Find out the numbers of seconds elapsed from January 1, 1970 to now. +1. Create a human readable time format + 1. YYY-MM-DD HH:mm:ss + 2. DD-MM-YYYY HH:mm:ss + 3. DD/MM/YYY HH:mm:ss + +πŸŽ‰ CONGRATULATIONS ! πŸŽ‰ + +[<< Day 2](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/02_Day/02_day_data_types.md) | [Day 4 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/04_Day/04_day_conditionals.md) diff --git a/03_Day/day_1_3.png b/03_Day/day_1_3.png new file mode 100644 index 0000000..1268d2c Binary files /dev/null and b/03_Day/day_1_3.png differ diff --git a/04_Day/04_day_conditionals.md b/04_Day/04_day_conditionals.md new file mode 100644 index 0000000..e2a26a6 --- /dev/null +++ b/04_Day/04_day_conditionals.md @@ -0,0 +1,312 @@ +## Table of Contents + +[<< Day 3](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/03_Day/03_day_booleans_operators_date.md) | [Day 5 >>](#) +-- + +![Thirty Days Of JavaScript](./day_1_4.png) + +- [πŸ“” Day 4](#%f0%9f%93%94-day-4) + - [Conditionals](#conditionals) + - [If](#if) + - [If Else](#if-else) + - [If else if else](#if-else-if-else) + - [Switch](#switch) + - [Ternary Operators](#ternary-operators) +- [πŸ’» Exercise - 8 : Conditionals](#%f0%9f%92%bb-exercise---8--conditionals) + +# πŸ“” Day 4 + +## Conditionals + +Conditional statements are used to decision based on different conditions. +By default , statements in JavaScript script executed sequentially from top to bottom. If the processing logic require so, the sequential flow of execution can be altered in two ways: + +- Conditional execution: a block of one or more statements will be executed if a certain expression is true +- Repetitive execution: a block of one or more statements will be repetitively executed as long as a certain expression is true. In this section, we will cover _if_, _else_ , _else if_ statements. The comparison and logical operator we learned in the previous sections will be useful in here. + +Conditions can be implementing using the following ways: + +- if +- if else +- if else if else +- switch +- ternary operator + +### If + +In JavaScript and other programming languages the key word _if_ use to check if a condition is true and to execute the block code. To create an if condition, we need _if_ keyword, condition inside a parenthesis and block of code inside a curly bracket({}). + +```js +// syntax +if (condition) { + //this part of code run for truthy condition +} +``` + +**Example:** + +```js +let num = 3 +if (num > 0) { + console.log(`${num} is a positive number`) +} +// 3 is a positive number +``` + +```js +let isRaining = true +if (isRaining) { + console.log('Remember to take your rain coat.') +} +``` + +As you can see in the above condition, 3 is greater than 0 and it is a positive number. The condition was true and the block code was executed. However, if the condition is false, we do not see a result. The same goes for the second condition, if isRaining is false the if block will not be executed and we do not see an output. In order to see the result of the falsy condition, we should have another block, which is going to be _else_. + +### If Else + +If condition is true the first block will be executed, if not the else condition will be executed. + +```js +// syntax +if (condition) { + // this part of code run for truthy condition +} else { + // this part of code run for false condition +} +``` + +```js +let num = 3 +if (num > 0) { + console.log(`${num} is a positive number`) +} else { + console.log(`${num} is a negative number`) +} +// 3 is a positive number + +num = -3 +if (num > 0) { + console.log(`${num} is a positive number`) +} else { + console.log(`${num} is a negative number`) +} +// -3 is a negative number +``` + +```js +let isRaining = true +if (isRaining) { + console.log('You need a rain coat.') +} else { + console.log('No need for a rain coat.') +} +// You need a rain coat. + +isRaining = false +if (isRaining) { + console.log('You need a rain coat.') +} else { + console.log('No need for a rain coat.') +} +// No need for a rain coat. +``` + +The above condition is false, therefore the else block was executed. How about if our condition is more than two, we will use *ele if* conditions. + +### If else if else + +On our daily life, we make decision on daily basis. We make decision not by checking one or two conditions instead we make decisions based on multiple conditions. As similar to our daily life, programming is also full conditions. We use *else if* when we have multiple conditions. + +```js +// syntax +if (condition) { + // code +} else if (condition) { + // code +} else { + // code + +} +``` + +**Example:** + +```js +let a = 0 +if (a > 0) { + console.log(`A${a} is a positive number`) +} else if (a < 0) { + print(`${a} is a negative number`) + else if (a == 0) { + print(` ${a} is zero`) +} else { + print('${a) is not a number') +} +``` + +```js +// if else if else +let weather = 'sunny' +if (weather === 'rainy') { + console.log('You need a rain coat.') +} else if (weather === 'cloudy') { + console.log('It might be cold, you need a jacket.') +} else if (weather === 'sunny') { + console.log('Go out freely.') +} else { + console.log('No need for rain coat.') +} +``` + +### Switch + +Switch is an alternative for **if else if else else** + +```js +let weather = 'cloudy' +switch (weather) { + case 'rainy': + console.log('You need a rain coat.') + break + case 'cloudy': + console.log('It might be cold, you need a jacket.') + break + case 'sunny': + console.log('Go out freely.') + break + default: + console.log(' No need for rain coat.') +} +// Switch More Examples +var dayUserInput = prompt('What day is today ?') +var day = dayUserInput.toLowerCase() +switch (day) { + case 'monday': + console.log('Today is Monday') + break + case 'tuesday': + console.log('Today is Tuesday') + break + case 'wednesday': + console.log('Today is Wednesday') + break + case 'thursday': + console.log('Today is Thursday') + break + case 'friday': + console.log('Today is Friday') + break + case 'saturday': + console.log('Today is Saturday') + break + case 'sunday': + console.log('Today is Sunday') + break + + default: + console.log('It is not a week day.') +} +``` + +### Ternary Operators + +Another way to write conditionals is using ternary operators. We have covered this in other sections but we should also mention it here. + +```js +let isRaining = true +isRaining + ? console.log('You need a rain coat.') + : console.log('No need for a rain coat.') +``` + +πŸŒ• You are extraordinary and you have a remarkable potential. You have just completed day 4 challenge and you are four steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle. + +# πŸ’» Exercise - 8 : Conditionals + +1. Get user input using prompt(β€œEnter your age:”). If user is 18 or older , give feedback:You are old enough to drive but if not 18 give feedback to wait for the years he supposed to wait for. + + ```sh + Enter your age: 30 + You are old enough to drive. + + Enter your age:15 + You are left with 3 years to drive. + ``` + +1. Compare the values of myAge and yourAge using if … else. Based on the comparison log to console who is older (me or you). Use prompt(β€œEnter your age:”) to get the age as input. + + ```sh + Enter your age: 30 + You are 5 years older than me. + ``` + +1. If a is greater than b return a is greater than b else a is less than b. Do it both using if else and ternary operator. + + ```js + let a = 4 + let b = 3 + ``` + + ```sh + 4 is greater than 3 + ``` + +1. Write a code which give grade students according to theirs scores: + - 80-100, A + - 70-89, B + - 60-69, C + - 50-59, D + - 0 -49, F +1. Check if the season is Autumn, Winter, Spring or Summer. + If the user input is: + - September, October or November, the season is Autumn. + - December, January or February, the season is Winter. + - March, April or May, the season is Spring + - June, July or August, the season is Summer + +1. Even numbers are divisible by 2 and the remainder is zero. How do you check if a number is even or not using JavaScript? + + ```sh + Enter a number: 2 + 2 is an even number + + Enter a number 9 + 9 is is an odd number. + ``` + +1. Check if a day is week end day or a working day. Your script will take day as an input. + +```sh + What is the day is today? Saturday + Saturday is a weekend day. + + What is the day today? saturDaY + Saturday is a weekend day. + + What is the day today? Friday + Friday is a work day. + + What is the day today? FrIDAy + Friday is a work day. + ``` + +8. Write a program which tells the number days in a month. + + ```sh + Enter month: January + January has 31 days. + + Enter month: JANUARY + January has 31 day + + Enter month: February + February has 28 days. + + Enter month: FEbruary + February has 28 days. + ``` + + +πŸŽ‰ CONGRATULATIONS ! πŸŽ‰ + +[<< Day 3](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/03_Day/03_day_booleans_operators_date.md) | [Day 5 >>](#) \ No newline at end of file diff --git a/04_Day/day_1_4.png b/04_Day/day_1_4.png new file mode 100644 index 0000000..d5262c6 Binary files /dev/null and b/04_Day/day_1_4.png differ diff --git a/images/date_time_object.png b/images/date_time_object.png new file mode 100644 index 0000000..c5297c7 Binary files /dev/null and b/images/date_time_object.png differ diff --git a/images/day_1_1.png b/images/day_1_1.png new file mode 100644 index 0000000..dd583c7 Binary files /dev/null and b/images/day_1_1.png differ diff --git a/readMe.md b/readMe.md index 73f1d50..eb2037c 100644 --- a/readMe.md +++ b/readMe.md @@ -1,5 +1,9 @@ ## Table of Contents -![Thirty Days Of JavaScript](./images/30DaysOfJavaScript.png) + +[Day 2 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/02_Day/02_day_data_types.md) +-- + +![Thirty Days Of JavaScript](./images/day_1_1.png) - [πŸ“”Day 1](#%f0%9f%93%94day-1) - [Introduction](#introduction) @@ -33,40 +37,11 @@ - [Comments](#comments) - [Variables](#variables) - [πŸ’» Day 1: Exercises](#%f0%9f%92%bb-day-1-exercises) -- [πŸ“” Day 2](#%f0%9f%93%94-day-2) - - [Data types](#data-types) - - [Primitive Data Types](#primitive-data-types) - - [Non-Primitive Data Types](#non-primitive-data-types) - - [Numbers](#numbers) - - [Declaring number data types](#declaring-number-data-types) - - [Math Object](#math-object) - - [Strings](#strings) - - [String Concatenation](#string-concatenation) - - [Concatenating using addition operator](#concatenating-using-addition-operator) - - [Template Literals(Template Strings)](#template-literalstemplate-strings) - - [String Methods](#string-methods) - - [Booleans](#booleans-1) - - [Undefined](#undefined-1) - - [Null](#null-1) - - [Operators](#operators) - - [Assignment operators](#assignment-operators) - - [Arithmetic Operators](#arithmetic-operators) - - [Comparison Operators](#comparison-operators) - - [Logical Operators](#logical-operators) - - [Increment Operator](#increment-operator) - - [Decrement Operator](#decrement-operator) - - [Operator Precendence](#operator-precendence) -- [πŸ’» Day 2: Exercises](#%f0%9f%92%bb-day-2-exercises) - - [Exercises: String Part](#exercises-string-part) - - [Exercises: Data types Part](#exercises-data-types-part) - - [Exercises: Arithmetic Operators Part](#exercises-arithmetic-operators-part) - - [Exercises: Booleans Part](#exercises-booleans-part) - - [Exercises: Comparison Operators](#exercises-comparison-operators) - - [Exercises: Logical Operators](#exercises-logical-operators) - # πŸ“”Day 1 + ## Introduction + **Congratulations** for deciding to participate in a 30 days of JavaScript programming challenge . In this challenge you will learn everything you need to be a JavaScript programmer and in general the whole concepts of programming. In the end of the challenge you will get a 30DaysOfJavaScript programming challenge certificate. Join the [telegram group](https://t.me/ThirtyDaysOfJavaScript). **A 30DaysOfJavaScript** challenge is a guide for both beginners and advanced JavaScript developers. Welcome to JavaScript. I enjoy using and teaching JavaScript and I hope you will do so. JavaScript is the language of the browser. @@ -76,8 +51,11 @@ You use JavaScript **_to add interactivity to websites, to develop mobile apps, **_JavaScript (JS)_** has increased in popularity in recent years and has been the leading programming language for four consecutive years and is the most used programming language on Github. + ## Requirements + No prior knowledge of programming is required to follow this challenge. You need only: + 1. Motivation 2. Computer 3. Internet @@ -85,9 +63,11 @@ No prior knowledge of programming is required to follow this challenge. You need 5. Code Editor ## Setup -I believe you have the motivation and a strong desire to be a developer, computer and Internet. If you have those, then you have everything. + +I believe you have the motivation and a strong desire to be a developer, computer and Internet. If you have those, then you have everything. ### Install Node.js + You may not need it right now but you may need it for later. Install [node.js](https://nodejs.org/en/). ![Node download](images/download_node.png) @@ -102,21 +82,27 @@ We can check if node is installed in our local machine by opening our device ter asabeneh $ node -v v12.14.0 ``` + I am using node version 12.14.0, which is the recommended version of node. ### Browser + There are many browsers out there. However, I strongly recommend Google Chrome. + #### Installing Google Chrome + Install [google chrome](https://www.google.com/chrome/) if you do not have one yet. We can write small JavaScript code on the browser console, but we do not use the browser console to develop applications. ![Google Chrome](images/google_chrome.png) #### Opening Google Chrome Console + You can open Google Chrome either by clicking three dots at the top right corner of the Chrome browser or using a shortcut. I prefer using shortcuts. + ![Opening chrome](images/opening_developer_tool.png) +To open the Chrome console using a short cut. -To open the Chrome console using a short cut. ```sh Mac Command+Option+I @@ -124,6 +110,7 @@ Command+Option+I Windows: Ctl+Shift+I ``` + ![Opening console](images/opening_chrome_console_shortcut.png) After you open the Google Chrome console, try to explore the marked buttons. We will spend most of the time on the Console part. The Console is the place where your JavaScript code goes. The Google Console V8 engine changes your JavaScript code to machine code. @@ -132,7 +119,9 @@ Let us write a JavaScript code on the Google Chrome console: ![write code on console](./images/js_code_on_chrome_console.png) #### Writing Code on browser Console + We can write any JavaScript code on the Google console or any browser console. However, for this challenge, we only focus on Google Chrome console. Open the console using: + ```sh Mac Command+Option+I @@ -140,13 +129,19 @@ Command+Option+I Windows: Ctl+Shift+I ``` + ##### Console.log + To write our first JavaScript code, we used a builtin function **console.log()**. We passed an argument as input data, and the function displays the output. We passed 'Hello, World' as input data or argument in the console.log() function. + ```js console.log('Hello, World!') ``` + ##### Console.log with multiple arguments + The console.log(param1, param2, param3), can take multiple arguments. + ![console log multiple arguments](./images/console_log_multipl_arguments.png) ```js @@ -154,33 +149,37 @@ console.log('Hello', 'World', '!') console.log('HAPPY', 'NEW', 'YEAR', 2020) console.log('Welcome', 'to', 30, 'Days', 'Of', 'JavaScript') ``` + As you can see from the above snippet code, *console.log()* can take multiple arguments. -Congratulations! You wrote your first JavaScript code using *console.log()*. +Congratulations! You wrote your first JavaScript code using *console.log()*. + ##### Comment + We add comments to our code. Comments are very important to make code more readable and to leave remarks in our code. JavaScript does not execute the comment part of our code. Any text starts with // in JavaScript is a comment or anything enclose like this /* */ is a comment. -Example: Single Line Comment +**Example: Single Line Comment** - // This is the first comment - // This is the second comment - // I am a single line comment -Example: Multiline Comment + // This is the first comment + // This is the second comment + // I am a single line comment + +**Example: Multiline Comment** /* - This is a multiline comment - Multiline comments can take multiple lines - JavaScript is the language of the web + This is a multiline comment + Multiline comments can take multiple lines + JavaScript is the language of the web */ ##### Syntax + JavaScript is a programming language. As a result, it has its syntax like other programming languages. If we do not write a syntax that JavaScript understands, it will raise different types of errors. We will explore different kinds of JavaScript errors later. For now, let us see syntax errors. ![Error](images/raising_syntax_error.png) I made a deliberate mistake. As a result, the console raises a syntax error. Actually, the syntax is very informative. It informs what type of mistake we made. By reading the error feedback guideline, we can correct the syntax and fix the problem. The process of identifying and removing errors from a program is called debugging. Let us fix the errors: - ```js console.log("Hello, World!") console.log('Hello, World!') @@ -188,36 +187,43 @@ console.log('Hello, World!') So far, we saw how to display text using a *console.log()*. If we are printing text or string using *console.log()*, the text has to be under the single, double, or backtick. **Example:** + ```js console.log("Hello, World!") console.log('Hello, World!') console.log(`Hello, World!`) -``` +``` + #### Arithmetics -Now, let us practice more writing JavaScript codes using *console.log()* on google chrome console for number data types. +Now, let us practice more writing JavaScript codes using *console.log()* on google chrome console for number data types. In addition to the text, we can also do mathematical calculations using JavaScript. Let us do the following simple calculations. ![Arithmetic](images/arithmetic.png) + ```js console.log(2 + 3) // Addition console.log(3 - 2) // Subtraction console.log(2 * 3) // Multiplication console.log(3 / 2) // Division -console.log(3 % 2) // Modulus - finding remainder +console.log(3 % 2) // Modulus - finding remainder console.log(3 ** 2) // Exponential - -``` +``` ### Code Editor -We can write our codes on the browser console, but it won't be for bigger projects. In a real working environment, developers use different code editors to write their codes. In this 30 days python JavaScript challenge, we will use visual studio code. + +We can write our codes on the browser console, but it won't be for bigger projects. In a real working environment, developers use different code editors to write their codes. In this 30 days python JavaScript challenge, we will use visual studio code. + #### Installing Visual Studio Code + VVisual studio code is a very popular open-source text editor. I would recommend to [download](https://code.visualstudio.com/) visual studio code, but if you are in favor of other editors, feel free to follow with what you have. -![Vscode](images/vscode.png) +![Vscode](images/vscode.png) If you installed visual studio code, let us start using it. + #### How to use visual studio code + Open the visual studio code by double-clicking the visual studio icon. When you open it, you will get this kind of interface. Try to interact with the labeled icons. ![Vscode ui](./images/vscode_ui.png) @@ -228,6 +234,7 @@ Open the visual studio code by double-clicking the visual studio icon. When you ![coding running](./images/launched_on_new_tab.png) ## Adding JavaScript to a web page + JavaScript can be added to a web page in three different ways: - **_Inline script_** - **_Internal script_** @@ -247,13 +254,15 @@ Create a folder on your desktop and call it 30DaysOfJS or in any location and c 30DaysOfScript:Inline Script - + ``` + Now, you wrote your first inline script. We can create a pop up alert message using the built-in *alert()* function. ### Internal script + The internal script can be written in the _head_ or the _body_, but it is preferred to put it on the body of the HTML document. First, let us write on the head part of the page. @@ -263,14 +272,14 @@ First, let us write on the head part of the page. 30DaysOfScript:Internal Script - ``` + This is how we write the internal script most of the time. Writing the JavaScript code in the body section is the most preferred place. Open the browser console to see the output from the console.log() ```html @@ -287,12 +296,15 @@ This is how we write the internal script most of the time. Writing the JavaScrip ``` + Open the browser console to see the output from the console.log() ![js code from vscode](./images/js_code_vscode.png) ### External script + Similar to the internal script, the external script link can be on the header or body, but it is preferred to put it in the body. First, we should create an external JavaScript file with .js extension. Any JavaScript file ends with .js. Create a file introduction.js inside your project directory and write the following code and link this .js file at the bottom of the body. + ```js console.log('Welcome to 30DaysOfJavaScript') ``` @@ -310,7 +322,9 @@ External scripts in the head @@ -318,19 +332,24 @@ External scripts in the body 30DaysOfJavaScript:External script - //it could be in the header or in the body + //it could be in the header or in the body // Here is the recommended place to put the external script @@ -344,22 +363,25 @@ console.log('Hello, World!') b}`) -``` -```sh -2 is greater than 3: false -``` -### String Methods -Everything in JavaScript is an object. A string is a primitive data type that means we can not modify once it is created. The string object has many string methods. There are differnt string methods that can help us to work with strings. - -1. *length*: The string *length* method returns the number of characters in a string included empty space. - **Example:** - ```js - let js = 'JavaScript' - console.log(js.length) // 10 - let firstName = 'Asabeneh' - console.log(firstName.length) // 8 - ``` -2. *Accessing characters in a string*: We can access each character in a string using its index. In programming, counting starts from 0. The first index of the string is zero, and the last index is one minus the length of the string. - - ![Accessing sting by index](./images/string_indexes.png) -Let us access the first character in 'JavaScript' string. -```js -let string = 'JavaScript' -let firstLetter = string[0] -console.log(firstLetter) // J -let secondLetter = string[1] // a -let thirdLetter = string[2] -let lastLetter = string[9] -console.log(lastLetter) // t -let lastIndex = string.length - 1 -console.log(lastIndex) // 9 -console.log(string[lastIndex]) // t - -``` -3. *toUpperCase()*: this method changes the string to uppercase letters. -```js -let string = 'JavaScript' -console.log(string.toUpperCase()) // JAVASCRIPT -let firstName = 'Asabeneh' -console.log(firstName.toUpperCase()) // ASABENEH -let country = 'Finland' -console.log(country.toUpperCase()) // FINLAND - -``` - -4. *toLowerCase()*: this method changes the string to lowercase letters. -```js -let string = 'JavasCript' -console.log(string.toLowerCase()) // javascript -let firstName = 'Asabeneh' -console.log(firstName.toLowerCase()) // asabeneh -let country = 'Finland' -console.log(country.toLowerCase()) // finland - -``` -5. *substr()*: It takes two arguments,the starting index and number of characters to slice. -```js -let string = 'JavaScript' -console.log(string.substr(4,6)) // Script -let country = 'Finland' -console.log(country.substr(3, 4)) // land - -``` -6. *substring()*: It takes two arguments,the starting index and the stopping index but it doesn't include the stopping index. - -```js -let string = 'JavaScript' -console.log(string.substring(0,4)) // Java -console.log(string.substring(4,10)) // Script -console.log(string.substring(4)) // Script -let country = 'Finland' -console.log(country.substring(0, 3)) // Fin -console.log(country.substring(3, 7)) // land -console.log(country.substring(3)) // land - -``` -7. *split()*: The split method splits a string at a specified place. - -```js -let string = '30 Days Of JavaScipt' -console.log(string.split()) // ["30 Days Of JavaScript"] -console.log(string.split(' ')) // ["30", "Days", "Of", "JavaScript"] -let firstName = 'Asabeneh' -console.log(firstName.split()) // ["Asabeneh"] -console.log(firstName.split('')) // ["A", "s", "a", "b", "e", "n", "e", "h"] -let countries = 'Finland, Sweden, Norway, Denmark, and Iceland' -console.log(countries.split(',')) // ["Finland", " Sweden", " Norway", " Denmark", " and Iceland"] -console.log(countries.split(', ')) // Β ["Finland", "Sweden", "Norway", "Denmark", "and Iceland"] - -``` -8. *trim()*: Removes trailing space in the beginning or the end of a string. - -```js -let string = ' 30 Days Of JavaScript ' -console.log(string) // -console.log(string.trim(' ')) // -let firstName = ' Asabeneh ' -console.log(firstName) -console.log(firstName.trim()) // -``` -```sh - 30 Days Of JavasCript -30 Days Of JavasCript - Asabeneh -Asabeneh -``` -9. *includes()*: It takes a substring argument and it check if substring argument exists in the string. *includes()* returns a boolean. It checks if a substring exist in a string and it returns true if it exists and false if it doesn't exist. - -```js -let string = '30 Days Of JavaScript' -console.log(string.includes('Days')) // true -console.log(string.includes('days')) // false -console.log(string.includes('Script')) // true -console.log(string.includes('script')) // false -console.log(string.includes('java')) // false -console.log(string.includes('Java')) // true - -let country = 'Finland' -console.log(country.includes('fin')) // false -console.log(country.includes('Fin')) // true -console.log(country.includes('land')) // true -console.log(country.includes('Land')) // false - -``` -10. *replace()*: takes to parameter the old substring and new substring. - -```js -string.replace(oldsubstring, newsubstring) -``` -```js -let string = '30 Days Of JavaScript' -console.log(string.replace('JavaScript', 'Python')) // 30 Days Of Python -let country = 'Finland' -console.log(country.replace('Fin', 'Noman')) Nomanland -``` -11. *charAt()*: Takes index and it returns the value at that index -```js -string.charAt(index) -``` -```js -let string = '30 Days Of JavaScript' -console.log(string.charAt(0)) // 3 -let lastIndex = string.length - 1 -console.log(string.charAt(lastIndex)) // t - -``` -12. *charCodeAt()*: Takes index and it returns char code(ASCII number) of the value at that index -```js -string.charCodeAt(index) -``` -```js -let string = '30 Days Of JavaScript' -console.log(string.charCodeAt(3)) // D ASCII number is 51 -let lastIndex = string.length - 1 -console.log(string.charCodeAt(lastIndex)) // t ASCII is 116 - -``` -13. *indexOf()*: Takes takes a substring and if the substring exists in a string it returns the first position of the substring if does not exist it returns -1 -```js -string.indexOf(substring) -``` -```js -let string = '30 Days Of JavaScript' -console.log(string.indexOf('D')) // 3 -console.log(string.indexOf('Days')) // 3 -console.log(string.indexOf('days')) // -1 -console.log(string.indexOf('a')) // 4 -console.log(string.indexOf('JavaScript')) // 11 -console.log(string.indexOf('Script')) //15 -console.log(string.indexOf('script')) // -1 - -``` -14. *lastIndexOf()*: Takes takes a substring and if the substring exists in a string it returns the last position of the substring if it does not exist it returns -1 -```js -string.lastIndexOf(index) -``` -```js -let string = 'I love JavaScript. If you do not love JavaScript what else can you love.' -console.log(string.lastIndexOf('love')) // 67 -console.log(string.lastIndexOf('you')) // 63 -console.log(string.lastIndexOf('JavaScript')) // 38 - -``` - -15. *concat()*: it takes many substrings and creates concatenation. -```js -string.concat(substring, substring, substring) -``` -```js -let string = '30' -console.log(string.concat("Days", "Of", "JavaScript")) // 30DaysOfJavaScript -let country = 'Fin' -console.log(country.concat("land")) // Finland - -``` - -16. *startsWith*: it takes a substring as an argument and it checks if the string starts with that specified substring. It returns a boolean(true or false). -```js -string.startsWith(substring) -``` -```js -let string = 'Love is the best to in this world' -console.log(string.startsWith('Love')) // true -console.log(string.startsWith('love')) // false -console.log(string.startsWith('world')) // false - -let country = 'Finland' -console.log(country.startsWith('Fin')) // true -console.log(country.startsWith('fin')) // false -console.log(country.startsWith('land')) // false - -``` -17. *endsWith*: it takes a substring as an argument and it checks if the string starts with that specified substring. It returns a boolean(true or false). -```js -string.endsWith(substring) -``` -```js -let string = 'Love is the best to in this world' -console.log(string.endsWith('world')) // true -console.log(string.endsWith('love')) // false -console.log(string.endsWith('in this world')) // true - -let country = 'Finland' -console.log(country.endsWith('land')) // true -console.log(country.endsWith('fin')) // false -console.log(country.endsWith('Fin')) // false - -``` -18. *search*: it takes a substring as an argument and it returns the index of the first match. -```js -string.search(substring) -``` -```js -let string = 'I love JavaScript. If you do not love JavaScript what else can you love.' -console.log(string.search('love')) // 2 - -``` -19. *match*: it takes a substring or regular expression pattern as an argument and it returns an array if there is match if not it returns null. Let us see how a regular expression pattern looks like. It starts with / sign and ends with / sign. - ```js - let string = 'love' - let patternOne = /love/ // with out any flag - let patternTwo = /love/gi // g-means to search in the whole text, i - case insensitive - - ``` -```js -string.match(substring) -``` -```js -let string = 'I love JavaScript. If you do not love JavaScript what else can you love.' -console.log(string.match('love')) // -/* -output - -["love", index: 2, input: "I love JavaScript. If you do not love JavaScript what else can you love.", groups: undefined] -*/ -let pattern = /love/gi -console.log(string.match(pattern)) // ["love", "love", "love"] - -``` -Let us extract numbers from text using regular expression. This is not regular expression section, no panic. -```js - -let txt = 'In 2019, I run 30 Days of Pyhton. Now, in 2020 I super exited to start this challenge' -let regEx = /\d+/ // d with escape character means d not a normal d instead acts a digit -// + means one or more digit numbers, -// if there is g after that it means global, search everywhere. -console.log(txt.match(regEx)) // ["2", "0", "1", "9", "3", "0", "2", "0", "2", "0"] -console.log(txt.match(/\d+/g)) // ["2019", "30", "2020"] -``` -20. *repeat()*: it takes a number argument and it returned the repeated version of the string. -```js -string.repeat(n) -``` -```js -let string = 'love' -console.log(string.repeat(10)) // lovelovelovelovelovelovelovelovelovelove -``` - -## Booleans - -A boolean data type represents one of the two values:_true_ or _false_. Boolean value is either true or false. The use of these data types will be clear when you start the comparison operator. Any comparisons return a boolean value which is either true or false. - -**Example: Boolean Values** -```js -let isLightOn = true; -let isRaining = false; -let isHungery = false; -let isMarried = true; -``` - -## Undefined -If we declare a variable and if we do not assign a value, the value will be undefined. In addition to this, if a function is not returning the value will be undefined. - -```js -let firstName; -console.log(firstName); //not defined, because it is not assigned to a value yet -``` - -## Null - -```js -let empty = null; -console.log(empty); // -> null , means no value -``` - -## Operators - -### Assignment operators -An equal sign in JavaScript is an assignment operator. It uses to assign a variable. -```js -let firstName = 'Asabeneh' -let country = 'Finland' - -``` -Assignment Operators - -![Assignment operators](images/assignment_operators.png) - -### Arithmetic Operators -Arithmetic operators are mathematical operators. -- Addition(+): a + b -- Subtraction(-): a - b -- Multiplication(*):a * b -- Division(/): a / b -- Modulus(%):a % b -- Exponential(**):a ** b - -```js -let numOne = 4; -let numTwo = 3; -let sum = numOne + numTwo; -let diff = numOne - numTwo; -let mult = numOne * numTwo; -let div = numOne / numTwo; -let remainder = numOne % numTwo; -let powerOf = numOne ** numTwo -console.log(sum, diff, mult, div, remainder, powerOf); // ->7,1,12,1.33,1, 64 - -let PI = 3.14; -let radius = 100; // length in meter - -const gravity = 9.81; // in m/s2 -let mass = 72; // in Kilogram -const boilingPoint = 100; // temperature in oC, boiling point of water -const bodyTemp = 37; // body temperature in oC - -//Let us calculate area of a circle -const areaOfCircle = PI * radius * radius; -console.log(areaOfCircle); // -> 314 m -// Let us calculate weight of an object -const weight = mass * gravity; -console.log(weight); // -> 706.32 N(Newton) - -//Concatenating string with numbers using string interpolation -/* - The boiling point of water is 100 oC. - Human body temperature is 37 oC. - The gravity of earth is 9.81 m/s2. - */ -console.log( - `The boiling point of water is ${boilingPoint} oC.\nHuman body temperature is ${bodyTemp} oC.\nThe gravity of earth is ${gravity} m / s2.` -); -``` -### Comparison Operators - -In programming we compare values, we use comparison operators to compare two values. We check if a value is greater or less or equal to other value. - -![Comparison Operators](./images/comparison_operators.png) -**Example: Comparison Operators** - -```js -console.log(3 > 2) // true, because 3 is greater than 2 -console.log(3 >= 2) // true, because 3 is greater than 2 -console.log(3 < 2) // false, because 3 is greater than 2 -console.log(2 < 3) // true, because 2 is less than 3 -console.log(2 <= 3) // true, because 2 is less than 3 -console.log(3 == 2) // false, because 3 is not equal to 2 -console.log(3 != 2) // true, because 3 is not equal to 2 -console.log(3 == '3') // true, compare only value -console.log(3 === '3') // false, compare both value and data type -console.log(3 !== '3') // true, compare both value and data type -console.log(3 !== '3') // true, compare both value and data type -console.log(3 != 3) // false, compare only value -console.log(3 !== 3) // false, compare both value and data type - -console.log('mango'.length == 'avocado'.length) // false -console.log('mango'.length != 'avocado'.length) // true -console.log('mango'.length < 'avocado'.length) // true -console.log('milk'.length != 'meat'.length) // false -console.log('milk'.length == 'meat'.length) // true -console.log('tomato'.length == 'potato'.length) // true -console.log('python'.length > 'dragon'.length) // false -``` - -### Logical Operators - -The following symbols are the common logical operators: -&&(ampersand) , ||(pipe) and !(negation). -&& gets true only if the two operands are true. -|| gets true either of the operand is true. -! negates true to false, false to true. - -```js -//&& ampersand example -const check = 4 > 3 && 10 > 5; // true and true -> true -const check = 4 > 3 && 10 < 5; // true and false -> false -const check = 4 < 3 && 10 < 5; // false and false -> false -//|| pipe or, example -const check = 4 > 3 || 10 > 5; // true and true -> true -const check = 4 > 3 || 10 < 5; // true and false -> true -const check = 4 < 3 || 10 < 5; // false and false -> false -//! Negation examples -let check = 4 > 3; // -> true -let check = !(4 > 3); // -> false -let isLightOn = true; -let isLightOff = !isLightOn; // -> false -let isMarried = !false; // -> true -``` -### Increment Operator -In JavaScrip we use the increment operator to increase a value stored in a variable. The increment could be pre or post increment. Let us see each of them: -1. Pre-increment -```js -let count = 0 -console.log(++count) // 1 -console.log(count) // 1 -``` -2. Post-increment -```js -let count = 0 -console.log(count++) // 0 -console.log(count) // 1 -``` -We use most of the time post-increment. At leas you should remember how to use post-increment operator. -### Decrement Operator -In JavaScrip we use the decrement operator to decrease a value stored in a variable. The decrement could be pre or post decrement. Let us see each of them: -1. Pre-decrement -```js -let count = 0 -console.log(--count) // -1 -console.log(count) // -1 -``` -2. Post-decrement -```js -let count = 0 -console.log(count--) // 0 -console.log(count) // -1 -``` -### Operator Precendence -I would like to recommend you to read about operator precendence from this [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence) - -# πŸ’» Day 2: Exercises -## Exercises: String Part - -1. Declare a variable name challenge and assign it to an initial value **'30 Days Of JavaScript'**. -2. Print the string on the browser console using __console.log()__ -3. Print the __length__ of the string on the browser console using _console.log()_ -4. Change all the string to capital letters using __toUpperCase()__ method -5. Change all the string to lowercase letters using __toLowerCase()__ method -6. Cut(slice) out the first word of the string using __substr()__ or __substring()__ method -7. Slice out the phrase *Days Of JavaScript* from *30 Days Of JavaScript*. -8. Use __substr__ to slice out the phase __because because because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__ -9. Check if the string contains a word __Script__ using __includes()__ method -10. Split the __string__ into __array__ using __split()__ method -11. Split the string 30 Days Of JavaScript at the space using __split()__ method -12. 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon' __split__ the string at the comma and change it to an array. -13. Change 30 Days Of JavaScript to 30 Days Of Python using __replace()__ method. -14. What is character at index 15 in '30 Days Of JavaScript' string use __charAt()__ method. -15. What is the character code of J in '30 Days Of JavaScript' string using __charCodeAt()__ -16. Use __indexOf__ to determine the position of the first occurrence of a in 30 Days Of JavaScript -17. Use __lastIndexOf__ to determine the position of the last occurrence of a in 30 Days Of JavaScript. -18. Use __indexOf__ to find the position of the first occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__ -19. Use __lastIndexOf__ to find the position of the first occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__ -20. Use __search__ to find the position of the first occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__ -21. Use __trim()__ to remove if there is trailing whitespace at the beginning and the end of a string.E.g ' 30 Days Of JavaScript '. -22. Use __startsWith()__ method with the string *30 Days Of JavaScript* make the result true -23. Use __endsWith()__ method with the string *30 Days Of JavaScript* make the result true -24. Use __match()__ method to find all the a’s in 30 Days Of JavaScript -25. Use __match()__ to count the number all because's in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__ -26. Use __concat()__ and merge '30 Days of' and 'JavaScript' to a single string, '30 Days Of JavaScript' -27. Use __repeat()__ method to print 30 Days Of JavaScript 2 times -28. Love is the best thing in this world. Some found their love and some are still looking for their love. Count the number of word love in this sentence. -29. Calculate the total annual income of the person by extract the numbers from the following text. 'He earns 5000 euro from salary per month, 10000 euro annual bonus, 15000 euro online courses per month.' -30. Clean the following text and find the most frequent word(hint, use replace and regular express). -```js - const sentence = '%I $am@% a %tea@cher%, &and& I lo%#ve %tea@ching%;. There $is nothing; &as& mo@re rewarding as educa@ting &and& @emp%o@wering peo@ple. ;I found tea@ching m%o@re interesting tha@n any other %jo@bs. %Do@es thi%s mo@tivate yo@u to be a tea@cher!? %Th#is 30#Days&OfJavaScript &is also $the $result of &love& of tea&ching' -``` -## Exercises: Data types Part -1. Declare firstName, lastName, country, city, age, isMarried, year variable and assign value to it - -1. The JavaScript typeof operator uses to check different data types. Check the data type of each variables from question number 1. - -## Exercises: Arithmetic Operators Part -JavaScript arithmetic operators are addition(+), subtraction(-), multiplication(*), division(/), modulus(%), exponential(**), increment(++) and decrement(--). - -```js -let operandOne = 4; -let operandTwo = 3; -``` -Using the above operands apply different JavaScript arithmetic operations. - -## Exercises: Booleans Part - -Boolean value is either true or false. - -1. Write three JavaScript statement which provide truthy value. -1. Write three JavaScript statement which provide falsy value. - -## Exercises: Comparison Operators - -Figure out the result of the following comparison expression first without using console.log(). After you decide the result confirm it using console.log() - -1. 4 > 3 -1. 4 >= 3 -1. 4 < 3 -1. 4 <= 3 -1. 4 == 4 -1. 4 === 4 -1. 4 != 4 -1. 4 !== 4 -1. 4 != '4' -1. 4 == '4' -1. 4 === '4' - -## Exercises: Logical Operators -Figure out the result of the following expressions first without using console.log(). After you decide the result confirm it by using console.log() -1. 4 > 3 && 10 < 12 -1. 4 > 3 && 10 > 12 -1. 4 > 3 || 10 < 12 -1. 4 > 3 || 10 > 12 -1. !(4 > 3) -1. !(4 < 3) -1. !(false) -1. !(4 > 3 && 10 < 12) -1. !(4 > 3 && 10 > 12) -1. !(4 === '4') - - - +πŸŽ‰ CONGRATULATIONS ! πŸŽ‰ +[Day 2 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/02_Day/02_day_data_types.md)