diff --git a/04_Day_Conditionals/04_day_conditionals.md b/04_Day_Conditionals/04_day_conditionals.md index 0100844..74db7ef 100644 --- a/04_Day_Conditionals/04_day_conditionals.md +++ b/04_Day_Conditionals/04_day_conditionals.md @@ -325,10 +325,10 @@ isRaining 1. Write a code which can give grades to students according to theirs scores: - 80-100, A - - 70-89, B - - 60-69, C - - 50-59, D - - 0-49, F + - 80-89, B + - 70-79, C + - 60-69, D + - 0-59, 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. diff --git a/Polish/images/projects/dom_min_project_solar_system_day_4.1.gif b/Polish/images/projects/dom_min_project_solar_system_day_4.1.gif deleted file mode 100644 index d88b04b..0000000 Binary files a/Polish/images/projects/dom_min_project_solar_system_day_4.1.gif and /dev/null differ diff --git a/Polish/images/projects/dom_min_project_solar_system_day_4.1.mkv b/Polish/images/projects/dom_min_project_solar_system_day_4.1.mkv deleted file mode 100644 index 1ed941c..0000000 Binary files a/Polish/images/projects/dom_min_project_solar_system_day_4.1.mkv and /dev/null differ diff --git a/Polish/images/projects/dom_min_project_solar_system_day_4.1.mp4 b/Polish/images/projects/dom_min_project_solar_system_day_4.1.mp4 deleted file mode 100644 index 69ce936..0000000 Binary files a/Polish/images/projects/dom_min_project_solar_system_day_4.1.mp4 and /dev/null differ diff --git a/Polish/images/projects/dom_mini_project_challenge_info_day_2.3.gif b/Polish/images/projects/dom_mini_project_challenge_info_day_2.3.gif deleted file mode 100644 index 571ea6f..0000000 Binary files a/Polish/images/projects/dom_mini_project_challenge_info_day_2.3.gif and /dev/null differ diff --git a/Polish/images/projects/dom_mini_project_challenge_info_day_2.3.png b/Polish/images/projects/dom_mini_project_challenge_info_day_2.3.png deleted file mode 100644 index 3387bea..0000000 Binary files a/Polish/images/projects/dom_mini_project_challenge_info_day_2.3.png and /dev/null differ diff --git a/Polish/images/projects/dom_mini_project_countries_day_6.1.gif b/Polish/images/projects/dom_mini_project_countries_day_6.1.gif deleted file mode 100644 index 8a8f09a..0000000 Binary files a/Polish/images/projects/dom_mini_project_countries_day_6.1.gif and /dev/null differ diff --git a/Polish/images/projects/dom_mini_project_countries_object_day_10.1.gif b/Polish/images/projects/dom_mini_project_countries_object_day_10.1.gif deleted file mode 100644 index 03b1e35..0000000 Binary files a/Polish/images/projects/dom_mini_project_countries_object_day_10.1.gif and /dev/null differ diff --git a/Polish/images/projects/dom_mini_project_form_validation_day_10.2.1.png b/Polish/images/projects/dom_mini_project_form_validation_day_10.2.1.png deleted file mode 100644 index 9d2c2b3..0000000 Binary files a/Polish/images/projects/dom_mini_project_form_validation_day_10.2.1.png and /dev/null differ diff --git a/Polish/images/projects/dom_mini_project_form_validation_day_10.2.png b/Polish/images/projects/dom_mini_project_form_validation_day_10.2.png deleted file mode 100644 index ca7cdd5..0000000 Binary files a/Polish/images/projects/dom_mini_project_form_validation_day_10.2.png and /dev/null differ diff --git a/Polish/images/projects/dom_mini_project_leaderboard_day_8.1.gif b/Polish/images/projects/dom_mini_project_leaderboard_day_8.1.gif deleted file mode 100644 index 789d0cb..0000000 Binary files a/Polish/images/projects/dom_mini_project_leaderboard_day_8.1.gif and /dev/null differ diff --git a/Polish/images/projects/dom_mini_project_leaderboard_day_8.1.png b/Polish/images/projects/dom_mini_project_leaderboard_day_8.1.png deleted file mode 100644 index 2956fa0..0000000 Binary files a/Polish/images/projects/dom_mini_project_leaderboard_day_8.1.png and /dev/null differ diff --git a/Polish/images/projects/dom_mini_project_slider_day_7.1.gif b/Polish/images/projects/dom_mini_project_slider_day_7.1.gif deleted file mode 100644 index 51bdadb..0000000 Binary files a/Polish/images/projects/dom_mini_project_slider_day_7.1.gif and /dev/null differ diff --git a/Polish/images/raising_syntax_error.png b/Polish/images/raising_syntax_error.png deleted file mode 100644 index 81f6245..0000000 Binary files a/Polish/images/raising_syntax_error.png and /dev/null differ diff --git a/Polish/images/regex.png b/Polish/images/regex.png deleted file mode 100644 index c7116b4..0000000 Binary files a/Polish/images/regex.png and /dev/null differ diff --git a/Polish/images/running_script.png b/Polish/images/running_script.png deleted file mode 100644 index deac13d..0000000 Binary files a/Polish/images/running_script.png and /dev/null differ diff --git a/Polish/images/scripts_on_vscode.png b/Polish/images/scripts_on_vscode.png deleted file mode 100644 index f6257be..0000000 Binary files a/Polish/images/scripts_on_vscode.png and /dev/null differ diff --git a/Polish/images/string_indexes.png b/Polish/images/string_indexes.png deleted file mode 100644 index cc2f638..0000000 Binary files a/Polish/images/string_indexes.png and /dev/null differ diff --git a/Polish/images/vscode.png b/Polish/images/vscode.png deleted file mode 100644 index 724fc10..0000000 Binary files a/Polish/images/vscode.png and /dev/null differ diff --git a/Polish/images/vscode_ui.png b/Polish/images/vscode_ui.png deleted file mode 100644 index 7210a08..0000000 Binary files a/Polish/images/vscode_ui.png and /dev/null differ diff --git a/Polish/images/web_storage.png b/Polish/images/web_storage.png deleted file mode 100644 index 46f9311..0000000 Binary files a/Polish/images/web_storage.png and /dev/null differ diff --git a/Polish/index.html b/Polish/index.html deleted file mode 100644 index 14e41c3..0000000 --- a/Polish/index.html +++ /dev/null @@ -1,128 +0,0 @@ - - - - - Document Object Model:30 Days Of JavaScript - - - - - - -
-

Asabeneh Yetayeh challenges in 2020

-

30DaysOfJavaScript Challenge

-

- -
- - - - - \ No newline at end of file diff --git a/Polish/readMe.md b/Polish/readMe.md deleted file mode 100644 index b032cf2..0000000 --- a/Polish/readMe.md +++ /dev/null @@ -1,670 +0,0 @@ -# 30 Days Of JavaScript - -| # Day | Topics | -| ----- | :-----------------------------------------------------------------------------------------------------------------------------------------------: | -| 01 | [wprowadzenie](./readMe.md) | -| 02 | [Typy danych](./02_Day_Data_types/02_day_data_types.md) | -| 03 | [Boole'a, operatory, data](./03_Day_Booleans_operators_date/03_booleans_operators_date.md) | -| 04 | [Warunkowe](./04_Day_Conditionals/04_day_conditionals.md) | -| 05 | [Tablice](./05_Day_Arrays/05_day_arrays.md) | -| 06 | [Pętle](./06_Day_Loops/06_day_loops.md) | -| 07 | [Funkcje](./07_Day_Functions/07_day_functions.md) | -| 08 | [Obiekty](./08_Day_Objects/08_day_objects.md) | -| 09 | [Funkcje wyższego rzędu](./09_Day_Higher_order_functions/09_day_higher_order_functions.md) | -| 10 | [Zestawy i mapy](./10_Day_Sets_and_Maps/10_day_Sets_and_Maps.md) | -| 11 | [Destrukturyzacja i rozprzestrzenianie](./11_Day_Destructuring_and_spreading/11_day_destructuring_and_spreading.md) | -| 12 | [Wyrażenia regularne](./12_Day_Regular_expressions/12_day_regular_expressions.md) | -| 13 | [Metody obiektów konsoli](./13_Day_Console_object_methods/13_day_console_object_methods.md) | -| 14 | [Obsługa błędów](./14_Day_Error_handling/14_day_error_handling.md) | -| 15 | [Klasy](./15_Day_Classes/15_day_classes.md) | -| 16 | [JSON](./16_Day_JSON/16_day_json.md) | -| 17 | [Magazyny internetowe](./17_Day_Web_storages/17_day_web_storages.md) | -| 18 | [Obietnice](./18_Day_Promises/18_day_promises.md) | -| 19 | [Zamknięcie](./19_Day_Closures/19_day_closures.md) | -| 20 | [Pisanie czystego kodu](./20_Day_Writing_clean_codes/20_day_writing_clean_codes.md) | -| 21 | [DOM](./21_Day_DOM/21_day_dom.md) | -| 22 | [Manipulowanie obiektem DOM](./22_Day_Manipulating_DOM_object/22_day_manipulating_DOM_object.md) | -| 23 | [Słuchacze zdarzeń](./23_Day_Event_listeners/23_day_event_listeners.md) | -| 24 | [Mini Projekt: Układ Słoneczny](./24_Day_Project_solar_system/24_day_project_solar_system.md) | -| 25 | [Mini Projekt: Wizualizacja danych krajów świata 1](./25_Day_World_countries_data_visualization_1/25_day_world_countries_data_visualization_1.md) | -| 26 | [Mini Projekt: Wizualizacja danych krajów świata 2](./26_Day_World_countries_data_visualization_2/26_day_world_countries_data_visualization_2.md) | -| 27 | [Mini Projekt: Portfolio](./27_Day_Mini_project_portfolio/27_day_mini_project_portfolio.md) | -| 28 | [Mini projekt: Tablica wyników](./28_Day_Mini_project_leaderboard/28_day_mini_project_leaderboard.md) | -| 29 | [Mini Projekt: animowane postacie](./29_Day_Mini_project_animating_characters/29_day_mini_project_animating_characters.md) | -| 30 | [Projekty końcowe](./30_Day_Mini_project_final/30_day_mini_project_final.md) | - -🧡🧡🧡 HAPPY CODING 🧡🧡🧡 - -
-

30 Days Of JavaScript: Introduction

- - - - - Twitter Follow - - -Author: -Asabeneh Yetayeh
- January, 2020 -
- -
- -🇬🇧 [English](./readMe.md) -🇪🇸 [Spanish](./Spanish/readme.md) -🇷🇺 [Russian](./RU/README.md) -🇦🇿 [Azerbaijan](./Azerbaijani/readMe.md) -KR [Korean](./Korea/README.md) -🇻🇳 [Vietnamese](./Vietnamese/README.md) - -
- -
- - -[Day 2 >>](./02_Day_Data_types/02_day_data_types.md) - -![Thirty Days Of JavaScript](./images/day_1_1.png) - -- [30 Days Of JavaScript](#30-days-of-javascript) -- [📔 Day 1](#-day-1) - - [Introduction](#introduction) - - [Requirements](#requirements) - - [Setup](#setup) - - [Install Node.js](#install-nodejs) - - [Browser](#browser) - - [Installing Google Chrome](#installing-google-chrome) - - [Opening Google Chrome Console](#opening-google-chrome-console) - - [Writing Code on Browser Console](#writing-code-on-browser-console) - - [Console.log](#consolelog) - - [Console.log with Multiple Arguments](#consolelog-with-multiple-arguments) - - [Comments](#comments) - - [Syntax](#syntax) - - [Arithmetics](#arithmetics) - - [Code Editor](#code-editor) - - [Installing Visual Studio Code](#installing-visual-studio-code) - - [How to Use Visual Studio Code](#how-to-use-visual-studio-code) - - [Adding JavaScript to a Web Page](#adding-javascript-to-a-web-page) - - [Inline Script](#inline-script) - - [Internal Script](#internal-script) - - [External Script](#external-script) - - [Multiple External Scripts](#multiple-external-scripts) - - [Introduction to Data types](#introduction-to-data-types) - - [Numbers](#numbers) - - [Strings](#strings) - - [Booleans](#booleans) - - [Undefined](#undefined) - - [Null](#null) - - [Checking Data Types](#checking-data-types) - - [Comments Again](#comments-again) - - [Variables](#variables) -- [💻 Day 1: Exercises](#-day-1-exercises) - -# 📔 Day 1 - -## Introduction - -**Congratulations** on deciding to participate in 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 concept of programming. In the end of the challenge you will get a 30DaysOfJavaScript programming challenge completion certificate. In case you need help or if you would like to help others you may join the [telegram group](https://t.me/ThirtyDaysOfJavaScript). - -**A 30DaysOfJavaScript** challenge is a guide for both beginners and advanced JavaScript developers. Welcome to JavaScript. JavaScript is the language of the web. I enjoy using and teaching JavaScript and I hope you will do so too. - -In this step by step JavaScript challenge, you will learn JavaScript, the most popular programming language in the history of mankind. -JavaScript is used **_to add interactivity to websites, to develop mobile apps, desktop applications, games_** and nowadays JavaScript can be used for **_machine learning_** and **_AI_**. -**_JavaScript (JS)_** has increased in popularity in recent years and has been the leading -programming language for six 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. A computer -3. Internet -4. A browser -5. A code editor - -## Setup - -I believe you have the motivation and a strong desire to be a developer, a computer and Internet. If you have those, then you have everything to get started. - -### Install Node.js - -You may not need Node.js right now but you may need it for later. Install [node.js](https://nodejs.org/en/). - -![Node download](images/download_node.png) - -After downloading double click and install - -![Install node](images/install_node.png) - -We can check if node is installed on our local machine by opening our device terminal or command prompt. - -```sh -asabeneh $ node -v -v12.14.0 -``` - -When making this tutorial I was using Node version 12.14.0, but now the recommended version of Node.js for download is v14.17.6, by the time you use this material you may have a higher Node.js version. - -### 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 console either by clicking three dots at the top right corner of the browser, selecting _More tools -> Developer tools_ or using a keyboard shortcut. I prefer using shortcuts. - -![Opening chrome](images/opening_developer_tool.png) - -To open the Chrome console using a keyboard shortcut. - -```sh -Mac -Command+Option+J - -Windows/Linux: -Ctl+Shift+J -``` - -![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. The Console is the place where your JavaScript code goes. The Google Console V8 engine changes your JavaScript code to machine code. -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 - -Windows: -Ctl+Shift+I -``` - -##### Console.log - -To write our first JavaScript code, we used a built-in 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()`** function can take multiple parameters separated by commas. The syntax looks like as follows:**`console.log(param1, param2, param3)`** - -![console log multiple arguments](./images/console_log_multipl_arguments.png) - -```js -console.log("Hello", "World", "!"); -console.log("HAPPY", "NEW", "YEAR", 2020); -console.log("Welcome", "to", 30, "Days", "Of", "JavaScript"); -``` - -As you can see from the snippet code above, _`console.log()`_ can take multiple arguments. - -Congratulations! You wrote your first JavaScript code using _`console.log()`_. - -##### Comments - -We can 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. In JavaScript, any text line starting with // in JavaScript is a comment, and anything enclosed like this `//` is also a comment. - -**Example: Single Line Comment** - -```js -// This is the first comment -// This is the second comment -// I am a single line comment -``` - -**Example: Multiline Comment** - -```js -/* -This is a multiline comment - Multiline comments can take multiple lines - JavaScript is the language of the web - */ -``` - -##### Syntax - -Programming languages are similar to human languages. English or many other language uses words, phrases, sentences, compound sentences and other more to convey a meaningful message. The English meaning of syntax is _the arrangement of words and phrases to create well-formed sentences in a language_. The technical definition of syntax is the structure of statements in a computer language. Programming languages have syntax. JavaScript is a programming language and like other programming languages it has its own syntax. 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 syntax errors. Actually, the syntax is very informative. It informs what type of mistake was 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!"); -``` - -So far, we saw how to display text using the _`console.log()`_. If we are printing text or string using _`console.log()`_, the text has to be inside the single quotes, double quotes, or a 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. -In addition to the text, we can also do mathematical calculations using JavaScript. Let us do the following simple calculations. -It is possible to write JavaScript code on Google Chrome console can directly without the **_`console.log()`_** function. However, it is included in this introduction because most of this challenge would be taking place in a text editor where the usage of the function would be mandatory. You can play around directly with instructions on the console. - -![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); // Exponentiation 3 ** 2 == 3 * 3 -``` - -### 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 of JavaScript challenge, we will be using Visual Studio Code. - -#### Installing Visual Studio Code - -Visual Studio Code is a very popular open-source text editor. I would recommend to [download Visual Studio Code](https://code.visualstudio.com/), but if you are in favor of other editors, feel free to follow with what you have. - -![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 its 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) - -![Vscode add project](./images/adding_project_to_vscode.png) - -![Vscode open project](./images/opening_project_on_vscode.png) - -![script file](images/scripts_on_vscode.png) - -![Installing Live Server](images/vsc_live_server.png) - -![running script](./images/running_script.png) - -![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_** -- **_External script_** -- **_Multiple External scripts_** - -The following sections show different ways of adding JavaScript code to your web page. - -### Inline Script - -Create a project folder on your desktop or in any location, name it 30DaysOfJS and create an **_`index.html`_** file in the project folder. Then paste the following code and open it in a browser, for example [Chrome](https://www.google.com/chrome/). - -```html - - - - 30DaysOfScript:Inline Script - - - - - -``` - -Now, you just wrote your first inline script. We can create a pop up alert message using the _`alert()`_ built-in 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. - -```html - - - - 30DaysOfScript:Internal Script - - - - -``` - -This is how we write an internal script most of the time. Writing the JavaScript code in the body section is the most preferred option. Open the browser console to see the output from the `console.log()`. - -```html - - - - 30DaysOfScript:Internal Script - - - - - - -``` - -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. All files ending with .js extension are JavaScript files. Create a file named 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"); -``` - -External scripts in the _head_: - -```html - - - - 30DaysOfJavaScript:External script - - - - -``` - -External scripts in the _body_: - -```html - - - - 30DaysOfJavaScript:External script - - - - - - - -``` - -Open the browser console to see the output of the `console.log()`. - -### Multiple External Scripts - -We can also link multiple external JavaScript files to a web page. -Create a `helloworld.js` file inside the 30DaysOfJS folder and write the following code. - -```js -console.log("Hello, World!"); -``` - -```html - - - - Multiple External Scripts - - - - - - -``` - -_Your main.js file should be below all other scripts_. It is very important to remember this. - -![Multiple Script](./images/multiple_script.png) - -## Introduction to Data types - -In JavaScript and also other programming languages, there are different types of data types. The following are JavaScript primitive data types: _String, Number, Boolean, undefined, Null_, and _Symbol_. - -### Numbers - -- Integers: Integer (negative, zero and positive) numbers - Example: - ... -3, -2, -1, 0, 1, 2, 3 ... -- Float-point numbers: Decimal number - Example - ... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ... - -### Strings - -A collection of one or more characters between two single quotes, double quotes, or backticks. - -**Example:** - -```js -"a"; -"Asabeneh"; -"Asabeneh"; -"Finland"; -"JavaScript is a beautiful programming language"; -"I love teaching"; -"I hope you are enjoying the first day"`We can also create a string using a backtick`; -("A string could be just as small as one character or as big as many pages"); -("Any data type under a single quote, double quote or backtick is a string"); -``` - -### Booleans - -A boolean value is either True or False. Any comparisons returns a boolean value, which is either true or false. - -A boolean data type is either a true or false value. - -**Example:** - -```js -true; // if the light is on, the value is true -false; // if the light is off, the value is false -``` - -### Undefined - -In JavaScript, if we don't assign a value to a variable, the value is undefined. In addition to that, if a function is not returning anything, it returns undefined. - -```js -let firstName; -console.log(firstName); // undefined, because it is not assigned to a value yet -``` - -### Null - -Null in JavaScript means an empty value. - -```js -let emptyValue = null; -``` - -## Checking Data Types - -To check the data type of a certain variable, we use the **typeof** operator. See the following example. - -```js -console.log(typeof "Asabeneh"); // string -console.log(typeof 5); // number -console.log(typeof true); // boolean -console.log(typeof null); // object type -console.log(typeof undefined); // undefined -``` - -## Comments Again - -Remember that commenting in JavaScript is similar to other programming languages. Comments are important in making your code more readable. -There are two ways of commenting: - -- _Single line commenting_ -- _Multiline commenting_ - -```js -// commenting the code itself with a single comment -// let firstName = 'Asabeneh'; single line comment -// let lastName = 'Yetayeh'; single line comment -``` - -Multiline commenting: - -```js -/* - let location = 'Helsinki'; - let age = 100; - let isMarried = true; - This is a Multiple line comment -*/ -``` - -## Variables - -Variables are _containers_ of data. Variables are used to _store_ data in a memory location. When a variable is declared, a memory location is reserved. When a variable is assigned to a value (data), the memory space will be filled with that data. To declare a variable, we use _var_, _let_, or _const_ keywords. - -For a variable that changes at a different time, we use _let_. If the data does not change at all, we use _const_. For example, PI, country name, gravity do not change, and we can use _const_. We will not use var in this challenge and I don't recommend you to use it. It is error prone way of declaring variable it has lots of leak. We will talk more about var, let, and const in detail in other sections (scope). For now, the above explanation is enough. - -A valid JavaScript variable name must follow the following rules: - -- A JavaScript variable name should not begin with a number. -- A JavaScript variable name does not allow special characters except dollar sign and underscore. -- A JavaScript variable name follows a camelCase convention. -- A JavaScript variable name should not have space between words. - -The following are examples of valid JavaScript variables. - -```js -firstName; -lastName; -country; -city; -capitalCity; -age; -isMarried; - -first_name; -last_name; -is_married; -capital_city; - -num1; -num_1; -_num_1; -$num1; -year2020; -year_2020; -``` - -The first and second variables on the list follows the camelCase convention of declaring in JavaScript. In this material, we will use camelCase variables(camelWithOneHump). We use CamelCase(CamelWithTwoHump) to declare classes, we will discuss about classes and objects in other section. - -Example of invalid variables: - -```js - first-name - 1_num - num_#_1 -``` - -Let us declare variables with different data types. To declare a variable, we need to use _let_ or _const_ keyword before the variable name. Following the variable name, we write an equal sign (assignment operator), and a value(assigned data). - -```js -// Syntax -let nameOfVariable = value; -``` - -The nameOfVriable is the name that stores different data of value. See below for detail examples. - -**Examples of declared variables** - -```js -// Declaring different variables of different data types -let firstName = "Asabeneh"; // first name of a person -let lastName = "Yetayeh"; // last name of a person -let country = "Finland"; // country -let city = "Helsinki"; // capital city -let age = 100; // age in years -let isMarried = true; - -console.log(firstName, lastName, country, city, age, isMarried); -``` - -```sh -Asabeneh Yetayeh Finland Helsinki 100 true -``` - -```js -// Declaring variables with number values -let age = 100; // age in years -const gravity = 9.81; // earth gravity in m/s2 -const boilingPoint = 100; // water boiling point, temperature in °C -const PI = 3.14; // geometrical constant -console.log(gravity, boilingPoint, PI); -``` - -```sh -9.81 100 3.14 -``` - -```js -// Variables can also be declaring in one line separated by comma, however I recommend to use a seperate line to make code more readble -let name = "Asabeneh", - job = "teacher", - live = "Finland"; -console.log(name, job, live); -``` - -```sh -Asabeneh teacher Finland -``` - -When you run _index.html_ file in the 01-Day folder you should get this: - -![Day one](./images/day_1.png) - -🌕 You are amazing! You have just completed day 1 challenge and you are on your way to greatness. Now do some exercises for your brain and muscle. - -# 💻 Day 1: Exercises - -1. Write a single line comment which says, _comments can make code readable_ -2. Write another single comment which says, _Welcome to 30DaysOfJavaScript_ -3. Write a multiline comment which says, _comments can make code readable, easy to reuse_ - _and informative_ - -4. Create a variable.js file and declare variables and assign string, boolean, undefined and null data types -5. Create datatypes.js file and use the JavaScript **_typeof_** operator to check different data types. Check the data type of each variable -6. Declare four variables without assigning values -7. Declare four variables with assigned values -8. Declare variables to store your first name, last name, marital status, country and age in multiple lines -9. Declare variables to store your first name, last name, marital status, country and age in a single line -10. Declare two variables _myAge_ and _yourAge_ and assign them initial values and log to the browser console. - -```sh -I am 25 years old. -You are 30 years old. -``` - -🎉 CONGRATULATIONS ! 🎉 - -[Day 2 >>](./02_Day_Data_types/02_day_data_types.md) diff --git a/RU/02_Day/02_day_data_types.md b/RU/02_Day/02_day_data_types.md deleted file mode 100644 index e898f4f..0000000 --- a/RU/02_Day/02_day_data_types.md +++ /dev/null @@ -1,973 +0,0 @@ -
-

30 Days Of JavaScript

- - - - - Twitter Follow - - -Автор: -Asabeneh Yetayeh
- Январь, 2020 -
- -
- -[<< День 1](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/RU/README.md) | [День 3 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/RU/03_Day/03_booleans_operators_date.md) - -![Thirty Days Of JavaScript](../images/banners/day_1_2.png) - -- [📔 Day 2](#%f0%9f%93%94-day-2) - - [Типы данных](#%d0%a2%d0%b8%d0%bf%d1%8b-%d0%b4%d0%b0%d0%bd%d0%bd%d1%8b%d1%85) - - [Примитивные типы данных](#%d0%9f%d1%80%d0%b8%d0%bc%d0%b8%d1%82%d0%b8%d0%b2%d0%bd%d1%8b%d0%b5-%d1%82%d0%b8%d0%bf%d1%8b-%d0%b4%d0%b0%d0%bd%d0%bd%d1%8b%d1%85) - - [Пример](#%d0%9f%d1%80%d0%b8%d0%bc%d0%b5%d1%80) - - [Непримитивные типы данных](#%d0%9d%d0%b5%d0%bf%d1%80%d0%b8%d0%bc%d0%b8%d1%82%d0%b8%d0%b2%d0%bd%d1%8b%d0%b5-%d1%82%d0%b8%d0%bf%d1%8b-%d0%b4%d0%b0%d0%bd%d0%bd%d1%8b%d1%85) - - [Числа](#%d0%a7%d0%b8%d1%81%d0%bb%d0%b0) - - [Объявление числовых типов данных](#%d0%9e%d0%b1%d1%8a%d1%8f%d0%b2%d0%bb%d0%b5%d0%bd%d0%b8%d0%b5-%d1%87%d0%b8%d1%81%d0%bb%d0%be%d0%b2%d1%8b%d1%85-%d1%82%d0%b8%d0%bf%d0%be%d0%b2-%d0%b4%d0%b0%d0%bd%d0%bd%d1%8b%d1%85) - - [Математический объект](#%d0%9c%d0%b0%d1%82%d0%b5%d0%bc%d0%b0%d1%82%d0%b8%d1%87%d0%b5%d1%81%d0%ba%d0%b8%d0%b9-%d0%be%d0%b1%d1%8a%d0%b5%d0%ba%d1%82) - - [Генератор случайных чисел](#%d0%93%d0%b5%d0%bd%d0%b5%d1%80%d0%b0%d1%82%d0%be%d1%80-%d1%81%d0%bb%d1%83%d1%87%d0%b0%d0%b9%d0%bd%d1%8b%d1%85-%d1%87%d0%b8%d1%81%d0%b5%d0%bb) - - [Строки](#%d0%a1%d1%82%d1%80%d0%be%d0%ba%d0%b8) - - [Конкатенация строк](#%d0%9a%d0%be%d0%bd%d0%ba%d0%b0%d1%82%d0%b5%d0%bd%d0%b0%d1%86%d0%b8%d1%8f-%d1%81%d1%82%d1%80%d0%be%d0%ba) - - [Конкатенация с использованием оператора сложения](#%d0%9a%d0%be%d0%bd%d0%ba%d0%b0%d1%82%d0%b5%d0%bd%d0%b0%d1%86%d0%b8%d1%8f-%d1%81-%d0%b8%d1%81%d0%bf%d0%be%d0%bb%d1%8c%d0%b7%d0%be%d0%b2%d0%b0%d0%bd%d0%b8%d0%b5%d0%bc-%d0%be%d0%bf%d0%b5%d1%80%d0%b0%d1%82%d0%be%d1%80%d0%b0-%d1%81%d0%bb%d0%be%d0%b6%d0%b5%d0%bd%d0%b8%d1%8f) - - [Длинные буквенные строки](#%d0%94%d0%bb%d0%b8%d0%bd%d0%bd%d1%8b%d0%b5-%d0%b1%d1%83%d0%ba%d0%b2%d0%b5%d0%bd%d0%bd%d1%8b%d0%b5-%d1%81%d1%82%d1%80%d0%be%d0%ba%d0%b8) - - [Перенос последовательности в строке](#%d0%9f%d0%b5%d1%80%d0%b5%d0%bd%d0%be%d1%81-%d0%bf%d0%be%d1%81%d0%bb%d0%b5%d0%b4%d0%be%d0%b2%d0%b0%d1%82%d0%b5%d0%bb%d1%8c%d0%bd%d0%be%d1%81%d1%82%d0%b8-%d0%b2-%d1%81%d1%82%d1%80%d0%be%d0%ba%d0%b5) - - [Шаблонные литералы (Шаблонные строки)](#%d0%a8%d0%b0%d0%b1%d0%bb%d0%be%d0%bd%d0%bd%d1%8b%d0%b5-%d0%bb%d0%b8%d1%82%d0%b5%d1%80%d0%b0%d0%bb%d1%8b-%d0%a8%d0%b0%d0%b1%d0%bb%d0%be%d0%bd%d0%bd%d1%8b%d0%b5-%d1%81%d1%82%d1%80%d0%be%d0%ba%d0%b8) - - [Строковые Методы](#%d0%a1%d1%82%d1%80%d0%be%d0%ba%d0%be%d0%b2%d1%8b%d0%b5-%d0%9c%d0%b5%d1%82%d0%be%d0%b4%d1%8b) - - [Проверка типов данных и приведение](#%d0%9f%d1%80%d0%be%d0%b2%d0%b5%d1%80%d0%ba%d0%b0-%d1%82%d0%b8%d0%bf%d0%be%d0%b2-%d0%b4%d0%b0%d0%bd%d0%bd%d1%8b%d1%85-%d0%b8-%d0%bf%d1%80%d0%b8%d0%b2%d0%b5%d0%b4%d0%b5%d0%bd%d0%b8%d0%b5) - - [Проверка типов данных](#%d0%9f%d1%80%d0%be%d0%b2%d0%b5%d1%80%d0%ba%d0%b0-%d1%82%d0%b8%d0%bf%d0%be%d0%b2-%d0%b4%d0%b0%d0%bd%d0%bd%d1%8b%d1%85) - - [Изменение типа данных (Casting)](#%d0%98%d0%b7%d0%bc%d0%b5%d0%bd%d0%b5%d0%bd%d0%b8%d0%b5-%d1%82%d0%b8%d0%bf%d0%b0-%d0%b4%d0%b0%d0%bd%d0%bd%d1%8b%d1%85-casting) - - [Строка в число](#%d0%a1%d1%82%d1%80%d0%be%d0%ba%d0%b0-%d0%b2-%d1%87%d0%b8%d1%81%d0%bb%d0%be) - - [Строка в число с плавающей запятой](#%d0%a1%d1%82%d1%80%d0%be%d0%ba%d0%b0-%d0%b2-%d1%87%d0%b8%d1%81%d0%bb%d0%be-%d1%81-%d0%bf%d0%bb%d0%b0%d0%b2%d0%b0%d1%8e%d1%89%d0%b5%d0%b9-%d0%b7%d0%b0%d0%bf%d1%8f%d1%82%d0%be%d0%b9) - - [Числа с плавающей точкой в целые числа.](#%d0%a7%d0%b8%d1%81%d0%bb%d0%b0-%d1%81-%d0%bf%d0%bb%d0%b0%d0%b2%d0%b0%d1%8e%d1%89%d0%b5%d0%b9-%d1%82%d0%be%d1%87%d0%ba%d0%be%d0%b9-%d0%b2-%d1%86%d0%b5%d0%bb%d1%8b%d0%b5-%d1%87%d0%b8%d1%81%d0%bb%d0%b0) - - [💻 День 2: Упражнения](#%f0%9f%92%bb-%d0%94%d0%b5%d0%bd%d1%8c-2-%d0%a3%d0%bf%d1%80%d0%b0%d0%b6%d0%bd%d0%b5%d0%bd%d0%b8%d1%8f) - - [Упражнение: Уровень 1](#%d0%a3%d0%bf%d1%80%d0%b0%d0%b6%d0%bd%d0%b5%d0%bd%d0%b8%d0%b5-%d0%a3%d1%80%d0%be%d0%b2%d0%b5%d0%bd%d1%8c-1) - - [Упражнение: уровень 2](#%d0%a3%d0%bf%d1%80%d0%b0%d0%b6%d0%bd%d0%b5%d0%bd%d0%b8%d0%b5-%d1%83%d1%80%d0%be%d0%b2%d0%b5%d0%bd%d1%8c-2) - - [Упражнения: уровень 3](#%d0%a3%d0%bf%d1%80%d0%b0%d0%b6%d0%bd%d0%b5%d0%bd%d0%b8%d1%8f-%d1%83%d1%80%d0%be%d0%b2%d0%b5%d0%bd%d1%8c-3) - -# 📔 Day 2 - -## Типы данных - -В предыдущем разделе мы немного упомянули о типах данных. Данные или значения имеют типы данных. Типы данных описывают характеристики данных. Типы данных можно разделить на два вида - -1. Примитивные типы данных -2. Непримитивные типы данных (ссылки на объекты) - -### Примитивные типы данных - -Примитивные типы данных в JavaScript включают в себя: - -1. Числа (Numbers) - Целые числа, числа с плавающей точкой -2. Строки (Strings) - Любые данные в одинарных или двойных кавычках -3. Булевые (boolean) - true или false значения -4. Null - пустое значение или нет значения -5. Undefined - объявленная переменная без значения - -Непримитивные типы данных в JavaScript включают в себя: - -1. Объекты -2. Функции -3. Массивы - -Теперь давайте посмотрим, что именно означают примитивные и не примитивные типы данных. - -_Примитивные_ типы данных являются неизменяемыми типами данных. Как только примитивный тип данных создан, мы не можем его изменить. - -#### Пример - -```js -let word = "JavaScript"; -``` - -Если мы попытаемся изменить строку, хранящуюся в переменной _word_, JavaScript вызовет ошибку. Любой тип данных с одинарными, двойными или обратными кавычками является строковым типом данных. - -```js -word[0] = "Y"; -``` - -Это выражение не изменяет строку, хранящуюся в переменной _word_. Таким образом, мы можем сказать, что строки не являются изменяемыми или неизменяемыми. -Примитивные типы данных сравниваются по их значениям. Давайте сравним различные значения данных. Смотрите пример ниже: - -```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 -``` - -### Непримитивные типы данных - -_Непримитивные_ типы данных являются изменяемыми. Мы можем изменить значение непримитивных типов данных после их создания. -Давайте посмотрим, создав массив. Массив - это список значений данных в квадратных скобках. Массивы могут содержать одинаковые или разные типы данных. На значения массива ссылается их индекс. В массиве JavaScript индекс начинается с нуля. Т.е. первый элемент массива находится с нулевым индексом, второй элемент с индексом один и третий элемент с индексом два и т.д. - -```js -let nums = [1, 2, 3]; -nums[0] = 10; - -console.log(nums); // [10, 2, 3] -``` - -Как вы можете видеть, массив, в котором непримитивный тип данных является изменяемым. Непримитивные типы данных нельзя сравнивать по значению. Даже если два непримитивных типа данных имеют одинаковые свойства и значения, они не являются строго равными. - -```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); // false -``` - -Основное правило, мы не сравниваем непримитивные типы данных. Не сравнивайте массив, функцию или объект. -Непримитивные значения называются ссылочными типами, поскольку они сравниваются по значению, а не по значению. Два объекта строго равны, если они ссылаются на один и тот же базовый объект. - -```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 -``` - -Если вам трудно понять разницу между примитивными типами данных и не примитивными типами данных, вы не единственный. -Успокойтесь и просто перейдите к следующему разделу и попробуйте вернуться через некоторое время. Теперь давайте начнем типы данных по типу номера. - -## Числа - -Числа представляют собой целые и десятичные значения, которые могут выполнять все арифметические операции. -Давайте посмотрим некоторые примеры чисел. - -### Объявление числовых типов данных - -```js -let age = 35; -const gravity = 9.81; //мы используем const для неизменных значений, гравитационная постоянная в m/s2 -let mass = 72; // масса в килограммах -const PI = 3.14; // ПИ геометрическая постоянная - -//Больше примеров -const boilingPoint = 100; // температура в oC, температура кипения воды которой постоянна -const bodyTemp = 37; // oC средняя температура тела человека, которая является постоянной - -console.log(age, gravity, mass, PI, boilingPoint, bodyTemp); -``` - -### Математический объект - -В JavaScript Math Object предоставляет множество методов для работы с числами. - -```js -const PI = Math.PI; - -console.log(PI); // 3.141592653589793 - -// Округление до ближайшего числа -// если выше .5 вверх, если меньше 0.5 вниз - -console.log(Math.round(PI)); // 3, чтобы округлить значения до ближайшего числа - -console.log(Math.round(9.81)); // 10 - -console.log(Math.floor(PI)); // 3 округление вниз - -console.log(Math.ceil(PI)); // 4 округление вверх - -console.log(Math.min(-5, 3, 20, 4, 5, 10)); // -5, возвращает минимальное значение - -console.log(Math.max(-5, 3, 20, 4, 5, 10)); // 20, возвращает максимальное значение - -const randNum = Math.random(); // создает случайное число от 0 до 0,999999 -console.log(randNum); - -// Давайте создадим случайное число от 0 до 10 - -const num = Math.floor(Math.random() * 11); // создает случайное число от 0 до 10 -console.log(num); - -// Абсолютное значение -console.log(Math.abs(-10)); //10 - -// Квадратный корень -console.log(Math.sqrt(100)); // 10 - -console.log(Math.sqrt(2)); //1.4142135623730951 - -// Мощность -console.log(Math.pow(3, 2)); // 9 - -console.log(Math.E); // 2.718 - -// Логарифм -// Возвращает натуральный логарифм основания E из x, Math.log(x) -console.log(Math.log(2)); // 0.6931471805599453 -console.log(Math.log(10)); // 2.302585092994046 - -// Тригонометрия -Math.sin(0); -Math.sin(60); - -Math.cos(0); -Math.cos(60); -``` - -#### Генератор случайных чисел - -JavaScript Math Object имеет генератор номеров метода `random()`, который генерирует числа от 0 до 0.999999999... - -```js -let randomNum = Math.random(); // генерирует от 0 до 0,999 -``` - -Теперь давайте посмотрим, как мы можем использовать метод `random()` для генерации случайного числа от 0 до 10 включительно. - -```js -let randomNum = Math.random(); // генерирует от 0 до 0,999 -let numBtnZeroAndTen = randomNum * 11; - -console.log(numBtnZeroAndTen); // это дает: мин 0 и макс 10.99 - -let randomNumRoundToFloor = Math.floor(numBtnZeroAndTen); -console.log(randomNumRoundToFloor); // это дает от 0 до 10 -``` - -## Строки - -Строки - это тексты, которые заключены в **_одинарную_** или **_двойную_** кавычку. Чтобы объявить строку, нам нужно имя переменной, оператор присваивания, значение в одинарных кавычках, двойные кавычки или обратные кавычки. - -Давайте посмотрим несколько примеров строки: - -```js -let space = " "; // Пусто - пробел -let firstName = "Asabeneh"; -let lastName = "Yetayeh"; -let country = "Finland"; -let city = "Helsinki"; -let language = "JavaScript"; -let job = "teacher"; -``` - -### Конкатенация строк - -Соединение двух или более строк вместе называется конкатенацией. - -```js -// Объявление разных переменных разных типов данных -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; // конкатенация, объединение двух строк. -console.log(fullName); -``` - -```sh -Asabeneh Yetayeh -``` - -Мы можем объединять строки разными способами. - -#### Конкатенация с использованием оператора сложения - -Конкатенация с использованием оператора сложения - старый способ. Этот способ объединения утомителен и подвержен ошибкам. Полезно знать, как объединить таким способом, но я настоятельно рекомендую использовать второй способ. - -```js -// Объявление разных переменных разных типов данных -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 -``` - -#### Длинные буквенные строки - -Строка может быть отдельным символом, абзацем или страницей. Если длина строки слишком велика, она не помещается в одну строку. Мы можем использовать символ обратной косой черты (\\) в конце каждой строки, чтобы указать, что строка будет продолжена на следующей строке. - -**Пример:** - -```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); -``` - -#### Перенос последовательности в строке - -В JavaScript и других языках программирования, после некоторых символов есть перенос - последовательности. Давайте посмотрим на наиболее распространенные escape-символы: - -- `\n` - Новая строка -- `\t` - Таб означает (8 пробелов) -- `\\` - Обратная косая черта -- `\'` - Одинарные кавычки (') -- `\"` - Двойные кавычки (") - -```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"); -``` - -#### Шаблонные литералы (Шаблонные строки) - -Чтобы создать строку шаблона, мы используем два обратных ключа. Мы можем вставить данные как выражение внутри строки шаблона. Чтобы ввести данные, мы заключаем выражение в фигурную скобку (`{}`), за которой следует знак `$`. Смотрите синтаксис ниже. - -```js -// Синтаксис -`String literal text ${expression}`; -``` - -**Пример: 1** - -```js -console.log(`The sum of 2 and 3 is 5`); // статическая запись данных -let a = 2; -let b = 3; -console.log(`The sum of ${a} and ${b} is ${a + b}`); // ввод данных динамически -``` - -**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 - Метод строковой интерполяции -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. -``` - -Используя шаблон строки или метод интерполяции строки, мы можем добавить выражение, которое может быть значением или некоторыми операциями (сравнение, арифметические операции, троичные операции). - -```js -let a = 2; -let b = 3; -console.log(`${a} is greater than ${b}: ${a > b}`); -``` - -```sh -2 is greater than 3: false -``` - -### Строковые Методы - -Все в JavaScript это объект. Строка - это примитивный тип данных, который означает, что мы не можем изменить его после создания. У строкового объекта есть много строковых методов. Существуют разные строковые методы, которые могут помочь нам работать со строками. - -1. _length_: Метод строки _length_ возвращает количество символов в строке, включая пустое пространство. - **Пример:** - - ```js - let js = "JavaScript"; - console.log(js.length); // 10 - let firstName = "Asabeneh"; - console.log(firstName.length); // 8 - ``` - -2. _Доступ к символам в строке_: мы можем получить доступ к каждому символу в строке, используя его индекс. В программировании отсчет начинается с 0. Первый индекс строки равен нулю, а последний индекс равен одному минус длина строки. - - ![Accessing sting by index](../images/string_indexes.png) - - Давайте получим доступ к различным символам в строке «JavaScript». - - ```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()`: этот метод изменяет строку на заглавные буквы. - - ```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()`: этот метод изменяет строку на заглавные буквы - - ```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()`:Требуется два аргумента: начальный индекс и количество символов для нарезки. - - ```js - let string = "JavaScript"; - console.log(string.substr(4, 6)); // Script - - let country = "Finland"; - console.log(country.substr(3, 4)); // land - ``` - -6. `substring()`: Он принимает два аргумента: начальный индекс и индекс остановки, но он не включает индекс остановки. - - ```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()`: Метод `split()` разделяет строку в указанном месте. - - ```js - let string = "30 Days Of JavaScript"; - - 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()`: Удаляет завершающий пробел в начале или конце строки. - - ```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()`: принимает аргумент подстроки и проверяет, существует ли аргумент подстроки в строке. `includes()` возвращает логическое значение. Он проверяет, существует ли подстрока в строке, и возвращает true, если она существует, и false, если она не существует. - - ```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()`: принимает к параметру старую подстроку и новую подстроку. - - ```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()`: принимает индекс и возвращает значение по этому индексу - - ```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()`: Принимает индекс и возвращает код символа (номер ASCII) значения по этому индексу - - ```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()`: Принимает подстроку, и если подстрока существует в строке, она возвращает первую позицию подстроки, если не существует, она возвращает -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()`: Принимает подстроку, и если подстрока существует в строке, она возвращает последнюю позицию подстроки, если она не существует, она возвращает -1 - - ```js - //syntax - string.lastIndexOf(substring); - ``` - - ```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()`: он принимает много подстрок и создает конкатенацию. - - ```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`: он принимает подстроку в качестве аргумента и проверяет, начинается ли строка с указанной подстроки. Возвращает логическое значение (true или 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`: он принимает подстроку в качестве аргумента и проверяет, начинается ли строка с указанной подстроки. Возвращает логическое значение (true или 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`: он принимает подстроку в качестве аргумента и возвращает индекс первого совпадения. - - ```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`: он принимает подстроку или шаблон регулярного выражения в качестве аргумента и возвращает массив, если есть совпадение, если нет, то возвращает ноль. Давайте посмотрим, как выглядит шаблон регулярного выражения. Он начинается с / знака и заканчивается / знаком. - - ```js - let string = "love"; - let patternOne = /love/; //без какого-либо флага - let patternTwo = /love/gi; // g-означает поиск по всему тексту, i - без учета регистра - ``` - - 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"] - ``` - - Давайте извлечем числа из текста, используя регулярное выражение. Это не раздел регулярных выражений, не паникуйте, мы рассмотрим регулярные выражения в другом разделе. - - ```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 с перенос-символом означает, что d не является нормальным d, вместо этого действует цифра - // + означает одно или несколько цифр, - // если после этого есть g, значит глобальный, ищите везде. - - 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()`: он принимает числовой аргумент и возвращает повторную версию строки. - - ```js - string.repeat(n); - ``` - - ```js - let string = "love"; - console.log(string.repeat(10)); // lovelovelovelovelovelovelovelovelovelove - ``` - -## Проверка типов данных и приведение - -### Проверка типов данных - -- Проверка типов данных: чтобы проверить тип данных определенного типа данных, мы используем `typeof` и также меняем один тип данных на другой. - -**Пример:** - -```js -// Различные типы данных JavaScript -// Давайте объявим разные типы данных - -let firstName = "Asabeneh"; // string -let lastName = "Yetayeh"; // string -let country = "Finland"; // string -let city = "Helsinki"; // string -let age = 250; // number, это не мой настоящий возраст, не переживай -let job; // undefined, потому что значение не было присвоено - -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 -``` - -### Изменение типа данных (Casting) - -- Приведение: преобразование одного типа данных в другой тип данных. Мы используем _parseInt()_, _parseFloat()_, _Number()_, _+sign_, _str()_. Когда мы выполняем арифметические операции, строковые числа должны быть сначала преобразованы в целое число или число с плавающей запятой, если нет, это возвращает ошибку. - -#### Строка в число - -Мы можем преобразовать номер строки в число. Любое число внутри кавычки является строковым числом. Пример номера строки: «10», «5» и т. Д. -Мы можем преобразовать строку в число, используя следующие методы: - -- 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 -``` - -#### Строка в число с плавающей запятой - -Мы можем преобразовать число с плавающей запятой в число с плавающей запятой. Любое число с плавающей запятой внутри кавычки является строковым числом с плавающей запятой. Пример числа с плавающей запятой: «9,81», «3,14», «1,44» и т. Д. -Мы можем преобразовать строку с плавающей точкой в число, используя следующие методы: - -- 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 в int: - -- parseInt() - -```js -let num = 9.81; -let numInt = parseInt(num); - -console.log(numInt); // 9 -``` - -🌕 Ты обалденный. Вы только что завершили 2-й день испытаний, и вы в двух шагах от своего пути к успеху. Теперь сделайте несколько упражнений для вашего мозга и ваших мышц. - -## 💻 День 2: Упражнения - -### Упражнение: Уровень 1 - -1. Объявите вызов имени переменной и присвойте ему начальное значение **«30 дней JavaScript»**. -2. Напечатайте строку в консоли браузера, используя `console.log()` -3. Напечатайте **length** строки в консоли браузера, используя `console.log()` -4. Измените всю строку на заглавные буквы, используя метод `toUpperCase()` -5. Измените всю строку на строчные буквы, используя метод `toLowerCase()` -6. Вырежьте (нарежьте) первое слово строки, используя метод `substr()` или `substring()` -7. Вырежьте фразу _Days Of JavaScript_ из _30 Days Of JavaScript_. -8. Проверьте, содержит ли строка слово **Script**, используя метод `includes()` -9. Разбейте **строку** на **массив**, используя метод `split()` -10. Разбить строку 30 Days Of JavaScript в пространстве с помощью метода `split()` -11. «Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon» **разбивают** строку на запятую и заменяют ее на массив. -12. Измените 30 Days Of JavaScript на 30 Days Of Python, используя метод `replace()`. -13. Что такое символ в индексе 15 в строке «30 Days Of JavaScript», используйте метод `charAt()`. -14. Что такое код символа J в строке «30 Days Of JavaScript» с использованием `charCodeAt()` -15. Используйте `indexOf`, чтобы определить позицию первого вхождения за 30 Days Of JavaScript -16. Используйте `lastIndexOf`, чтобы определить позицию последнего вхождения в 30 Days Of JavaScript. -17. Используйте `indexOf`, чтобы найти позицию первого вхождения слова **потому что** в следующем предложении: **«Вы не можете закончить предложение, потому что, потому что, потому что это соединение»** -18. Используйте `lastIndexOf`, чтобы найти позицию последнего вхождения слова **потому что** в следующем предложении: **«Вы не можете закончить предложение, потому что, потому что потому что это соединение»** -19. Используйте `search`, чтобы найти позицию первого вхождения слова **потому что** в следующем предложении: **«Вы не можете закончить предложение, потому что, потому что потому что это соединение»** -20. Используйте `trim()`, чтобы удалить, если в начале и конце строки есть конечные пробелы. Например, «30 Days Of JavaScript». -21. Используйте метод `launchWith()` со строкой _30 Days Of JavaScript_, чтобы сделать результат верным -22. Используйте метод `setsWith()` со строкой _30 Days Of JavaScript_, чтобы сделать результат верным -23. Используйте метод `match()`, чтобы найти все за 30 Days Of JavaScript -24. Используйте `concat()` и объедините «30 Days» и «JavaScript» в одну строку «30 Days Of JavaScript» -25. Используйте метод `repeat()`, чтобы напечатать 30 Days Of JavaScript 2 раза - -### Упражнение: уровень 2 - -1. Используя `console.log()`, выведите следующее утверждение. - - ```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 one another. - ``` - -2. Используя `console.log()` распечатайте следующую цитату Матери Терезы. - - ```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." - ``` - -3. Проверьте, точно ли `typeof` '10' равен 10. Если нет, сделайте его точно равным. -4. Убедитесь, что `parseFloat('9.8')` равен 10, если не равен точно 10. -5. Проверьте, найдено ли 'on' как в Python, так и в жаргоне -6. Я надеюсь, что этот курс не полон жаргона. Проверьте, находится ли _jargon_ в предложении. -7. Сгенерируйте случайное число от 0 до 100 включительно. -8. Генерация случайного числа от 50 до 100 включительно. -9. Сгенерируйте случайное число от 0 до 255 включительно. -10. Получите доступ к символам строки «JavaScript», используя случайное число. -11. Используйте `console.log()` и управляющие символы для печати следующего шаблона. - - ```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 - ``` - -12. Используйте `substr`, чтобы вырезать фразу **потому что потому что** в следующем предложении: **'Вы не можете закончить предложение, потому что потому что потому что это соединение'** - -### Упражнения: уровень 3 - -1. «Любовь - лучшая вещь в этом мире. Некоторые нашли свою любовь, а некоторые все еще ищут свою любовь. Подсчитайте количество слов любви в этом предложении. -2. Используйте `match()`, чтобы сосчитать число все потому, что в следующем предложении: **«Вы не можете закончить предложение, потому что, потому что, потому что это соединение»** -3. Очистите следующий текст и найдите наиболее часто встречающееся слова (подсказка, используйте замену и регулярный экспресс). - - ```js - const sentence = - "%I $am@% a %tea@cher%, &and& I lo%#ve %te@a@ching%;. The@re $is no@th@ing; &as& mo@re rewarding as educa@ting &and& @emp%o@weri@ng peo@ple. ;I found tea@ching m%o@re interesting tha@n any ot#her %jo@bs. %Do@es thi%s mo@tiv#ate yo@u to be a tea@cher!? %Th#is 30#Days&OfJavaScript &is al@so $the $resu@lt of &love& of tea&ching"; - ``` - -4. Рассчитайте общий годовой доход человека, извлекая цифры из следующего текста. «Он зарабатывает 5000 евро с зарплаты в месяц, годовой бонус в 10000 евро, онлайн-курсы в 15000 евро в месяц». - -🎉 ПОЗДРАВЛЯЕМ! 🎉 - -[<< День 1](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/RU/readMe.md) | [День 3 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/RU/03_Day/03_booleans_operators_date.md) diff --git a/RU/02_Day/day_1_2.png b/RU/02_Day/day_1_2.png deleted file mode 100644 index 0f6eefb..0000000 Binary files a/RU/02_Day/day_1_2.png and /dev/null differ diff --git a/RU/03_Day/03_booleans_operators_date.md b/RU/03_Day/03_booleans_operators_date.md deleted file mode 100644 index 06b649c..0000000 --- a/RU/03_Day/03_booleans_operators_date.md +++ /dev/null @@ -1,649 +0,0 @@ -
-

30 Days Of JavaScript

- - - - - Twitter Follow - - -Автор: -Asabeneh Yetayeh
- Январь, 2020 -
- -
- -[<< День 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](../images/banners/day_1_3.png) - -- [📔 День 3](#%f0%9f%93%94-%d0%94%d0%b5%d0%bd%d1%8c-3) - - [Булевый тип (boolean)](#%d0%91%d1%83%d0%bb%d0%b5%d0%b2%d1%8b%d0%b9-%d1%82%d0%b8%d0%bf-boolean) - - [Пример: логические значения](#%d0%9f%d1%80%d0%b8%d0%bc%d0%b5%d1%80-%d0%bb%d0%be%d0%b3%d0%b8%d1%87%d0%b5%d1%81%d0%ba%d0%b8%d0%b5-%d0%b7%d0%bd%d0%b0%d1%87%d0%b5%d0%bd%d0%b8%d1%8f) - - [Истинные значения](#%d0%98%d1%81%d1%82%d0%b8%d0%bd%d0%bd%d1%8b%d0%b5-%d0%b7%d0%bd%d0%b0%d1%87%d0%b5%d0%bd%d0%b8%d1%8f) - - [Ложные значения](#%d0%9b%d0%be%d0%b6%d0%bd%d1%8b%d0%b5-%d0%b7%d0%bd%d0%b0%d1%87%d0%b5%d0%bd%d0%b8%d1%8f) - - [Undefined](#undefined) - - [Null](#null) - - [Операторы](#%d0%9e%d0%bf%d0%b5%d1%80%d0%b0%d1%82%d0%be%d1%80%d1%8b) - - [Операторы присваивания](#%d0%9e%d0%bf%d0%b5%d1%80%d0%b0%d1%82%d0%be%d1%80%d1%8b-%d0%bf%d1%80%d0%b8%d1%81%d0%b2%d0%b0%d0%b8%d0%b2%d0%b0%d0%bd%d0%b8%d1%8f) - - [Арифметические Операторы](#%d0%90%d1%80%d0%b8%d1%84%d0%bc%d0%b5%d1%82%d0%b8%d1%87%d0%b5%d1%81%d0%ba%d0%b8%d0%b5-%d0%9e%d0%bf%d0%b5%d1%80%d0%b0%d1%82%d0%be%d1%80%d1%8b) - - [Операторы сравнения](#%d0%9e%d0%bf%d0%b5%d1%80%d0%b0%d1%82%d0%be%d1%80%d1%8b-%d1%81%d1%80%d0%b0%d0%b2%d0%bd%d0%b5%d0%bd%d0%b8%d1%8f) - - [Пример: операторы сравнения](#%d0%9f%d1%80%d0%b8%d0%bc%d0%b5%d1%80-%d0%be%d0%bf%d0%b5%d1%80%d0%b0%d1%82%d0%be%d1%80%d1%8b-%d1%81%d1%80%d0%b0%d0%b2%d0%bd%d0%b5%d0%bd%d0%b8%d1%8f) - - [Логические Операторы](#%d0%9b%d0%be%d0%b3%d0%b8%d1%87%d0%b5%d1%81%d0%ba%d0%b8%d0%b5-%d0%9e%d0%bf%d0%b5%d1%80%d0%b0%d1%82%d0%be%d1%80%d1%8b) - - [Оператор инкремента](#%d0%9e%d0%bf%d0%b5%d1%80%d0%b0%d1%82%d0%be%d1%80-%d0%b8%d0%bd%d0%ba%d1%80%d0%b5%d0%bc%d0%b5%d0%bd%d1%82%d0%b0) - - [Оператор декремента](#%d0%9e%d0%bf%d0%b5%d1%80%d0%b0%d1%82%d0%be%d1%80-%d0%b4%d0%b5%d0%ba%d1%80%d0%b5%d0%bc%d0%b5%d0%bd%d1%82%d0%b0) - - [Тернарный операторы](#%d0%a2%d0%b5%d1%80%d0%bd%d0%b0%d1%80%d0%bd%d1%8b%d0%b9-%d0%be%d0%bf%d0%b5%d1%80%d0%b0%d1%82%d0%be%d1%80%d1%8b) - - [Приоритет оператора](#%d0%9f%d1%80%d0%b8%d0%be%d1%80%d0%b8%d1%82%d0%b5%d1%82-%d0%be%d0%bf%d0%b5%d1%80%d0%b0%d1%82%d0%be%d1%80%d0%b0) - - [Методы окна](#%d0%9c%d0%b5%d1%82%d0%be%d0%b4%d1%8b-%d0%be%d0%ba%d0%bd%d0%b0) - - [Метод alert()](#%d0%9c%d0%b5%d1%82%d0%be%d0%b4-alert) - - [Метод prompt()](#%d0%9c%d0%b5%d1%82%d0%be%d0%b4-prompt) - - [Метод confirm()](#%d0%9c%d0%b5%d1%82%d0%be%d0%b4-confirm) - - [Объект Date](#%d0%9e%d0%b1%d1%8a%d0%b5%d0%ba%d1%82-date) - - [Создание объекта времени](#%d0%a1%d0%be%d0%b7%d0%b4%d0%b0%d0%bd%d0%b8%d0%b5-%d0%be%d0%b1%d1%8a%d0%b5%d0%ba%d1%82%d0%b0-%d0%b2%d1%80%d0%b5%d0%bc%d0%b5%d0%bd%d0%b8) - - [Получение года](#%d0%9f%d0%be%d0%bb%d1%83%d1%87%d0%b5%d0%bd%d0%b8%d0%b5-%d0%b3%d0%be%d0%b4%d0%b0) - - [Получение месяца](#%d0%9f%d0%be%d0%bb%d1%83%d1%87%d0%b5%d0%bd%d0%b8%d0%b5-%d0%bc%d0%b5%d1%81%d1%8f%d1%86%d0%b0) - - [Получение даты](#%d0%9f%d0%be%d0%bb%d1%83%d1%87%d0%b5%d0%bd%d0%b8%d0%b5-%d0%b4%d0%b0%d1%82%d1%8b) - - [Получение дня](#%d0%9f%d0%be%d0%bb%d1%83%d1%87%d0%b5%d0%bd%d0%b8%d0%b5-%d0%b4%d0%bd%d1%8f) - - [Получение часов](#%d0%9f%d0%be%d0%bb%d1%83%d1%87%d0%b5%d0%bd%d0%b8%d0%b5-%d1%87%d0%b0%d1%81%d0%be%d0%b2) - - [Получение минут](#%d0%9f%d0%be%d0%bb%d1%83%d1%87%d0%b5%d0%bd%d0%b8%d0%b5-%d0%bc%d0%b8%d0%bd%d1%83%d1%82) - - [Получение секунд](#%d0%9f%d0%be%d0%bb%d1%83%d1%87%d0%b5%d0%bd%d0%b8%d0%b5-%d1%81%d0%b5%d0%ba%d1%83%d0%bd%d0%b4) - - [Получение времени](#%d0%9f%d0%be%d0%bb%d1%83%d1%87%d0%b5%d0%bd%d0%b8%d0%b5-%d0%b2%d1%80%d0%b5%d0%bc%d0%b5%d0%bd%d0%b8) - - [💻 День 3: Упражнения](#%f0%9f%92%bb-%d0%94%d0%b5%d0%bd%d1%8c-3-%d0%a3%d0%bf%d1%80%d0%b0%d0%b6%d0%bd%d0%b5%d0%bd%d0%b8%d1%8f) - - [Упражнения: Уровень 1](#%d0%a3%d0%bf%d1%80%d0%b0%d0%b6%d0%bd%d0%b5%d0%bd%d0%b8%d1%8f-%d0%a3%d1%80%d0%be%d0%b2%d0%b5%d0%bd%d1%8c-1) - - [Упражнения: уровень 2](#%d0%a3%d0%bf%d1%80%d0%b0%d0%b6%d0%bd%d0%b5%d0%bd%d0%b8%d1%8f-%d1%83%d1%80%d0%be%d0%b2%d0%b5%d0%bd%d1%8c-2) - - [Упражнения: уровень 3](#%d0%a3%d0%bf%d1%80%d0%b0%d0%b6%d0%bd%d0%b5%d0%bd%d0%b8%d1%8f-%d1%83%d1%80%d0%be%d0%b2%d0%b5%d0%bd%d1%8c-3) - -# 📔 День 3 - -## Булевый тип (boolean) - -Логический тип данных представляет одно из двух значений: _true_ или _false_. Логическое значение может быть истинным или ложным. Использование этих типов данных будет понятно при запуске оператора сравнения. Любые сравнения возвращают логическое значение, которое является истинным или ложным. - -### Пример: логические значения - -```js -let isLightOn = true; -let isRaining = false; -let isHungry = false; -let isMarried = true; -let truValue = 4 > 3; // true -let falseValue = 4 < 3; // false -``` - -Мы согласились с тем, что логические значения являются истинными или ложными. - -### Истинные значения - -- Все числа (положительные и отрицательные) являются правдивыми, кроме нуля -- Все строки правдивы -- boolean истинное - -### Ложные значения - -- 0 -- 0n -- null -- undefined -- NaN -- the boolean false -- '', "", ``, пустая строка - -Нужно хорощо помнить эти истинные и ложные значения. В следующем разделе мы будем использовать их с условиями для принятия решения. - -## Undefined - -Если мы объявим переменную и не назначим значение, оно будет неопределенным. В дополнение к этому, если функция не возвращает значение, оно будет неопределенным. - -```js -let firstName; -console.log(firstName); //не определено, потому что оно еще не присвоено значению -``` - -## Null - -```js -let empty = null; -console.log(empty); // -> null , не имеет значения -``` - -## Операторы - -### Операторы присваивания - -Знак равенства в JavaScript - это оператор присваивания. Используется для присвоения переменной. - -```js -let firstName = "Asabeneh"; -let country = "Finland"; -``` - -Операторы присваивания - -![Assignment operators](../images/assignment_operators.png) - -### Арифметические Операторы - -Арифметические операторы являются математическими операторами. - -- Сложение (+): `a + b` -- Вычитание (-): `a - b` -- Умножение (_): `a _ b` -- Деление (/): `a / b` -- Остаток от деления % (%): `a % b` -- Возведение в степень (**): `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 -``` - -```js -let PI = 3.14; -let radius = 100; // длина в метрах - -const gravity = 9.81; // в m/s2 -let mass = 72; // в килограммах -const boilingPoint = 100; // температура в °С, температура кипения воды -const bodyTemp = 37; // температура тела в °С - -//Рассчитаем площадь круга -const areaOfCircle = PI * radius * radius; -console.log(areaOfCircle); // 314 m - -// Давайте посчитаем вес объекта -const weight = mass * gravity; -console.log(weight); // 706.32 N (Newton) - -//Конкатенация строк с числами с использованием строковой интерполяции -/* -Температура кипения воды составляет 100 °С. -Температура тела человека составляет 37 °С. -Гравитация земли составляет 9,81 м/с2. - */ -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](../images/comparison_operators.png) - -#### Пример: операторы сравнения - -```js -console.log(3 > 2); // true, потому что 3 больше 2 -console.log(3 >= 2); // true, потому что 3 больше 2 -console.log(3 < 2); // false, потому что 3 больше 2 -console.log(2 < 3); // true, потому что 2 меньше 3 -console.log(2 <= 3); // true, потому что 2 меньше 3 -console.log(3 == 2); // false, потому что 3 не равно 2 -console.log(3 != 2); // true, потому что 3 не равно 2 -console.log(3 == "3"); // true, сравнить только значение -console.log(3 === "3"); // false, сравнить значение и тип данных -console.log(3 !== "3"); // true, сравнить значение и тип данных -console.log(3 !== "3"); // true, сравнить значение и тип данных -console.log(3 != 3); // false, сравнить только значение -console.log(3 !== 3); // false, сравнить значение и тип данных -console.log(0 == false); // true, эквивалент -console.log(0 == ""); // true, эквивалент -console.log(0 == " "); // true, эквивалент -console.log(0 === ""); // false, не совсем то же самое -console.log(0 === false); // false, не совсем то же самое -console.log(1 == true); // true, эквивалент -console.log(1 === true); // false, не совсем то же самое -console.log(undefined == null); // true -console.log(undefined === null); // false -console.log(NaN == NaN); // false, не равный -console.log(NaN === NaN); // false -console.log(typeof NaN); // число - -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 -``` - -Попытайтесь понять приведенные выше сравнения с некоторой логикой. Запоминать без какой-либо логики может быть сложно. -JavaScript - это своего рода проводной язык программирования. Код JavaScript запускается и дает вам результат, но если вы не разбираетесь в нем, это может быть нежелательным результатом. - -По практическому правилу, если значение не верно с `==`, оно не будет равно `===`. Использование `===` более безопасно, чем использование `==`. Следующая [ссылка](https://dorey.github.io/JavaScript-Equality-Table/) имеет исчерпывающий список сравнения типов данных. - -### Логические Операторы - -Следующие символы являются общими логическими операторами: `&&` (амперсанд), `||` (труба) и `!` (отрицание). - -- `&&` получает значение `true`, только если два операнда имеют значение `true`. -- `||` становится истинным, любой из операндов верен. -- `!` отрицает истину на ложь, ложь на истину. - -```js -//&& Пример оператора амперсанда - -const check = 4 > 3 && 10 > 5; // true && true -> true -const check = 4 > 3 && 10 < 5; // true && false -> false -const check = 4 < 3 && 10 < 5; // false && false -> false - -//|| pipe or operator, example - -const check = 4 > 3 || 10 > 5; // true || true -> true -const check = 4 > 3 || 10 < 5; // true || false -> true -const check = 4 < 3 || 10 < 5; // false || false -> false - -//! Примеры отрицания - -let check = 4 > 3; // true -let check = !(4 > 3); // false -let isLightOn = true; -let isLightOff = !isLightOn; // false -let isMarried = !false; // true -``` - -### Оператор инкремента - -В JavaScript мы используем оператор приращения для увеличения значения, хранящегося в переменной. Приращение может быть до или после приращения. Давайте посмотрим на каждого из них: - -1. Преинкремент - - ```js - let count = 0; - console.log(++count); // 1 - console.log(count); // 1 - ``` - -2. Пост-инкремент - - ```js - let count = 0; - console.log(count++); // 0 - console.log(count); // 1 - ``` - -Мы используем большую часть времени после приращения. По крайней мере, вы должны помнить, как использовать постинкрементный оператор. - -### Оператор декремента - -В JavaScript мы используем оператор декремента для уменьшения значения, хранящегося в переменной. Декремент может быть до или после декремента. Давайте посмотрим на каждого из них: - -1. Предекремент - - ```js - let count = 0; - console.log(--count); // -1 - console.log(count); // -1 - ``` - -2. Постдекремента - - ```js - let count = 0; - console.log(count--); // 0 - console.log(count); // -1 - ``` - -### Тернарный операторы - -Тернарный оператор позволяет записать условие. -Другой способ написания условных выражений - использование Тернарных операторов. Посмотрите на следующие примеры: - -```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 negative number`); -number = -5; - -number > 0 - ? console.log(`${number} is a positive number`) - : console.log(`${number} is a negative number`); -``` - -```sh -5 is a positive number --5 is a negative number -``` - -### Приоритет оператора - -Я хотел бы рекомендовать вам прочитать о приоритете оператора из этой [ссылки](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence) - -## Методы окна - -### Метод alert() - -Как вы видели в самом начале, метод `alert()` отображает окно предупреждения с указанным сообщением и кнопкой OK. Это встроенный метод, и он принимает аргумент. - -```js -alert(message); -``` - -```js -alert("Welcome to 30DaysOfJavaScript"); -``` - -Не используйте слишком много предупреждений, потому что это раздражает, используйте его только для тестирования. - -### Метод prompt() - -Методы подсказки окна отображают окно подсказки с вводом в вашем браузере, чтобы принять входные значения, и входные данные могут быть сохранены в переменной. Метод `prompt()` принимает два аргумента. Второй аргумент является необязательным. - -```js -prompt("required text", "optional text"); -``` - -```js -let number = prompt("Enter number", "number goes here"); -console.log(number); -``` - -### Метод confirm() - -Метод `confirm()` отображает диалоговое окно с указанным сообщением, а также кнопки "ОК" и "Отмена". -Окно подтверждения часто используется, чтобы запросить у пользователя разрешение на что-либо. Окно `confirm()` принимает строку в качестве аргумента. -Нажатие "ОК" дает значение `true`, нажатие кнопки "Отмена" дает значение `false`. - -```js -const agree = confirm("Are you sure you like to delete? "); -console.log(agree); // результат будет true или false в зависимости от того, что вы нажимаете в диалоговом окне -``` - -These are not all the window methods we will have a separate section to go deep into window methods. - -## Объект Date - -Время это важная вещь. Нам нравится знать время определенного действия или события. В JavaScript текущее время и дата создаются с использованием JavaScript Date Object. Объект, который мы создаем с использованием объекта Date, предоставляет множество методов для работы с датой и временем. Методы, которые мы используем для получения информации о дате и времени из значений объекта даты, начинаются со слова _get_, поскольку они предоставляют информацию. - -- `getFullYear()`, -- `getMonths()`, -- `getDate()`, -- `getDay()`, -- `getHours()`, -- `getMinutes`, -- `getSeconds()`, -- `getMilliseconds()`, -- `getTime()`, -- `getDay()` - -![Date time Object](../images/date_time_object.png) - -### Создание объекта времени - -Однажды мы создаем объект времени. Объект времени предоставит информацию о времени. Давайте создадим объект времени - -```js -const now = new Date(); -console.log(now); // Sat Jan 04 2020 00:56:41 GMT+0200 (Eastern European Standard Time) -``` - -Мы создали объект времени, и мы можем получить доступ к любой информации о дате и времени из объекта, используя методы get, которые мы упомянули в таблице. - -### Получение года - -Давайте извлечем или получим полный объект времени. - -```js -const now = new Date(); -console.log(now.getFullYear()); // 2020 -``` - -### Получение месяца - -Давайте извлечем или получим месяц из объекта времени. - -```js -const now = new Date(); -console.log(now.getMonth()); // 0, потому, что месяц январь, month(0-11) -``` - -### Получение даты - -Давайте извлечем или получим дату месяца из объекта времени. - -```js -const now = new Date(); -console.log(now.getDate()); // 4, потому что день месяца 4th, day(0-31) -``` - -### Получение дня - -Давайте извлечем или получим день недели из объекта времени. - -```js -const now = new Date(); -console.log(now.getDay()); // 6, потому, что день Суббота, который является 5-м днем, -// Получение дня недели в виде числа (0-6) -``` - -### Получение часов - -Давайте извлекать или получать часы из объекта времени. - -```js -const now = new Date(); -console.log(now.getHours()); // 0, потому, что время 00:56:41 -``` - -### Получение минут - -Давайте извлекать или получать минуты из объекта времени. - -```js -const now = new Date(); -console.log(now.getMinutes()); // 56, потому, что время 00:56:41 -``` - -### Получение секунд - -Давайте извлекать или получать секунды из объекта времени. - -```js -const now = new Date(); -console.log(now.getSeconds()); // 41, потому, что время 00:56:41 -``` - -### Получение времени - -Этот метод дает время в миллисекундах, начиная с 1 января 1970 года. Он также известен как время Unix. Мы можем получить время Unix двумя способами: - -1. Используя `getTime()` - - ```js - const now = new Date(); // - console.log(now.getTime()); // 1578092201341, это количество секунд, прошедших с January 1, 1970 to January 4, 2020 00:56:41 - ``` - -2. Используя _Date.now()_ - -```js -const allSeconds = Date.now(); // -console.log(allSeconds); // 1578092201341, это количество секунд, прошедших с January 1, 1970 to January 4, 2020 00:56:41 - -const timeInSeconds = new Date().getTime(); -console.log(allSeconds == timeInSeconds); // true -``` - -Давайте отформатируем эти значения в удобочитаемом формате времени. - -**Пример:** - -```js -const now = new Date(); -const year = now.getFullYear(); // вернет year -const month = now.getMonth() + 1; // вернет month(0 - 11) -const date = now.getDate(); // вернет date (1 - 31) -const hours = now.getHours(); // вернет number (0 - 23) -const minutes = now.getMinutes(); // вернет number (0 -59) - -console.log(`${date}/${month}/${year} ${hours}:${minutes}`); // 4/1/2020 0:56 -``` - -🌕 У вас есть безграничная энергия! Вы только что выполнили 3-й день испытаний, и вы на три шага на пути к успеху. Теперь сделайте несколько упражнений для вашего мозга и ваших мышц. - -## 💻 День 3: Упражнения - -### Упражнения: Уровень 1 - -1. Объявите переменные firstName, lastName, страну, город, возраст, isMarried, year, присвойте ей значение и используйте оператор `typeof` для проверки разных типов данных. -2. Проверьте, равен ли тип «10» 10 -3. Проверьте, равен ли `parseInt ('9.8')` 10 -4. Булево значение равно либо true, либо false. - - 1. Напишите три утверждения JavaScript, которые обеспечивают значение `true`. - 2. Напишите три оператора JavaScript, которые предоставляют значения `false`. - -5. Сначала выясните результат следующего выражения сравнения без использования `console.log()`. После того, как вы определите результат, подтвердите его, используя `console.log()`. - - 1. 4 > 3 - 2. 4 >= 3 - 3. 4 < 3 - 4. 4 <= 3 - 5. 4 == 4 - 6. 4 === 4 - 7. 4 != 4 - 8. 4 !== 4 - 9. 4 != '4' - 10. 4 == '4' - 11. 4 === '4' - 12. Найдите длину python и jargon и сделайте ложное сравнение. - -6. Сначала выясните результат следующих выражений без использования `console.log()`. После того, как вы определите результат, подтвердите его с помощью `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') - 11. В обоих случаях нет 'on' - -7. Используйте объект Date для выполнения следующих действий -     1. Какой сегодня год? -     2. Какой сегодня месяц, как число? -     3. Какая сегодня дата? -     4. Какой сегодня день, как число? -     5. Сколько сейчас часов? -     6. Какие минуты сейчас? -     7. Узнайте количество секунд, прошедших с 1 января 1970 года по настоящее время. - -### Упражнения: уровень 2 - -1. Напишите скрипт, который предложит пользователю ввести основание и высоту треугольника и рассчитать площадь треугольника. (прлощадь = 0.5 x b x h). - - ```sh - Введите основанеи: 20 - Введите высоту: 10 - Площадь треугольника 50 - ``` - -2. Напишите скрипт, который предложит пользователю ввести сторону a, сторону b и сторону c треугольника и вычислить периметр треугольника. (периметр = a + b + c) - - ```sh - Введите сторону a: 5 - Введите сторону b: 4 - Введите сторону c: 3 - Периметр треугольника 12 - ``` - -3. Получите длину и ширину, используя подсказку, и вычислите площадь прямоугольника (площадь = длина х ширина и периметр прямоугольника (периметр = 2 х (длина + ширина)) -4. Получите радиус, используя подсказку, и вычислите площадь круга (площадь = pi x r x r) и окружность круга (c = 2 x pi x r), где pi = 3.14. -5. Рассчитайте наклон, x-пересечение и y-пересечение y = 2x -2 -6. Наклон (m = y2-y1 / x2-x1). Найти наклон между точкой (2, 2) и точкой (6,10) -7. Сравните наклон двух приведенных выше вопросов. -8. Рассчитайте значение y (y = x ^ 2 + 6x + 9). Попробуйте использовать разные значения х и выяснить, при каком значении х у 0. -9. Напишите скрипт, который побудит пользователя вводить часы и ставку за час. Рассчитать зарплату человека? - - ```sh - Введите часы: 40 - Введите ставку в час: 28 - Ваш еженедельный заработок 1120 - ``` - -10. Если длина вашего имени больше 7, скажем, ваше имя длинное, иначе скажем, ваше имя короткое. -11. Сравните длину вашего имени и длину вашей фамилии, и вы должны получить этот вывод. - - ```js - let firstName = "Asabeneh"; - let lastName = "Yetayeh"; - ``` - - ```sh - Твое имя, Asabeneh длиннее вашей фамилии, Yetayeh - ``` - -12. Объявите две переменные _myAge_ и _yourAge_ и присвойте им начальные значения, myAge и yourAge. - - ```js - let myAge = 250; - let yourAge = 25; - ``` - - ```sh - Я на 225 лет старше тебя. - ``` - -13. Используя подсказку, укажите год рождения пользователя и, если ему исполнилось 18 лет, разрешите ему ехать, если он не скажет пользователю подождать определенное количество лет. - - ```sh - Введите год рождения: 1995 - Вам 25. Вы достаточно взрослый, чтобы водить - - Введите год рождения: 2005 - Вам 15. Вам будет разрешено водить после 3 лет. - ``` - -14. Напишите скрипт, который предложит пользователю ввести количество лет. Подсчитайте, сколько секунд человек может прожить. Предположим, кто-то живет всего сто лет - - ```sh - Введите число, в котором вы живете: 100 - - Вы жили 3153600000 секунд. - ``` - -15. Создайте удобочитаемый формат времени, используя объект Date time - 1. YYY-MM-DD HH:mm - 2. DD-MM-YYYY HH:mm - 3. DD/MM/YYY HH:mm - -### Упражнения: уровень 3 - -1. Создайте удобочитаемый формат времени, используя объект Date time. Час и минута должны быть все время двузначными (7 часов должны быть 07, а 5 минут должны быть 05) - 1. YYY-MM-DD HH:mm eg. 20120-01-02 07:05 - -🎉 ПОЗДРАВЛЯЕМ! 🎉 - -[<< День 2](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/RU/02_Day/02_day_data_types.md) | [День 4 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/RU/04_Day/04_day_conditionals.md) diff --git a/RU/04_Day/04_day_conditionals.md b/RU/04_Day/04_day_conditionals.md deleted file mode 100644 index e306cdf..0000000 --- a/RU/04_Day/04_day_conditionals.md +++ /dev/null @@ -1,351 +0,0 @@ -
-

30 Days Of JavaScript

- - - - - Twitter Follow - - -Автор: -Asabeneh Yetayeh
- Январь, 2020 -
- -
- -[<< День 3](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/RU/03_Day/03_booleans_operators_date.md) | [День 5 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/RU/05_Day/05_day_arrays.md) - -![Thirty Days Of JavaScript](../images/banners/day_1_4.png) - -- [📔 День 4](#%f0%9f%93%94-%d0%94%d0%b5%d0%bd%d1%8c-4) - - [Условные операторы](#%d0%a3%d1%81%d0%bb%d0%be%d0%b2%d0%bd%d1%8b%d0%b5-%d0%be%d0%bf%d0%b5%d1%80%d0%b0%d1%82%d0%be%d1%80%d1%8b) - - [if](#if) - - [if else](#if-else) - - [if else if else](#if-else-if-else) - - [Switch](#switch) - - [Тернарный оператор](#%d0%a2%d0%b5%d1%80%d0%bd%d0%b0%d1%80%d0%bd%d1%8b%d0%b9-%d0%be%d0%bf%d0%b5%d1%80%d0%b0%d1%82%d0%be%d1%80) - - [💻 Упражнения](#%f0%9f%92%bb-%d0%a3%d0%bf%d1%80%d0%b0%d0%b6%d0%bd%d0%b5%d0%bd%d0%b8%d1%8f) - - [Упражнения: уровень 1](#%d0%a3%d0%bf%d1%80%d0%b0%d0%b6%d0%bd%d0%b5%d0%bd%d0%b8%d1%8f-%d1%83%d1%80%d0%be%d0%b2%d0%b5%d0%bd%d1%8c-1) - - [Упражнения: уровень 2](#%d0%a3%d0%bf%d1%80%d0%b0%d0%b6%d0%bd%d0%b5%d0%bd%d0%b8%d1%8f-%d1%83%d1%80%d0%be%d0%b2%d0%b5%d0%bd%d1%8c-2) - - [Упражнения: уровень 3](#%d0%a3%d0%bf%d1%80%d0%b0%d0%b6%d0%bd%d0%b5%d0%bd%d0%b8%d1%8f-%d1%83%d1%80%d0%be%d0%b2%d0%b5%d0%bd%d1%8c-3) - -# 📔 День 4 - -## Условные операторы - -Условные операторы используются для принятия решения на основе различных условий. -По умолчанию операторы в скрипте JavaScript выполняются последовательно сверху вниз. Если логика обработки требует этого, последовательный поток выполнения может быть изменен двумя способами: - -- Условное выполнение: блок из одного или нескольких операторов будет выполнен, если определенное выражение истинно -- Повторное выполнение: блок из одного или нескольких операторов будет выполняться повторно, если определенное выражение истинно. В этом разделе мы рассмотрим операторы `if`, `else`, `else if`. Здесь будут полезны сравнение и логический оператор, который мы изучили в предыдущих разделах. - -Условия могут быть реализованы следующими способами: - -- if -- if else -- if else if else -- switch -- ternary operator - -### if - -В JavaScript и других языках программирования ключевое слово `if` используется, чтобы проверить, выполняется ли условие и выполнить код блока. Чтобы создать условие `if`, нам нужно ключевое слово `if`, условие внутри скобки и блок кода внутри фигурной скобки ({}). - -```js -// синтаксис -if (condition) { - //эта часть кода работает для true состояния -} -``` - -**Пример:** - -```js -let num = 3; -if (num > 0) { - console.log(`${num} это положительное число`); -} -// 3 это положительное число -``` - -```js -let isRaining = true; -if (isRaining) { - console.log("Remember to take your rain coat."); -} -``` - -Как видно из вышеприведенного условия, 3 больше 0 и является положительным числом. Условие было выполнено, и код блока был выполнен. Однако, если условие ложно, мы не видим результат. То же самое касается второго условия, если isRaining равен `false`, блок `if` не будет выполнен, и мы не увидим вывод. Чтобы увидеть результат ложного условия, у нас должен быть еще один блок, который будет `else`. - -### if else - -Если условие истинно, первый блок будет выполнен, если нет, будет выполнено условие else. - -```js -// синтаксис -if (condition) { - // эта часть кода работает для истинного состояния -} else { - // эта часть кода выполняется для ложного условия -} -``` - -```js -let num = 3; -if (num > 0) { - console.log(`${num} это положительное число`); -} else { - console.log(`${num} отрицательное число`); -} -// 3 это положительное число - -num = -3; -if (num > 0) { - console.log(`${num} это положительное число`); -} else { - console.log(`${num} это отрицательное число`); -} -// -3 это отрицательное число -``` - -```js -let isRaining = true; -if (isRaining) { - console.log("Тебе нужен плащ от дождя.."); -} else { - console.log("Не нужно пальто от дождя."); -} -// Тебе нужен плащ от дождя. - -isRaining = false; -if (isRaining) { - console.log("Тебе нужен плащ от дождя.."); -} else { - console.log("Не нужно пальто от дождя."); -} -// Не нужно пальто от дождя. -``` - -Вышеуказанное условие ложно, поэтому был выполнен блок `else`. Как насчет, если наше условие больше двух, мы будем использовать `else if` условия. - -### if else if else - -В нашей повседневной жизни мы принимаем решения ежедневно. Мы принимаем решение не проверяя одно или два условия, а принимаем решения на основе нескольких условий. Как и в нашей повседневной жизни, программирование также полно условий. Мы используем `else if`, когда у нас есть несколько условий. - -```js -// синтаксис -if (condition) { - // код -} else if (condition) { - // код -} else { - // код -} -``` - -**Пример:** - -```js -let a = 0; -if (a > 0) { - console.log(`${a} это положительное число`); -} else if (a < 0) { - console.log(`${a} это отрицательное число`); -} else if (a == 0) { - console.log(`${a} это 0`); -} else { - console.log(`${a} это не число`); -} -``` - -```js -// if else if else -let weather = "солнечно"; -if (weather === "дождливо") { - console.log("Вам нужен плащ от дождя."); -} else if (weather === "облачно") { - console.log("Может быть холодно, тебе нужен пиджак."); -} else if (weather === "солнечно") { - console.log("Выйди свободным."); -} else { - console.log("Не нужно пальто от дождя."); -} -``` - -### Switch - -Переключатель является альтернативой для `if else if else else`. -Оператор `switch` начинается с ключевого слова `switch`, за которым следуют скобки и блок кода. Внутри блока кода у нас будут разные случаи. Case case запускается, если значение в скобках оператора `switch` совпадает с case vale. Перерыв должен закончиться, и он не снижается после того, как условие выполнено. Блок по умолчанию выполняется, если все случаи не удовлетворяют условию. - -```js -switch (caseValue) { - case 1: - // код - break; - case 2: - // код - break; - case 3: - // код - default: - // код -} -``` - -```js -let weather = "облачно"; -switch (weather) { - case "дождливо": - console.log("Вам нужен плащ от дождя."); - break; - case "облачно": - console.log("Может быть холодно, тебе нужен пиджак."); - break; - case "солнечно": - console.log("Выйди свободно."); - break; - default: - console.log("Не нужно пальто от дождя."); -} - -// Switch больше примеров -let dayUserInput = prompt("Какой сегодня день ?"); -let day = dayUserInput.toLowerCase(); - -switch (day) { - case "понедельник": - console.log("Сегодня понедельник"); - break; - case "вторник": - console.log("Сегодня вторник"); - break; - case "среда": - console.log("Сегодня среда"); - break; - case "четверг": - console.log("Сегодня четверг"); - break; - case "пятница": - console.log("Сегодня пятница"); - break; - case "суббота": - console.log("Сегодня суббота"); - break; - case "воскресенье": - console.log("Сегодня воскресенье"); - break; - default: - console.log("Это не день недели."); -} -``` - -### Тернарный оператор - -Другой способ написания условных выражений - использование тернарных операторов. Мы рассмотрели это в других разделах, но мы также должны упомянуть об этом здесь. - -```js -let isRaining = true; -isRaining - ? console.log("You need a rain coat.") - : console.log("No need for a rain coat."); -``` - -🌕 Вы необыкновенный и у вас есть замечательный потенциал. Вы только что выполнили четвертый день испытаний и прошли четыре шага на пути к успеху. Теперь сделайте несколько упражнений для вашего мозга и ваших мышц. - -## 💻 Упражнения - -### Упражнения: уровень 1 - -1. Получить пользовательский ввод с помощью `prompt("Введите свой возраст:")`. Если пользователю 18 лет или больше, оставьте отзыв: вы достаточно взрослый, чтобы ездить, но если нет, то 18 - отзывайте, чтобы ждать те годы, которые он должен был ждать. - - ```sh - Введите свой возраст: 30 - Вы достаточно взрослый, чтобы водить. - - Введите свой возраст: 15 - Вам осталось 3 года до вождения. - ``` - -2. Сравните значения myAge и yourAge, используя _if… else_. На основе сравнения журнала для консоли, кто старше (я или вы). Используйте `prompt("Введите свой возраст:")`, чтобы получить возраст в качестве входных данных. - - ```sh - Введите свой возраст: 30 - Ты на 5 лет старше меня. - ``` - -3. Если a больше, чем b, вернуть «a больше, чем b», иначе «a меньше, чем b». Попробуй реализовать в пути - - - используя if else - - тернарный оператор. - - ```js - let a = 4; - let b = 3; - ``` - - ```sh - 4 больше 3 - ``` - -4. Четные числа делятся на 2, а остаток равен нулю. Как проверить, является ли число четным или нет с помощью JavaScript? - - ```sh - Введите число: 2 - 2 - четное число - - Введите число: 9 - 9 является нечетным числом. - ``` - -### Упражнения: уровень 2 - -1. Напишите код, который может дать оценку студентам в соответствии с их оценками: - - 80-100, A - - 70-89, B - - 60-69, C - - 50-59, D - - 0-49, F -2. Проверьте, является ли сезон осенью, зимой, весной или летом. - Если пользовательский ввод: - - сентябрь, октябрь или ноябрь, сезон осень. - - декабрь, январь или февраль, сезон зима. - - март, апрель или май, сезон весна - - июнь, июль или август, сезон лето -3. Проверьте, является ли день выходным или рабочим днем. Ваш сценарий примет день как вход. - - ```sh - Какой сегодня день? Суббота - Суббота - выходной день. - - Какой сегодня день? СубБоТта - Суббота - выходной день. - - Какой сегодня день? Пятница - Пятница рабочий день. - - Какой сегодня день? ПяТНИца - Пятница рабочий день. - ``` - -### Упражнения: уровень 3 - -1. Напишите программу, которая сообщает количество дней в месяце. - - ```sh - Введите месяц: январь - В январе 31 день. - - Введите месяц: ЯНВАРЬ - В январе 31 день - - Введите месяц: февраль - Февраль имеет 28 дней. - - Введите месяц: феВРаль - Февраль имеет 28 дней. - ``` - -🎉 ПОЗДРАВЛЯЕМ ! 🎉 - -[<< День 3](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/RU/03_Day/03_booleans_operators_date.md) | [День 5 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/RU/05_Day/05_day_arrays.md) diff --git a/RU/05_Day/05_day_arrays.md b/RU/05_Day/05_day_arrays.md deleted file mode 100644 index 24ccc68..0000000 --- a/RU/05_Day/05_day_arrays.md +++ /dev/null @@ -1,788 +0,0 @@ -
-

30 Days Of JavaScript

- - - - - Twitter Follow - - -Автор: -Asabeneh Yetayeh
- Январь, 2020 -
- -
- -[<< День 4](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/RU/04_Day/04_day_conditionals.md) | [День 6 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/RU/06_Day/06_day_loops.md) - -![День 5](../images/banners/day_1_5.png) - -- [📔 День 5](#%f0%9f%93%94-%d0%94%d0%b5%d0%bd%d1%8c-5) - - [Массивы](#%d0%9c%d0%b0%d1%81%d1%81%d0%b8%d0%b2%d1%8b) - - [Как создать пустой массив](#%d0%9a%d0%b0%d0%ba-%d1%81%d0%be%d0%b7%d0%b4%d0%b0%d1%82%d1%8c-%d0%bf%d1%83%d1%81%d1%82%d0%be%d0%b9-%d0%bc%d0%b0%d1%81%d1%81%d0%b8%d0%b2) - - [Как создать массив со значениями](#%d0%9a%d0%b0%d0%ba-%d1%81%d0%be%d0%b7%d0%b4%d0%b0%d1%82%d1%8c-%d0%bc%d0%b0%d1%81%d1%81%d0%b8%d0%b2-%d1%81%d0%be-%d0%b7%d0%bd%d0%b0%d1%87%d0%b5%d0%bd%d0%b8%d1%8f%d0%bc%d0%b8) - - [Создание массива с использованием split](#%d0%a1%d0%be%d0%b7%d0%b4%d0%b0%d0%bd%d0%b8%d0%b5-%d0%bc%d0%b0%d1%81%d1%81%d0%b8%d0%b2%d0%b0-%d1%81-%d0%b8%d1%81%d0%bf%d0%be%d0%bb%d1%8c%d0%b7%d0%be%d0%b2%d0%b0%d0%bd%d0%b8%d0%b5%d0%bc-split) - - [Доступ к элементам массива по индексу](#%d0%94%d0%be%d1%81%d1%82%d1%83%d0%bf-%d0%ba-%d1%8d%d0%bb%d0%b5%d0%bc%d0%b5%d0%bd%d1%82%d0%b0%d0%bc-%d0%bc%d0%b0%d1%81%d1%81%d0%b8%d0%b2%d0%b0-%d0%bf%d0%be-%d0%b8%d0%bd%d0%b4%d0%b5%d0%ba%d1%81%d1%83) - - [Изменение элемента массива](#%d0%98%d0%b7%d0%bc%d0%b5%d0%bd%d0%b5%d0%bd%d0%b8%d0%b5-%d1%8d%d0%bb%d0%b5%d0%bc%d0%b5%d0%bd%d1%82%d0%b0-%d0%bc%d0%b0%d1%81%d1%81%d0%b8%d0%b2%d0%b0) - - [Методы манипулирования массивом](#%d0%9c%d0%b5%d1%82%d0%be%d0%b4%d1%8b-%d0%bc%d0%b0%d0%bd%d0%b8%d0%bf%d1%83%d0%bb%d0%b8%d1%80%d0%be%d0%b2%d0%b0%d0%bd%d0%b8%d1%8f-%d0%bc%d0%b0%d1%81%d1%81%d0%b8%d0%b2%d0%be%d0%bc) - - [Конструктор массива](#%d0%9a%d0%be%d0%bd%d1%81%d1%82%d1%80%d1%83%d0%ba%d1%82%d0%be%d1%80-%d0%bc%d0%b0%d1%81%d1%81%d0%b8%d0%b2%d0%b0) - - [Creating static values with fill](#creating-static-values-with-fill) - - [Конкатенация массива с использованием concat](#%d0%9a%d0%be%d0%bd%d0%ba%d0%b0%d1%82%d0%b5%d0%bd%d0%b0%d1%86%d0%b8%d1%8f-%d0%bc%d0%b0%d1%81%d1%81%d0%b8%d0%b2%d0%b0-%d1%81-%d0%b8%d1%81%d0%bf%d0%be%d0%bb%d1%8c%d0%b7%d0%be%d0%b2%d0%b0%d0%bd%d0%b8%d0%b5%d0%bc-concat) - - [Получение длины массива](#%d0%9f%d0%be%d0%bb%d1%83%d1%87%d0%b5%d0%bd%d0%b8%d0%b5-%d0%b4%d0%bb%d0%b8%d0%bd%d1%8b-%d0%bc%d0%b0%d1%81%d1%81%d0%b8%d0%b2%d0%b0) - - [Получение индекса элемента в массиве arr](#%d0%9f%d0%be%d0%bb%d1%83%d1%87%d0%b5%d0%bd%d0%b8%d0%b5-%d0%b8%d0%bd%d0%b4%d0%b5%d0%ba%d1%81%d0%b0-%d1%8d%d0%bb%d0%b5%d0%bc%d0%b5%d0%bd%d1%82%d0%b0-%d0%b2-%d0%bc%d0%b0%d1%81%d1%81%d0%b8%d0%b2%d0%b5-arr) - - [Получение последнего индекса элемента в массиве](#%d0%9f%d0%be%d0%bb%d1%83%d1%87%d0%b5%d0%bd%d0%b8%d0%b5-%d0%bf%d0%be%d1%81%d0%bb%d0%b5%d0%b4%d0%bd%d0%b5%d0%b3%d0%be-%d0%b8%d0%bd%d0%b4%d0%b5%d0%ba%d1%81%d0%b0-%d1%8d%d0%bb%d0%b5%d0%bc%d0%b5%d0%bd%d1%82%d0%b0-%d0%b2-%d0%bc%d0%b0%d1%81%d1%81%d0%b8%d0%b2%d0%b5) - - [Проверка массива](#%d0%9f%d1%80%d0%be%d0%b2%d0%b5%d1%80%d0%ba%d0%b0-%d0%bc%d0%b0%d1%81%d1%81%d0%b8%d0%b2%d0%b0) - - [Преобразование массива в строку](#%d0%9f%d1%80%d0%b5%d0%be%d0%b1%d1%80%d0%b0%d0%b7%d0%be%d0%b2%d0%b0%d0%bd%d0%b8%d0%b5-%d0%bc%d0%b0%d1%81%d1%81%d0%b8%d0%b2%d0%b0-%d0%b2-%d1%81%d1%82%d1%80%d0%be%d0%ba%d1%83) - - [Объединение элементов массива](#%d0%9e%d0%b1%d1%8a%d0%b5%d0%b4%d0%b8%d0%bd%d0%b5%d0%bd%d0%b8%d0%b5-%d1%8d%d0%bb%d0%b5%d0%bc%d0%b5%d0%bd%d1%82%d0%be%d0%b2-%d0%bc%d0%b0%d1%81%d1%81%d0%b8%d0%b2%d0%b0) - - [Элементы массива срезов](#%d0%ad%d0%bb%d0%b5%d0%bc%d0%b5%d0%bd%d1%82%d1%8b-%d0%bc%d0%b0%d1%81%d1%81%d0%b8%d0%b2%d0%b0-%d1%81%d1%80%d0%b5%d0%b7%d0%be%d0%b2) - - [Метод сращивания в массиве](#%d0%9c%d0%b5%d1%82%d0%be%d0%b4-%d1%81%d1%80%d0%b0%d1%89%d0%b8%d0%b2%d0%b0%d0%bd%d0%b8%d1%8f-%d0%b2-%d0%bc%d0%b0%d1%81%d1%81%d0%b8%d0%b2%d0%b5) - - [Добавление элемента в массив с помощью push](#%d0%94%d0%be%d0%b1%d0%b0%d0%b2%d0%bb%d0%b5%d0%bd%d0%b8%d0%b5-%d1%8d%d0%bb%d0%b5%d0%bc%d0%b5%d0%bd%d1%82%d0%b0-%d0%b2-%d0%bc%d0%b0%d1%81%d1%81%d0%b8%d0%b2-%d1%81-%d0%bf%d0%be%d0%bc%d0%be%d1%89%d1%8c%d1%8e-push) - - [Удаление конечного элемента с помощью pop](#%d0%a3%d0%b4%d0%b0%d0%bb%d0%b5%d0%bd%d0%b8%d0%b5-%d0%ba%d0%be%d0%bd%d0%b5%d1%87%d0%bd%d0%be%d0%b3%d0%be-%d1%8d%d0%bb%d0%b5%d0%bc%d0%b5%d0%bd%d1%82%d0%b0-%d1%81-%d0%bf%d0%be%d0%bc%d0%be%d1%89%d1%8c%d1%8e-pop) - - [Удаление элемента с самого начала](#%d0%a3%d0%b4%d0%b0%d0%bb%d0%b5%d0%bd%d0%b8%d0%b5-%d1%8d%d0%bb%d0%b5%d0%bc%d0%b5%d0%bd%d1%82%d0%b0-%d1%81-%d1%81%d0%b0%d0%bc%d0%be%d0%b3%d0%be-%d0%bd%d0%b0%d1%87%d0%b0%d0%bb%d0%b0) - - [Добавить элемент с начала](#%d0%94%d0%be%d0%b1%d0%b0%d0%b2%d0%b8%d1%82%d1%8c-%d1%8d%d0%bb%d0%b5%d0%bc%d0%b5%d0%bd%d1%82-%d1%81-%d0%bd%d0%b0%d1%87%d0%b0%d0%bb%d0%b0) - - [Обратный порядок массивов](#%d0%9e%d0%b1%d1%80%d0%b0%d1%82%d0%bd%d1%8b%d0%b9-%d0%bf%d0%be%d1%80%d1%8f%d0%b4%d0%be%d0%ba-%d0%bc%d0%b0%d1%81%d1%81%d0%b8%d0%b2%d0%be%d0%b2) - - [Сортировка элементов в массиве](#%d0%a1%d0%be%d1%80%d1%82%d0%b8%d1%80%d0%be%d0%b2%d0%ba%d0%b0-%d1%8d%d0%bb%d0%b5%d0%bc%d0%b5%d0%bd%d1%82%d0%be%d0%b2-%d0%b2-%d0%bc%d0%b0%d1%81%d1%81%d0%b8%d0%b2%d0%b5) - - [Массив массивов](#%d0%9c%d0%b0%d1%81%d1%81%d0%b8%d0%b2-%d0%bc%d0%b0%d1%81%d1%81%d0%b8%d0%b2%d0%be%d0%b2) - - [💻 Упражнения](#%f0%9f%92%bb-%d0%a3%d0%bf%d1%80%d0%b0%d0%b6%d0%bd%d0%b5%d0%bd%d0%b8%d1%8f) - - [Упражнения: Уровень 1](#%d0%a3%d0%bf%d1%80%d0%b0%d0%b6%d0%bd%d0%b5%d0%bd%d0%b8%d1%8f-%d0%a3%d1%80%d0%be%d0%b2%d0%b5%d0%bd%d1%8c-1) - - [Упражнения: Уровень 2](#%d0%a3%d0%bf%d1%80%d0%b0%d0%b6%d0%bd%d0%b5%d0%bd%d0%b8%d1%8f-%d0%a3%d1%80%d0%be%d0%b2%d0%b5%d0%bd%d1%8c-2) - - [Упражнения: Уровень 3](#%d0%a3%d0%bf%d1%80%d0%b0%d0%b6%d0%bd%d0%b5%d0%bd%d0%b8%d1%8f-%d0%a3%d1%80%d0%be%d0%b2%d0%b5%d0%bd%d1%8c-3) - -# 📔 День 5 - -## Массивы - -В отличие от переменных, массив может хранить _несколько значений_. Каждое значение в массиве имеет _индекс_, а каждый индекс имеет _ссылку в адресе памяти_. Каждое значение может быть доступно с помощью их _индексов_. Индекс массива начинается с _0_, а последний элемент на единицу меньше длины массива. - -Массив - это коллекция различных типов данных, которые упорядочены и изменяемы (модифицируемы). Массив позволяет хранить повторяющиеся элементы и различные типы данных. Массив может быть пустым или иметь разные значения типа данных. - -### Как создать пустой массив - -В JavaScript мы можем создать массив различными способами. Давайте по-разному создадим массив. -Очень часто используется _const_ вместо _let_ для объявления переменной массива. Если вы используете `const`, это означает, что вы больше не используете это имя. - -- Используя конструктор Array - -```js -// синтаксис -const arr = Array(); -// or -// let arr = new Array() -console.log(arr); // [] -``` - -- Используя квадратные скобки ([]) - -```js -// синтаксис -// Это наиболее рекомендуемый способ создания пустого списка -const arr = []; -console.log(arr); -``` - -### Как создать массив со значениями - -Массив с начальными значениями. Мы используем свойство _length_, чтобы найти длину массива. - -```js -const numbers = [0, 3.14, 9.81, 37, 98.6, 100]; // массив из чисел -const fruits = ["banana", "orange", "mango", "lemon"]; // массив из строк, fruits -const vegetables = ["Tomato", "Potato", "Cabbage", "Onion", "Carrot"]; // массив из строк, vegetables -const animalProducts = ["milk", "meat", "butter", "yoghurt"]; // массив из строк, products -const webTechs = ["HTML", "CSS", "JS", "React", "Redux", "Node", "MongDB"]; // массив из веб технологий -const countries = ["Finland", "Denmark", "Sweden", "Norway", "Iceland"]; // массив из строк, countries - -// Распечатать массив и его длину - -console.log("Numbers:", numbers); -console.log("Number of numbers:", numbers.length); - -console.log("Fruits:", fruits); -console.log("Number of fruits:", fruits.length); - -console.log("Vegetables:", vegetables); -console.log("Number of vegetables:", vegetables.length); - -console.log("Animal products:", animalProducts); -console.log("Number of animal products:", animalProducts.length); - -console.log("Web technologies:", webTechs); -console.log("Number of web technologies:", webTechs.length); - -console.log("Countries:", countries); -console.log("Number of countries:", countries.length); -``` - -```sh -Numbers: [0, 3.14, 9.81, 37, 98.6, 100] -Number of numbers: 6 -Fruits: ['banana', 'orange', 'mango', 'lemon'] -Number of fruits: 4 -Vegetables: ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] -Number of vegetables: 5 -Animal products: ['milk', 'meat', 'butter', 'yoghurt'] -Number of animal products: 4 -Web technologies: ['HTML', 'CSS', 'JS', 'React', 'Redux', 'Node', 'MongDB'] -Number of web technologies: 7 -Countries: ['Finland', 'Estonia', 'Denmark', 'Sweden', 'Norway'] -Number of countries: 5 -``` - -- Массив может иметь элементы разных типов данных - -```js -const arr = [ - "Asabeneh", - 250, - true, - { country: "Finland", city: "Helsinki" }, - { skills: ["HTML", "CSS", "JS", "React", "Python"] } -]; // arr содержит разные типы данных -console.log(arr); -``` - -### Создание массива с использованием split - -Как мы видели в предыдущем разделе, мы можем разбить строку в разных позициях и перейти в массив. Давайте посмотрим на примеры ниже. - -```js -let js = "JavaScript"; -const charsInJavaScript = js.split(""); - -console.log(charsInJavaScript); // ["J", "a", "v", "a", "S", "c", "r", "i", "p", "t"] - -let companiesString = "Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon"; -const companies = companiesString.split(","); - -console.log(companies); // ["Facebook", " Google", " Microsoft", " Apple", " IBM", " Oracle", " Amazon"] -let txt = - "I love teaching and empowering people. I teach HTML, CSS, JS, React, Python."; -const words = txt.split(" "); - -console.log(words); -// в тексте есть специальные символы, подумайте, как можно получить только слова -// ["I", "love", "teaching", "and", "empowering", "people.", "I", "teach", "HTML,", "CSS,", "JS,", "React,", "Python"] -``` - -### Доступ к элементам массива по индексу - -Мы получаем доступ к каждому элементу в массиве, используя их индекс. Индекс массива начинается с 0. На рисунке ниже четко показано начало индекса. - -![arr index](../images/array_index.png) - -```js -const fruits = ["banana", "orange", "mango", "lemon"]; -let firstFruit = fruits[0]; // мы получаем доступ к первому элементу, используя его индекс - -console.log(firstFruit); // banana - -secondFruit = fruits[1]; -console.log(secondFruit); // orange - -let lastFruit = fruits[3]; -console.log(lastFruit); // lemon -// Последний индекс можно рассчитать следующим образом - -let lastIndex = fruits.length - 1; -lastFruit = fruits[lastIndex]; - -console.log(lastFruit); // lemon -``` - -```js -const numbers = [0, 3.14, 9.81, 37, 98.6, 100]; // набор чисел - -console.log(numbers.length); // => узнать размер массива, который 6 -console.log(numbers); // -> [0, 3.14, 9.81, 37, 98.6, 100] -console.log(numbers[0]); // -> 0 -console.log(numbers[5]); // -> 100 - -let lastIndex = numbers.length - 1; -console.log(numbers[lastIndex]); // -> 100 -``` - -```js -const webTechs = [ - "HTML", - "CSS", - "JavaScript", - "React", - "Redux", - "Node", - "MongoDB" -]; // Список веб-технологий - -console.log(webTechs); // все элементы массива -console.log(webTechs.length); // => узнать размер массива, который 7 -console.log(webTechs[0]); // -> HTML -console.log(webTechs[6]); // -> MongoDB - -let lastIndex = webTechs.length - 1; -console.log(webTechs[lastIndex]); // -> MongoDB -``` - -```js -const countries = [ - "Albania", - "Bolivia", - "Canada", - "Denmark", - "Ethiopia", - "Finland", - "Germany", - "Hungary", - "Ireland", - "Japan", - "Kenya" -]; // Список стран - -console.log(countries); // -> все страны в масиве -console.log(countries[0]); // -> Albania -console.log(countries[10]); // -> Kenya - -let lastIndex = countries.length - 1; -console.log(countries[lastIndex]); // -> Kenya -``` - -```js -const shoppingCart = [ - "Milk", - "Mango", - "Tomato", - "Potato", - "Avocado", - "Meat", - "Eggs", - "Sugar" -]; // Список продуктов питания - -console.log(shoppingCart); // -> все shoppingCart в массиве -console.log(shoppingCart[0]); // -> Milk -console.log(shoppingCart[7]); // -> Sugar - -let lastIndex = shoppingCart.length - 1; -console.log(shoppingCart[lastIndex]); // -> Sugar -``` - -### Изменение элемента массива - -Массив является изменяемым (модифицируемым). После создания массива мы можем изменить содержимое элементов массива. - -```js -const numbers = [1, 2, 3, 4, 5]; -numbers[0] = 10; // изменение 1 на индекс 0 до 10 -numbers[1] = 20; // изменение 2 на индекс 1 до 20 - -console.log(numbers); // [10, 20, 3, 4, 5] - -const countries = [ - "Albania", - "Bolivia", - "Canada", - "Denmark", - "Ethiopia", - "Finland", - "Germany", - "Hungary", - "Ireland", - "Japan", - "Kenya" -]; - -countries[0] = "Afghanistan"; // Замена Albania на Afghanistan -let lastIndex = countries.length - 1; -countries[lastIndex] = "Korea"; // Замена Kenya на Korea - -console.log(countries); -``` - -```sh -["Afghanistan", "Bolivia", "Canada", "Denmark", "Ethiopia", "Finland", "Germany", "Hungary", "Ireland", "Japan", "Korea"] -``` - -### Методы манипулирования массивом - -Существуют разные методы манипулирования массивом. Вот некоторые из доступных методов для работы с массивами: _Array, length, concat, indexOf, slice, splice, join, toString, includes, lastIndexOf, isArray, fill, push, pop, shift, unshift_ - -#### Конструктор массива - -Массив: для создания массива. - -```js -const arr = Array(); // создает пустой массив -console.log(arr); - -const eightEmptyValues = Array(8); // он создает восемь пустых значений -console.log(eightEmptyValues); // [empty x 8] -``` - -#### Creating static values with fill - -fill: Fill all the array elements with a static value - -```js -const arr = Array(); // создает пустой массив -console.log(arr); - -const eightXvalues = Array(8).fill("X"); // он создает восемь значений элементов, заполненных 'X' -console.log(eightXvalues); // ['X', 'X','X','X','X','X','X','X'] - -const eight0values = Array(8).fill(0); // он создает восемь значений элементов, заполненных '0' -console.log(eight0values); // [0, 0, 0, 0, 0, 0, 0, 0] - -const four4values = Array(4).fill(4); // он создает 4 значения элемента, заполненные '4' -console.log(four4values); // [4, 4, 4, 4] -``` - -#### Конкатенация массива с использованием concat - -`concat`: объединение двух массивов. - -```js -const firstList = [1, 2, 3]; -const secondList = [4, 5, 6]; -const thirdList = firstList.concat(secondList); - -console.log(thirdList); // [1, 2, 3, 4, 5, 6] -``` - -```js -const fruits = ["banana", "orange", "mango", "lemon"]; // массив из fruits -const vegetables = ["Tomato", "Potato", "Cabbage", "Onion", "Carrot"]; // массив из vegetables -const fruitsAndVegetables = fruits.concat(vegetables); // объединение двух массивов - -console.log(fruitsAndVegetables); -``` - -```sh -["banana", "orange", "mango", "lemon", "Tomato", "Potato", "Cabbage", "Onion", "Carrot"] -``` - -#### Получение длины массива - -`length`: чтобы узнать размер массива - -```js -const numbers = [1, 2, 3, 4, 5]; -console.log(numbers.length); // -> 5 это размер массива -``` - -#### Получение индекса элемента в массиве arr - -`indexOf`: проверить, существует ли элемент в массиве. Если он существует, он возвращает индекс, иначе он возвращает -1. - -```js -const numbers = [1, 2, 3, 4, 5]; - -console.log(numbers.indexOf(5)); // -> 4 -console.log(numbers.indexOf(0)); // -> -1 -console.log(numbers.indexOf(1)); // -> 0 -console.log(numbers.indexOf(6)); // -> -1 -``` - -Проверьте элемент, если он существует в массиве. - -- Проверьте элементы в списке - -```js -// давайте проверим, существует ли banana в массиве - -const fruits = ["banana", "orange", "mango", "lemon"]; -let index = fruits.indexOf("banana"); // 0 - -if (index != -1) { - console.log("Этот фрукт существует в массиве"); -} else { - console.log("Этот фрукт не существует в массиве"); -} -// Этот фрукт существует в массиве - -// мы можем использовать также тернарный оператор здесь -index != -1 - ? console.log("Этот фрукт существует в массиве") - : console.log("Этот фрукт не существует в массиве"); - -// давайте проверим, существует ли в массиве avocado -let indexOfAvocado = fruits.indexOf("avocado"); // -1, если элемент не найден, индекс -1 -if (indexOfAvocado != -1) { - console.log("Этот фрукт существует в массиве"); -} else { - console.log("Этот фрукт не существует в массиве"); -} -// Этот фрукт не существует в массиве -``` - -#### Получение последнего индекса элемента в массиве - -`lastIndexOf`: отдает позицию последнего элемента в массиве. Если он существует, он возвращает индекс, иначе он возвращает -1. - -```js -const numbers = [1, 2, 3, 4, 5, 3, 1, 2]; - -console.log(numbers.lastIndexOf(2)); // 7 -console.log(numbers.lastIndexOf(0)); // -1 -console.log(numbers.lastIndexOf(1)); // 6 -console.log(numbers.lastIndexOf(4)); // 3 -console.log(numbers.lastIndexOf(6)); // -1 -``` - -`includes` в себя: чтобы проверить, существует ли элемент в массиве. Если он существует, он возвращает истину, иначе он возвращает ложь. - -```js -const numbers = [1, 2, 3, 4, 5]; - -console.log(numbers.includes(5)); // true -console.log(numbers.includes(0)); // false -console.log(numbers.includes(1)); // true -console.log(numbers.includes(6)); // false - -const webTechs = [ - "HTML", - "CSS", - "JavaScript", - "React", - "Redux", - "Node", - "MongoDB" -]; // Список веб-технологий - -console.log(webTechs.includes("Node")); // true -console.log(webTechs.includes("C")); // false -``` - -#### Проверка массива - -`Array.isArray`: чтобы проверить, является ли тип данных массивом - -```js -const numbers = [1, 2, 3, 4, 5]; -console.log(Array.isArray(numbers)); // true - -const number = 100; -console.log(Array.isArray(number)); // false -``` - -#### Преобразование массива в строку - -`toString`: преобразовывает массив в строку - -```js -const numbers = [1, 2, 3, 4, 5]; -console.log(numbers.toString()); // 1,2,3,4,5 - -const names = ["Asabeneh", "Mathias", "Elias", "Brook"]; -console.log(names.toString()); // Asabeneh,Mathias,Elias,Brook -``` - -#### Объединение элементов массива - -`join`: используется для соединения элементов массива, аргумент, переданный в методе join, будет объединен в массив и возвращен в виде строки. По умолчанию он соединяется запятой, но мы можем передать другой строковый параметр, который можно объединить между элементами. - -```js -const numbers = [1, 2, 3, 4, 5]; -console.log(numbers.join()); // 1,2,3,4,5 - -const names = ["Asabeneh", "Mathias", "Elias", "Brook"]; - -console.log(names.join()); // Asabeneh,Mathias,Elias,Brook -console.log(names.join("")); //AsabenehMathiasEliasBrook -console.log(names.join(" ")); //Asabeneh Mathias Elias Brook -console.log(names.join(", ")); //Asabeneh, Mathias, Elias, Brook -console.log(names.join(" # ")); //Asabeneh # Mathias # Elias # Brook - -const webTechs = [ - "HTML", - "CSS", - "JavaScript", - "React", - "Redux", - "Node", - "MongoDB" -]; // Список веб-технологий - -console.log(webTechs.join()); // "HTML,CSS,JavaScript,React,Redux,Node,MongoDB" -console.log(webTechs.join(" # ")); // "HTML # CSS # JavaScript # React # Redux # Node # MongoDB" -``` - -#### Элементы массива срезов - -`slice`: вырезает несколько предметов из диапазона. -Требуется два параметра: начальная и конечная позиция. Это не включает в себя конечную позицию. - -```js -const numbers = [1, 2, 3, 4, 5]; - -console.log(numbers.slice()); // -> it copies all item -console.log(numbers.slice(0)); // -> it copies all item -console.log(numbers.slice(0, numbers.length)); // it copies all item -console.log(numbers.slice(1, 4)); // -> [2,3,4] // it doesn't include the ending position -``` - -#### Метод сращивания в массиве - -`splice`: требуется три параметра: начальная позиция, количество удалений и количество добавляемых элементов. - -```js -const numbers = [1, 2, 3, 4, 5]; - -console.log(numbers.splice()); // -> удалить все предметы -``` - -```js -const numbers = [1, 2, 3, 4, 5]; -console.log(numbers.splice(0, 1)); // удалить первый элемент -``` - -```js -const numbers = [1, 2, 3, 4, 5]; -console.log(numbers.splice(3, 3, 6, 7, 8)); // -> [1, 2, 3, 6, 7, 8] // удаляет два элемента и заменяет три -``` - -#### Добавление элемента в массив с помощью push - -`push`: добавление элемента в конце. Чтобы добавить элемент в конец существующего массива, мы используем метод `push`. - -```js -// синтаксис -const arr = ["item1", "item2", "item3"]; -arr.push("new item"); - -console.log(arr); -// ['item1', 'item2','item3','new item'] -``` - -```js -const numbers = [1, 2, 3, 4, 5]; -numbers.push(6); - -console.log(numbers); // -> [1,2,3,4,5,6] - -numbers.pop(); // -> убрать один предмет с конца -console.log(numbers); // -> [1,2,3,4,5] -``` - -```js -let fruits = ["banana", "orange", "mango", "lemon"]; -fruits.push("apple"); - -console.log(fruits); // ['banana', 'orange', 'mango', 'lemon', 'apple'] - -fruits.push("lime"); -console.log(fruits); // ['banana', 'orange', 'mango', 'lemon', 'apple', 'lime'] -``` - -#### Удаление конечного элемента с помощью pop - -`pop`: удаление элемента в конце. - -```js -const numbers = [1, 2, 3, 4, 5]; -numbers.pop(); // -> убрать один предмет с конца - -console.log(numbers); // -> [1,2,3,4] -``` - -#### Удаление элемента с самого начала - -`shift`: удаление одного элемента массива в начале массива. - -```js -const numbers = [1, 2, 3, 4, 5]; -numbers.shift(); // -> удаление одного элемента с начала - -console.log(numbers); // -> [2,3,4,5] -``` - -#### Добавить элемент с начала - -`unshift`: добавление элемента массива в начало массива. - -```js -const numbers = [1, 2, 3, 4, 5]; -numbers.unshift(0); // -> добавить один элемент с начала - -console.log(numbers); // -> [0,1,2,3,4,5] -``` - -#### Обратный порядок массивов - -`reverse`: обратный порядок массива. - -```js -const numbers = [1, 2, 3, 4, 5]; -numbers.reverse(); // -> обратный порядок массива - -console.log(numbers); // [5, 4, 3, 2, 1] - -numbers.reverse(); -console.log(numbers); // [1, 2, 3, 4, 5] -``` - -#### Сортировка элементов в массиве - -`sort`: расположить элементы массива в порядке возрастания. Сортировка принимает функцию обратного вызова, мы увидим, как мы используем сортировку с функцией обратного вызова в следующих разделах. - -```js -const webTechs = [ - "HTML", - "CSS", - "JavaScript", - "React", - "Redux", - "Node", - "MongoDB" -]; - -webTechs.sort(); -console.log(webTechs); // ["CSS", "HTML", "JavaScript", "MongoDB", "Node", "React", "Redux"] - -webTechs.reverse(); // после сортировки мы можем изменить это -console.log(webTechs); // ["Redux", "React", "Node", "MongoDB", "JavaScript", "HTML", "CSS"] -``` - -### Массив массивов - -Массив может хранить различные типы данных, включая сам массив. Давайте создадим массив массивов - -```js -const firstNums = [1, 2, 3]; -const secondNums = [1, 4, 9]; - -const arrayOfArray = [ - [1, 2, 3], - [1, 2, 3] -]; -console.log(arrayOfArray[0]); // [1, 2, 3] - -const frontEnd = ["HTML", "CSS", "JS", "React", "Redux"]; -const backEnd = ["Node", "Express", "MongoDB"]; -const fullStack = [frontEnd, backEnd]; -console.log(fullStack); // [["HTML", "CSS", "JS", "React", "Redux"], ["Node", "Express", "MongoDB"]] -console.log(fullStack.length); // 2 -console.log(fullStack[0]); // ["HTML", "CSS", "JS", "React", "Redux"] -console.log(fullStack[1]); // ["Node", "Express", "MongoDB"] -``` - -🌕Вы прилежны, и вы уже многого достигли. Вы только что завершили 5-й день испытаний, и вы на 5 шагов приблизились к своему пути к успеху. Теперь сделайте несколько упражнений для вашего мозга и ваших мышц. - -## 💻 Упражнения - -### Упражнения: Уровень 1 - -```js -const countries = [ - "Albania", - "Bolivia", - "Canada", - "Denmark", - "Ethiopia", - "Finland", - "Germany", - "Hungary", - "Ireland", - "Japan", - "Kenya" -]; - -const webTechs = [ - "HTML", - "CSS", - "JavaScript", - "React", - "Redux", - "Node", - "MongoDB" -]; -``` - -1. Объявите массив _empty_; -2. Объявить массив с более чем 5 количеством элементов -3. Найдите длину вашего массива -4. Получить первый элемент, средний элемент и последний элемент массива -5. Объявите массив с именем _mixedDataTypes_, поместите различные типы данных в ваш массив и найдите длину массива. Вы должны быть размером больше 5 -6. Объявите имя переменной массива _itCompanies_ и присвойте начальные значения Facebook, Google, Microsoft, Apple, IBM, Oracle и Amazon -7. Напечатайте массив, используя `console.log()` -8. Распечатайте количество компаний в массиве -9. Распечатать первую компанию, среднюю и последнюю компанию -10. Распечатайте каждую компанию -11. Измените название каждой компании на заглавные по одному и напечатайте их -12. Распечатайте массив как предложение: Facebook, Google, Microsoft, Apple, IBM, Oracle и Amazon являются крупными ИТ-компаниями. -13. Проверьте, существует ли определенная компания в массиве _itCompanies_. Если она существует, верните компанию, иначе верните компанию, которая не найдена -14. Отфильтруйте компании, которые имеют более одного «o» без метода фильтра -15. Сортировать массив с помощью метода `sort()` -16. Обратный массив, используя метод `reverse()` -17. Вырежьте первые 3 компании из массива -18. Вырежьте последние 3 компании из массива -19. Вырежьте середину ИТ-компании или компаний из массива -20. Удалить первую IT-компанию из массива -21. Уберите среднюю ИТ-компанию или компании из массива -22. Удалить последнюю ИТ-компанию из массива -23. Удалить все ИТ-компании - -### Упражнения: Уровень 2 - -1. Создайте отдельный файл _country.js_ и сохраните массив стран в этот файл, создайте отдельный файл _web_techs.js_ и сохраните массив _webTechs_ в этом файле. Доступ к обоим файлам в файле _main.js_ -2. Сначала удалите все функции и измените строку на массив и посчитайте количество слов в массиве - - ```js - let text = - "I love teaching and empowering people. I teach HTML, CSS, JS, React, Python."; - console.log(words); - console.log(words.length); - ``` - - ```sh - ["I", "love", "teaching", "and", "empowering", "people", "I", "teach", "HTML", "CSS", "JS", "React", "Python"] - - 13 - ``` - -3. В следующей корзине добавить, удалить, изменить элементы - - ```js - const shoppingCart = ["Milk", "Coffee", "Tea", "Honey"]; - ``` - - - добавьте 'Meat' в начале вашей корзины, если оно еще не добавлено - - добавьте sugar в конец вашей корзины, если он еще не добавлен - - Удалить 'Honey', если у вас аллергия на мед - - изменить чай на 'Green Tea' - -4. В массиве стран проверьте, существует ли в массиве 'Ethiopia', напечатайте 'Ethiopia'. Если его нет, добавьте в список стран. -5. В массиве webTechs проверьте, существует ли в массиве Sass, и если он существует, выведите «Sass - это препроцесс CSS». Если он не существует, добавьте Sass в массив и распечатайте массив. -6. Объедините следующие две переменные и сохраните их в переменной fullStack. - - ```js - const frontEnd = ["HTML", "CSS", "JS", "React", "Redux"]; - const backEnd = ["Node", "Express", "MongoDB"]; - - console.log(fullStack); - ``` - - ```sh - ["HTML", "CSS", "JS", "React", "Redux", "Node", "Express", "MongoDB"] - ``` - -### Упражнения: Уровень 3 - -1. Ниже приведен массив из 10 студентов в возрасте: - - ```js - const ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24]; - ``` - - - Отсортировать массив и найти минимальный и максимальный возраст - - Найти средний возраст (один средний или два средних, разделенные на два) - - Найти средний возраст (все предметы, поделенные на количество предметов) - - Найти диапазон возрастов (максимум минус мин) - - Сравните значения (минимум - среднее) и (максимум - среднее), используйте метод `abs()` - - 1. Разделите первые десять стран из [массива стран](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) - -2. Найдите среднюю страну (страны) в [массиве стран](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) -3. Разделите массив стран на два равных массива, если он четный. Если массив стран не является четным, еще одна страна для первой половины. - -🎉 ПОЗДРАВЛЯЕМ ! 🎉 - -[<< День 4](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/RU/04_Day/04_day_conditionals.md) | [День 6 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/RU/06_Day/06_day_loops.md) diff --git a/RU/06_Day/06_day_loops.md b/RU/06_Day/06_day_loops.md deleted file mode 100644 index 3308eb4..0000000 --- a/RU/06_Day/06_day_loops.md +++ /dev/null @@ -1,443 +0,0 @@ -
-

30 Days Of JavaScript

- - - - - Twitter Follow - - -Автор: -Asabeneh Yetayeh
- Январь, 2020 -
- -
- -[<< День 5](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/RU/05_Day/05_day_arrays.md) | [День 7 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/RU/07_Day/07_day_functions.md) - -![Day 5](../images/banners/day_1_6.png) - -- [📔 День 6](#%f0%9f%93%94-%d0%94%d0%b5%d0%bd%d1%8c-6) - - [Циклы](#%d0%a6%d0%b8%d0%ba%d0%bb%d1%8b) - - [Цикл for](#%d0%a6%d0%b8%d0%ba%d0%bb-for) - - [Цикл while](#%d0%a6%d0%b8%d0%ba%d0%bb-while) - - [Цикл do while](#%d0%a6%d0%b8%d0%ba%d0%bb-do-while) - - [Цикл for of](#%d0%a6%d0%b8%d0%ba%d0%bb-for-of) - - [break](#break) - - [continue](#continue) - - [💻 Упражнения: День 6](#%f0%9f%92%bb-%d0%a3%d0%bf%d1%80%d0%b0%d0%b6%d0%bd%d0%b5%d0%bd%d0%b8%d1%8f-%d0%94%d0%b5%d0%bd%d1%8c-6) - - [Упражнения: Уровень 1](#%d0%a3%d0%bf%d1%80%d0%b0%d0%b6%d0%bd%d0%b5%d0%bd%d0%b8%d1%8f-%d0%a3%d1%80%d0%be%d0%b2%d0%b5%d0%bd%d1%8c-1) - - [Упражнения: Уровень 2](#%d0%a3%d0%bf%d1%80%d0%b0%d0%b6%d0%bd%d0%b5%d0%bd%d0%b8%d1%8f-%d0%a3%d1%80%d0%be%d0%b2%d0%b5%d0%bd%d1%8c-2) - - [Упражнения: Уровень 3](#%d0%a3%d0%bf%d1%80%d0%b0%d0%b6%d0%bd%d0%b5%d0%bd%d0%b8%d1%8f-%d0%a3%d1%80%d0%be%d0%b2%d0%b5%d0%bd%d1%8c-3) - -# 📔 День 6 - -## Циклы - -Большинство действий, которые мы делаем в жизни, полны повторений. Представьте себе, если я попрошу вас распечатать от 0 до 100, используя `console.log()`. Для реализации этой простой задачи может потребоваться от 2 до 5 минут, такая утомительная и повторяющаяся задача может быть выполнена с помощью цикла. - -В языках программирования для выполнения повторяющихся задач мы используем разные виды циклов. Следующие примеры представляют собой наиболее часто используемые циклы. - -### Цикл for - -```js -// Структура цикла for -for(initialization, condition, increment/decrement){ - // код идет здесь -} -``` - -```js -for (let i = 0; i <= 5; i++) { - console.log(i); -} -// 0 1 2 3 4 5 -``` - -```js -for (let i = 5; i >= 0; i--) { - console.log(i); -} -// 5 4 3 2 1 0 -``` - -```js -for (let i = 0; i <= 5; i++) { - console.log(`${i} * ${i} = ${i * i}`); -} -``` - -```sh -0 * 0 = 0 -1 * 1 = 1 -2 * 2 = 4 -3 * 3 = 9 -4 * 4 = 16 -5 * 5 = 25 -``` - -```js -const countries = ["Finland", "Sweden", "Denmark", "Norway", "Iceland"]; -const newArr = []; -for (let i = 0; i < countries.length; i++) { - newArr.push(countries[i].toUpperCase()); -} -//["FINLAND", "SWEDEN", "DENMARK", "NORWAY", "ICELAND"] -``` - -Добавление всех элементов в массив - -```js -const numbers = [1, 2, 3, 4, 5]; -let sum = 0; -for (let i = 0; i < numbers.length; i++) { - sum = sum + numbers[i]; // можно сократить: sum += numbers[i] -} - -console.log(sum); // 15 -``` - -Создание нового массива на основе существующего массива - -```js -const numbers = [1, 2, 3, 4, 5]; -const newArr = []; -let sum = 0; -for (let i = 0; i < numbers.length; i++) { - newArr.push(i * i); -} - -console.log(newArr); // [1, 4, 9, 16, 25] -``` - -```js -const countries = ["Finland", "Sweden", "Norway", "Denmark", "Iceland"]; -const newArr = []; -for (let i = 0; i < countries.length; i++) { - newArr.push(countries[i].toUpperCase()); -} - -console.log(newArr); // ["FINLAND", "SWEDEN", "NORWAY", "DENMARK", "ICELAND"] -``` - -### Цикл while - -```js -let i = 0; -while (i <= 5) { - console.log(i); - i++; -} -// 0 1 2 3 4 5 -``` - -### Цикл do while - -```js -let i = 0; -do { - console.log(i); - i++; -} while (i <= 5); -// 0 1 2 3 4 5 -``` - -### Цикл for of - -Мы используем для цикла для массивов. Это очень удобный способ перебора массива, если мы не заинтересованы в индексе. - -```js -for (const element of arr) { - // код идет здесь -} -``` - -```js -const numbers = [1, 2, 3, 4, 5]; - -for (const num of numbers) { - console.log(num); //1 2 3 4 5 -} - -for (const num of numbers) { - console.log(num * num); //1 4 9 16 25 -} - -// добавление всех чисел в массиве -let sum = 0; -for (const num of numbers) { - sum += sum + num; // можно также сократить, как это: sum += num -} -console.log(sum); // 15 - -const webTechs = [ - "HTML", - "CSS", - "JavaScript", - "React", - "Redux", - "Node", - "MongoDB" -]; - -for (const tech of webTechs) { - console.log(tech.toUpperCase()); // HTML CSS JAVASCRIPT REACT NODE MONGODB -} - -for (const tech of webTechs) { - console.log(tech[0]); // получить только первую букву каждого элемента, H C J R N M -} -``` - -```js -const countries = ["Finland", "Sweden", "Norway", "Denmark", "Iceland"]; -const newArr = []; -for (const country of countries) { - newArr.push(country.toUpperCase()); -} - -console.log(newArr); // ["FINLAND", "SWEDEN", "NORWAY", "DENMARK", "ICELAND"] -``` - -### break - -контент будет добавлен в ближайшее время - -### continue - -контент будет добавлен в ближайшее время - -🌕 Ты такой смелый, что дошел так далеко. Теперь вы получили возможность автоматизировать повторяющиеся и утомительные задачи. Вы только что завершили 6-й день испытаний, и вы на 6 ступенек на пути к успеху. Теперь сделайте несколько упражнений для вашего мозга и ваших мышц. - -## 💻 Упражнения: День 6 - -### Упражнения: Уровень 1 - -```js -const countries = [ - "Albania", - "Bolivia", - "Canada", - "Denmark", - "Ethiopia", - "Finland", - "Germany", - "Hungary", - "Ireland", - "Japan", - "Kenya" -]; - -const webTechs = [ - "HTML", - "CSS", - "JavaScript", - "React", - "Redux", - "Node", - "MongoDB" -]; - -const mernStack = ["MongoDB", "Express", "React", "Node"]; -``` - -1. Выполните итерацию от 0 до 10 с помощью цикла `for`, сделайте то же самое с помощью циклов `while` и `do while` -2. Итерируйте 10 к 0, используя цикл `for`, cделайте то же самое, используя цикл `while` и `do while` -3. Итерируйте от 0 до n, используя цикл `for` -4. Напишите цикл, который создает следующий шаблон, используя `console.log()`: - - ```js - # - ## - ### - #### - ##### - ###### - ####### - ``` - -5. Используйте цикл для печати следующего шаблона: - - ```sh - 0 x 0 = 0 - 1 x 1 = 1 - 2 x 2 = 4 - 3 x 3 = 9 - 4 x 4 = 16 - 5 x 5 = 25 - 6 x 6 = 36 - 7 x 7 = 49 - 8 x 8 = 64 - 9 x 9 = 81 - 10 x 10 = 100 - ``` - -6. Используя цикл, напечатайте следующий шаблон - - ```sh - i i^2 i^3 - 0 0 0 - 1 1 1 - 2 4 8 - 3 9 27 - 4 16 64 - 5 25 125 - 6 36 216 - 7 49 343 - 8 64 512 - 9 81 729 - 10 100 1000 - ``` - -7. Используйте цикл для перебора от 0 до 100 и печати только четных чисел. -8. Используйте цикл для итерации от 0 до 100 и выведите только нечетные числа -9. Используйте цикл для итерации от 0 до 100 и печатайте только простые числа -10. Используйте цикл для итерации от 0 до 100, распечатайте и распечатайте сумму всех чисел. - - ```sh - Сумма всех чисел 5050. - ``` - -11. Используйте цикл `for` для итерации от 0 до 100 и выведите сумму всех четных чисел и сумму всех коэффициентов. - - ```sh - The sum of all evens is 2550. And the sum of all odds is 2500. - ``` - -12. Используйте цикл `for` для итерации от 0 до 100 и выведите сумму всех четных чисел и сумму всех шансов. Вывести сумму четных и сумму шансов в виде массива - - ```sh - [2550, 2500] - ``` - -13. Разработайте небольшой скрипт, который генерирует массив из 5 случайных чисел -14. Разработайте небольшой скрипт, который генерирует массив из 5 случайных чисел, числа должны быть уникальными -15. Разработайте небольшой скрипт, который генерирует случайный идентификатор из шести символов: - - ```sh - 5j2khz - ``` - -### Упражнения: Уровень 2 - -1. Разработайте небольшой скрипт, который генерирует произвольное количество символов случайного идентификатора: - - ```sh - fe3jo1gl124g - ``` - - ```sh - xkqci4utda1lmbelpkm03rba - ``` - -2. Напишите скрипт, который генерирует случайное шестнадцатеричное число - - ```sh - '#ee33df' - ``` - -3. Напишите скрипт, который генерирует случайное число цветов RGB. - - ```sh - rgb(240,180,80) - ``` - -4. Используя вышеуказанный массив стран, создайте следующий новый массив. - - ```sh - ["ALBANIA", "BOLIVIA", "CANADA", "DENMARK", "ETHIOPIA", "FINLAND", "GERMANY", "HUNGARY", "IRELAND", "JAPAN", "KENYA"] - ``` - -5. Используя приведенный выше массив стран, создайте массив для длины стран. - - ```sh - [7, 7, 6, 7, 8, 7, 7, 7, 7, 5, 5] - ``` - -6. Используйте массив стран для создания следующего массива массивов: - - ```sh - [ - ['Albania', 'ALB', 7], - ['Bolivia', 'BOL', 7], - ['Canada', 'CAN', 6], - ['Denmark', 'DEN', 7], - ['Ethiopia', 'ETH', 8], - ['Finland', 'FIN', 7], - ['Germany', 'GER', 7], - ['Hungary', 'HUN', 7], - ['Ireland', 'IRE', 7], - ['Japan', 'JAP', 5], - ['Kenya', 'KEN', 5] - ] - ``` - -7. В приведенном выше массиве стран проверьте, существует ли страна или страны, содержащие слово 'land'. Если есть страны, содержащие 'land', выведите ее в виде массива. Если нет страны, содержащей слово 'land', выведите «All these are countries without land». - - ```sh - ['Finland', 'Iceland'] - ``` - -8. В приведенном выше массиве стран проверьте, существует ли страна или страны, заканчивающиеся на «ia». Если есть страны, оканчивающиеся на, распечатайте его, как массив. Если нет страны, содержащей слово «ai», выведите «Эти страны заканчиваются без ia». - - ```sh - ['Albania', 'Bolivia','Ethiopia'] - ``` - -9. Используя приведенный выше массив стран, найдите страну, содержащую наибольшее количество символов. - - ```sh - Ethiopia - ``` - -10. Используя приведенный выше массив стран, найдите страну, содержащую всего 5 символов. - - ```sh - ['Japan', 'Kenya'] - ``` - -11. Найдите самое длинное слово в массиве webTechs. -12. Используйте webTechs для создания следующего массива массивов: - - ```sh - [["HTML", 4], ["CSS", 3],["JavaScript", 10],["React", 5],["Redux", 5],["Node", 4],["MongoDB", 7]] - ``` - -13. Приложение, созданное с использованием MongoDB, Express, React и Node, называется стеком MERN. Создайте аббревиатуру MERN с помощью массива mernStack. -14. Итерируйте по массиву, `["HTML", "CSS", "JS", "React", "Redux", "Node", "Express", "MongoDB"]`, используя цикл `for` или цикл `for of` печатайте из предметов. -15. Это массив фруктов `['banana', 'orange', 'mango', 'lemon']` измените порядок, используя цикл, без использования обратного метода. -16. Распечатайте все элементы массива, как показано ниже. - - ```js - const fullStack = [ - ["HTML", "CSS", "JS", "React"], - ["Node", "Express", "MongoDB"] - ]; - ``` - - ```sh - HTML - CSS - JS - REACT - NODE - EXPRESS - MONGODB - ``` - -### Упражнения: Уровень 3 - -1. Скопируйте массив стран (избегайте мутаций) -2. Массивы изменчивы. Создайте копию массива, которая не изменяет оригинал. Сортировать скопированный массив и сохранить в переменной _sortedCountries_ -3. Отсортируйте массив `webTechs` и массив `mernStack` -4. Извлеките все страны содержащие слово 'land' в [массив стран](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) и распечатайте его как массив -5. Найдите страну, содержащую наибольшее количество символов в [массиве стран](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) -6. Извлеките все страны содержащие слово 'land' from the [массив стран](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) и распечатайте его как массив -7. Извлеките все страны, содержащие только четыре символа из [массива стран](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) и распечатайте его как массив -8. Извлеките все страны, содержащие два или более слов из [массив стран](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) и распечатайте его как массив -9. Разверните [массив стран](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) и примените метод capitalize для каждой страны, храня его в виде массива - -🎉 ПОЗДРАВЛЯЕМ ! 🎉 - -[<< День 5](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/RU/05_Day/05_day_arrays.md) | [День 7 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/RU/07_Day/07_day_functions.md) diff --git a/RU/README.md b/RU/README.md deleted file mode 100644 index 8180bfe..0000000 --- a/RU/README.md +++ /dev/null @@ -1,623 +0,0 @@ -
-

30 Days Of JavaScript

- - - - - Twitter Follow - - -Автор: -Asabeneh Yetayeh
- Январь, 2020 -
- -
- - 🇬🇧 [English](../readMe.md) - 🇪🇸 [Spanish](../Spanish/readme.md) - 🇷🇺 [Russian](./README.md) - -
- -
- -[День 2 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/RU/02_Day/02_day_data_types.md) - -![Thirty Days Of JavaScript](./images/day_1_1.png) - -- [День 1](#%d0%94%d0%b5%d0%bd%d1%8c-1) - - [Вступление](#%d0%92%d1%81%d1%82%d1%83%d0%bf%d0%bb%d0%b5%d0%bd%d0%b8%d0%b5) - - [Требования](#%d0%a2%d1%80%d0%b5%d0%b1%d0%be%d0%b2%d0%b0%d0%bd%d0%b8%d1%8f) - - [Настройка](#%d0%9d%d0%b0%d1%81%d1%82%d1%80%d0%be%d0%b9%d0%ba%d0%b0) - - [Установка Node.js](#%d0%a3%d1%81%d1%82%d0%b0%d0%bd%d0%be%d0%b2%d0%ba%d0%b0-nodejs) - - [Браузер](#%d0%91%d1%80%d0%b0%d1%83%d0%b7%d0%b5%d1%80) - - [Установка Google Chrome](#%d0%a3%d1%81%d1%82%d0%b0%d0%bd%d0%be%d0%b2%d0%ba%d0%b0-google-chrome) - - [Открытие Google Chrome Console](#%d0%9e%d1%82%d0%ba%d1%80%d1%8b%d1%82%d0%b8%d0%b5-google-chrome-console) - - [Написание кода на консоли браузера](#%d0%9d%d0%b0%d0%bf%d0%b8%d1%81%d0%b0%d0%bd%d0%b8%d0%b5-%d0%ba%d0%be%d0%b4%d0%b0-%d0%bd%d0%b0-%d0%ba%d0%be%d0%bd%d1%81%d0%be%d0%bb%d0%b8-%d0%b1%d1%80%d0%b0%d1%83%d0%b7%d0%b5%d1%80%d0%b0) - - [Console.log](#consolelog) - - [Console.log with multiple arguments](#consolelog-with-multiple-arguments) - - [Комментарии](#%d0%9a%d0%be%d0%bc%d0%bc%d0%b5%d0%bd%d1%82%d0%b0%d1%80%d0%b8%d0%b8) - - [Синтаксис](#%d0%a1%d0%b8%d0%bd%d1%82%d0%b0%d0%ba%d1%81%d0%b8%d1%81) - - [Арифметика](#%d0%90%d1%80%d0%b8%d1%84%d0%bc%d0%b5%d1%82%d0%b8%d0%ba%d0%b0) - - [Редактор кода](#%d0%a0%d0%b5%d0%b4%d0%b0%d0%ba%d1%82%d0%be%d1%80-%d0%ba%d0%be%d0%b4%d0%b0) - - [Установка Visual Studio Code](#%d0%a3%d1%81%d1%82%d0%b0%d0%bd%d0%be%d0%b2%d0%ba%d0%b0-visual-studio-code) - - [Как использовать VS Code](#%d0%9a%d0%b0%d0%ba-%d0%b8%d1%81%d0%bf%d0%be%d0%bb%d1%8c%d0%b7%d0%be%d0%b2%d0%b0%d1%82%d1%8c-vs-code) - - [Добавление JavaScript на веб-страницу](#%d0%94%d0%be%d0%b1%d0%b0%d0%b2%d0%bb%d0%b5%d0%bd%d0%b8%d0%b5-javascript-%d0%bd%d0%b0-%d0%b2%d0%b5%d0%b1-%d1%81%d1%82%d1%80%d0%b0%d0%bd%d0%b8%d1%86%d1%83) - - [Встроенный скрипт](#%d0%92%d1%81%d1%82%d1%80%d0%be%d0%b5%d0%bd%d0%bd%d1%8b%d0%b9-%d1%81%d0%ba%d1%80%d0%b8%d0%bf%d1%82) - - [Внутренний скрипт](#%d0%92%d0%bd%d1%83%d1%82%d1%80%d0%b5%d0%bd%d0%bd%d0%b8%d0%b9-%d1%81%d0%ba%d1%80%d0%b8%d0%bf%d1%82) - - [Внешний скрипт](#%d0%92%d0%bd%d0%b5%d1%88%d0%bd%d0%b8%d0%b9-%d1%81%d0%ba%d1%80%d0%b8%d0%bf%d1%82) - - [Несколько внешних скриптов](#%d0%9d%d0%b5%d1%81%d0%ba%d0%be%d0%bb%d1%8c%d0%ba%d0%be-%d0%b2%d0%bd%d0%b5%d1%88%d0%bd%d0%b8%d1%85-%d1%81%d0%ba%d1%80%d0%b8%d0%bf%d1%82%d0%be%d0%b2) - - [Введение в типы данных](#%d0%92%d0%b2%d0%b5%d0%b4%d0%b5%d0%bd%d0%b8%d0%b5-%d0%b2-%d1%82%d0%b8%d0%bf%d1%8b-%d0%b4%d0%b0%d0%bd%d0%bd%d1%8b%d1%85) - - [Число](#%d0%a7%d0%b8%d1%81%d0%bb%d0%be) - - [Строка](#%d0%a1%d1%82%d1%80%d0%be%d0%ba%d0%b0) - - [Пример](#%d0%9f%d1%80%d0%b8%d0%bc%d0%b5%d1%80) - - [Булевый (логический) тип «boolean»](#%d0%91%d1%83%d0%bb%d0%b5%d0%b2%d1%8b%d0%b9-%d0%bb%d0%be%d0%b3%d0%b8%d1%87%d0%b5%d1%81%d0%ba%d0%b8%d0%b9-%d1%82%d0%b8%d0%bf-%c2%abboolean%c2%bb) - - [Пример](#%d0%9f%d1%80%d0%b8%d0%bc%d0%b5%d1%80-1) - - [Undefined](#undefined) - - [Null](#null) - - [Проверка типов данных](#%d0%9f%d1%80%d0%be%d0%b2%d0%b5%d1%80%d0%ba%d0%b0-%d1%82%d0%b8%d0%bf%d0%be%d0%b2-%d0%b4%d0%b0%d0%bd%d0%bd%d1%8b%d1%85) - - [Комментарии](#%d0%9a%d0%be%d0%bc%d0%bc%d0%b5%d0%bd%d1%82%d0%b0%d1%80%d0%b8%d0%b8-1) - - [Переменные](#%d0%9f%d0%b5%d1%80%d0%b5%d0%bc%d0%b5%d0%bd%d0%bd%d1%8b%d0%b5) - - [Примеры: Переменные](#%d0%9f%d1%80%d0%b8%d0%bc%d0%b5%d1%80%d1%8b-%d0%9f%d0%b5%d1%80%d0%b5%d0%bc%d0%b5%d0%bd%d0%bd%d1%8b%d0%b5) -- [💻 День 1: Упражнения](#%f0%9f%92%bb-%d0%94%d0%b5%d0%bd%d1%8c-1-%d0%a3%d0%bf%d1%80%d0%b0%d0%b6%d0%bd%d0%b5%d0%bd%d0%b8%d1%8f) - -# День 1 - -## Вступление - -**Поздравляем** с решением принять участие в 30-дневном челендже по программированию на JavaScript. В этом задании вы изучите все, что вам нужно для того, чтобы стать программистом на JavaScript, и вообще все концепции программирования. В конце конкурса вы получите сертификат 30DaysOfJavaScript. Присоединяйтесь к [группе телеграмм](https://t.me/ThirtyDaysOfJavaScript). - -**Задача 30DaysOfJavaScript** - руководство для начинающих и опытных разработчиков JavaScript. Добро пожаловать в JavaScript. Мне нравится использовать и преподавать JavaScript, и я надеюсь, что вы это сделаете. JavaScript - это язык браузера. - -В этом пошаговом руководстве вы изучите JavaScript, самый популярный язык программирования в истории человечества. -Вы используете JavaScript **_для добавления интерактивности на веб-сайты, для разработки мобильных приложений, настольных приложений, игр_**, и в настоящее время JavaScript можно использовать для **_машинного обучения_** и **_AI_**. -**_JavaScript (JS)_** вырос в популярности в последние годы и был ведущим языком программирования в течение четырех лет подряд и является наиболее используемым языком программирования на Github. - -## Требования - -Для выполнения этой задачи не требуется предварительное знание программирования. Вам нужно только: - -1. Мотивация -2. Компьютер -3. Интернет -4. Браузер -5. Редактор кода - -## Настройка - -Я считаю, что у вас есть мотивация и сильное желание быть разработчиком, компьютер и Интернет. Если у вас есть это, то у вас есть всё =). - -### Установка Node.js - -Возможно, вам это не нужно прямо сейчас, но может понадобиться позже. Устанавить [node.js](https://nodejs.org/en/). - -![Node download](images/download_node.png) - -После загрузки дважды щелкните и установите - -![Install node](images/install_node.png) - -Мы можем проверить, установлен ли узел на нашем локальном компьютере, открыв терминал устройства или командную строку. - -```sh -asabeneh $ node -v -v12.14.0 -``` - -Я использую версию node 12.14.0, которая является рекомендуемой версией узла. - -### Браузер - -Есть много браузеров там. Тем не менее, я настоятельно рекомендую Google Chrome. - -#### Установка Google Chrome - -Установите [google chrome](https://www.google.com/chrome/), если у вас его еще нет. Мы можем написать небольшой код JavaScript в консоли браузера, но мы не используем консоль браузера для разработки приложений. - -![Google Chrome](images/google_chrome.png) - -#### Открытие Google Chrome Console - -Вы можете открыть Google Chrome, нажав три точки в верхнем правом углу браузера Chrome или воспользовавшись ярлыком. Я предпочитаю использовать ярлыки. - -![Opening chrome](images/opening_developer_tool.png) - -Чтобы открыть консоль Chrome с помощью горячих клавиш. - -```sh -Mac -Command+Option+I - -Windows: -Ctl+Shift+I -``` - -![Opening console](images/opening_chrome_console_shortcut.png) - -После того, как вы откроете консоль Google Chrome, попробуйте изучить отмеченные кнопки. Мы будем проводить большую часть времени на консоли. Консоль - это место, куда идет ваш код JavaScript. Движок Google Console V8 изменяет ваш код JavaScript на машинный код. -Давайте напишем код JavaScript на консоли Google Chrome: - -![write code on console](./images/js_code_on_chrome_console.png) - -#### Написание кода на консоли браузера - -Мы можем написать любой код JavaScript на консоли Google или любой консоли браузера. Однако для решения этой проблемы мы сосредоточимся только на консоли Google Chrome. Откройте консоль, используя: - -```sh -Mac -Command+Option+I - -Windows: -Ctl+Shift+I -``` - -##### Console.log - -Чтобы написать наш первый код JavaScript, мы использовали встроенную функцию `console.log()`. Мы передали аргумент в качестве входных данных, и функция отображает вывод. Мы передали 'Hello, World' в качестве входных данных или аргумента в функцию `console.log()`. - -```js -console.log("Hello, World!"); -``` - -##### Console.log with multiple arguments - -`console.log(param1, param2, param3)`, может принимать несколько аргументов. - -![console log multiple arguments](./images/console_log_multipl_arguments.png) - -```js -console.log("Hello", "World", "!"); -console.log("HAPPY", "NEW", "YEAR", 2020); -console.log("Welcome", "to", 30, "Days", "Of", "JavaScript"); -``` - -Как вы можете видеть из приведенного выше фрагмента кода, `console.log()` может принимать несколько аргументов. - -Поздравляем! Вы написали свой первый код JavaScript, используя `console.log()`. - -##### Комментарии - -Мы добавляем комментарии к нашему коду. Комментарии очень важны, чтобы сделать код более читабельным и оставить комментарии в нашем коде. JavaScript не выполняет часть комментариев нашего кода. Любой текст, начинающийся с `//` в JavaScript, является комментарием или что-то в этом роде `/* */` является комментарием. - -**Пример: Однострочный комментарий** - -```js -// Это первый комментарий -// Это второй комментарий -// Я однострочный комментарий -``` - -**Пример: Многострочный комментарий** - -```js -/* -Это многострочный комментарий -Многострочные комментарии могут занимать несколько строк -JavaScript - это язык Интернета -*/ -``` - -##### Синтаксис - -JavaScript это язык программирования. В результате он имеет свой синтаксис, как и другие языки программирования. Если мы не напишем синтаксис, понятный JavaScript, это вызовет различные типы ошибок. Мы рассмотрим различные виды ошибок JavaScript позже. А пока давайте посмотрим на синтаксические ошибки. - -![Error](images/raising_syntax_error.png) - -Я сделал преднамеренную ошибку. В результате консоль вызывает синтаксическую ошибку. На самом деле, синтаксис очень информативен. Он сообщает, какую ошибку мы допустили. Прочитав руководство по обратной связи об ошибках, мы можем исправить синтаксис и устранить проблему. Процесс выявления и удаления ошибок из программы называется отладкой. Давайте исправим ошибки: - -```js -console.log("Hello, World!"); -console.log("Hello, World!"); -``` - -До сих пор мы видели, как отображать текст с помощью `console.log()`. Если мы печатаем текст или строку с помощью `console.log()`, текст должен находиться в одинарных, двойных или обратных кавычках. -**Пример:** - -```js -console.log("Hello, World!"); -console.log("Hello, World!"); -console.log(`Hello, World!`); -``` - -#### Арифметика - -Теперь давайте попрактикуемся в написании кодов JavaScript с помощью `console.log()` в консоли Google Chrome для числовых типов данных. -В дополнение к тексту мы также можем выполнять математические вычисления с использованием JavaScript. Давайте сделаем следующие простые вычисления. - -![Arithmetic](images/arithmetic.png) - -```js -console.log(2 + 3); // Сложение -console.log(3 - 2); // Вычитание -console.log(2 * 3); // Умножение -console.log(3 / 2); // Разделение -console.log(3 % 2); // Модуль - поиск остатка -console.log(3 ** 2); // Экспоненциальный -``` - -### Редактор кода - -Мы можем написать наш код в консоли браузера, но это не будет работать для больших проектов. В реальной рабочей среде разработчики используют разные редакторы кода для написания своих кодов. В этом 30-дневном челендже JavaScript мы будем использовать визуальный Visual Studio Code. - -#### Установка Visual Studio Code - -VS Code - это очень популярный текстовый редактор с открытым исходным кодом. Я бы рекомендовал [скачать](https://code.visualstudio.com/) VS Code, но если вы поддерживаете другие редакторы, не стесняйтесь использовать то, что у вас есть. - -![Vscode](images/vscode.png) - -Если вы установили код VS Code, давайте начнем использовать его. - -#### Как использовать VS Code - -Откройте код VS Code, дважды щелкнув значок VS Code. Когда вы откроете его, вы получите такой интерфейс. Попробуйте взаимодействовать с помеченными значками. - -![Vscode ui](./images/vscode_ui.png) - -![Vscode add project](./images/adding_project_to_vscode.png) - -![Vscode open project](./images/opening_project_on_vscode.png) - -![script file](images/scripts_on_vscode.png) - -![running script](./images/running_script.png) - -![coding running](./images/launched_on_new_tab.png) - -## Добавление JavaScript на веб-страницу - -JavaScript можно добавить на веб-страницу тремя различными способами: - -- **_Встроенный скрипт_** -- **_Внутренний скрипт_** -- **_Внешний скрипт_** -- **_Несколько внешних скриптов_** - -В следующих разделах показаны различные способы добавления кода JavaScript на вашу веб-страницу. - -### Встроенный скрипт - -Создайте папку на рабочем столе и назовите ее `30DaysOfJS` или в любом месте и создайте файл **_index.html_** в папке проекта. Затем вставьте следующий код и откройте его в браузере, либо в [Chrome](https://www.google.com/chrome/). - -```html - - - - 30DaysOfScript: Встроенный скрипт - - - - - -``` - -Теперь вы написали свой первый встроенный скрипт. Мы можем создать всплывающее сообщение с предупреждением, используя встроенную функцию `alert()`. - -### Внутренний скрипт - -Внутренний скрипт может быть записан в `head` или `body`, но предпочтительно поместить его в `body` HTML-документа. -Во-первых, давайте напишем в верхней части страницы. - -```html - - - - 30DaysOfScript: Внутренний скрипт - - - - -``` - -Так мы пишем внутренний скрипт большую часть времени. Написание кода JavaScript в разделе `body` является наиболее предпочтительным местом. Откройте консоль браузера, чтобы увидеть вывод `console.log()` - -```html - - - - 30DaysOfScript: Внутренний скрипт - - - - - - -``` - -Откройте консоль браузера, чтобы увидеть вывод `console.log()` - -![js code from vscode](./images/js_code_vscode.png) - -### Внешний скрипт - -Подобно внутреннему сценарию, ссылка на внешний сценарий может быть в `head` или `body`, но предпочтительно помещать ее в `body`. -Во-первых, мы должны создать внешний файл JavaScript с расширением `.js`. Любой файл JavaScript заканчивается на `.js`. Создайте файл `introduction.js` внутри директории вашего проекта, напишите следующий код и подключите этот файл `.js` внизу `body`. - -```js -console.log("Добро пожаловать на 30 дней JavaScript"); -``` - -Внешние скрипты в head - -```html - - - - 30DaysOfJavaScript: Внешний скрипт - - - - -``` - -Внешние скрипты в body - -```html - - - - 30DaysOfJavaScript:External script - - - - - - -``` - -Откройте консоль браузера, чтобы увидеть вывод `console.log()`. - -### Несколько внешних скриптов - -Мы можем связать несколько внешних файлов JavaScript с веб-страницей. -Создайте файл _helloworld.js_ в папке 30DaysOfJS и напишите следующий код. - -```js -console.log("Hello, World!"); -``` - -```html - - - - Multiple External Scripts - - - - - - -``` - -Ваш файл main.js должен быть ниже всех других скриптов. Будьте внимательными, чтобы понять эту строчку. - -![Multiple Script](./images/multiple_script.png) - -## Введение в типы данных - -В JavaScript, а также в других языках программирования существуют разные типы типов данных. Ниже приведены примитивные типы данных JavaScript: _Строка, Число, Булевый (логический) тип, undefined, Null_ и _Symbol_. - -### Число - -- Integer: Целые (отрицательные, нулевые и положительные) числа - Пример: - ... -3, -2, -1, 0, 1, 2, 3 ... -- Float: десятичное число - Пример: - ... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ... - -### Строка - -Строка (string) в JavaScript должна быть заключена в кавычки (одинарных, двойных или обратных кавычках). - -#### Пример - -```js -"Asabeneh"; -"Finland"; -"JavaScript is a beautiful programming language"; -"I love teaching"; -"I hope you are enjoying the first day"`We can also create a string using a backtick`; -``` - -### Булевый (логический) тип «boolean» - -Логическое значение может быть истинным или ложным. Любые сравнения возвращают логическое значение, которое является истинным или ложным. - -Логический тип данных является либо Истинным, либо Ложным значением. - -#### Пример - -```js -true; // если свет включен, значение истинно -false; // если свет выключен, значение False -``` - -### Undefined - -В JavaScript, если мы не присваиваем значение переменной, значение не определено. В дополнение к этому, если функция ничего не возвращает, она возвращает undefined. - -```js -let firstName; -console.log(firstName); // не определено, потому что оно еще не присвоено значению -``` - -### Null - -Null в JavaScript означает пустое значение. - -```js -let emptyValue = null; -``` - -## Проверка типов данных - -Чтобы проверить тип данных определенного типа данных, мы используем оператор `typeof`. Смотрите следующий пример. - -```js -console.log(typeof "Asabeneh"); // строка -console.log(typeof 5); // число -console.log(typeof true); // булевое значение -console.log(typeof null); // объект -console.log(typeof undefined); // undefined -``` - -## Комментарии - -Комментирование в JavaScript похоже на другие языки программирования. Комментарии важны для того, чтобы сделать ваш код более читабельным. - -Есть два способа комментирования: - -- _Однострочные комментарии_ -- _Многострочное комментирование_ - -```js -// комментирование самого кода одним комментарием -// let firstName = 'Asabeneh'; однострочный комментарий -// let lastName = 'Yetayeh'; однострочный комментарий -``` - -Многострочное комментирование: - -```js -/* - let location = 'Helsinki'; - let age = 100; - let isMarried = true; - This is a Multiple line comment -*/ -``` - -## Переменные - -Переменные являются _контейнером_ данных. Переменные, используются для хранения данных в ячейке памяти. Когда переменная объявлена, место в памяти зарезервировано. Когда переменной присваивается значение (данные), пространство памяти будет заполнено этими данными. Чтобы объявить переменную, мы используем ключевые слова `var`, `let` или `const`. Мы поговорим подробнее о `var`, `let` и `const` в других разделах (область действия). Пока приведенного выше объяснения достаточно. - -Для переменной, которая изменяется в другое время, мы используем `let`. Если данные не меняются вообще, мы используем `const`. Например, PI, название страны, гравитация не меняются, и мы можем использовать `const`. - -- Имя переменной JavaScript не должно начинаться с цифры. -- Имя переменной JavaScript не допускает специальных символов, кроме знака доллара и подчеркивания. -- Имя переменной JavaScript следует соглашению camelCase. -- Имя переменной JavaScript не должно содержать пробелов между словами. - -Ниже приведены допустимые примеры переменных JavaScript. - -Допустимые переменные в JavaScript: - -```js -firstName; -lastName; -country; -city; -capitalCity; -age; -isMarried; - -first_name; -last_name; -is_marreid; -capital_city; - -num1; -num_1; -_num_1; -$num1; -year2020; -year_2020; -``` - -camelCase или первый способ декларирования обычно используются в JavaScript. В этом материале мы будем использовать переменные camelCase. - -Неверное название переменных: - -```sh -first-name -1_num -num_#_1 -``` - -Давайте объявим переменные с разными типами данных. Чтобы объявить переменную, нам нужно использовать ключевое слово let или const перед именем переменной. После имени переменной мы пишем знак равенства (оператор присваивания) и значение. - -```js -// Синтаксис -let nameOfVariable = value; -``` - -### Примеры: Переменные - -```js -// Объявление разных переменных разных типов данных -let firstName = "Asabeneh"; // имя человека -let lastName = "Yetayeh"; // фамилия человека -let country = "Finland"; // страна -let city = "Helsinki"; // столица -let age = 100; // возраст в годах -let isMarried = true; - -console.log(firstName, lastName, country, city, age, isMarried); -``` - -```sh -Asabeneh Yetayeh Finland Helsinki 100 True -``` - -```js -// Объявление переменных с числовыми значениями -let age = 100; // возраст в годах -const gravity = 9.81; // сила тяжести на землю в м/с2 -const boilingPoint = 100; // температура кипения воды, температура в oC -const PI = 3.14; // геометрическая постоянная - -console.log(gravity, boilingPoint, PI); -``` - -```sh -9.81 100 3.14 -``` - -```js -// Переменные также могут быть объявлены в одну строку через запятую -let name = "Asabeneh", // Имя человека - job = "teacher", - live = "Finland"; -console.log(name, job, live); -``` - -```sh -Asabeneh teacher Finland -``` - -Когда вы запускаете файлы в папке 01-Day, вы должны получить это: - -![Day one](./images/day_1.png) - -🌕 Ты великолепен. Вы только что выполнили задание первого дня, и вы на пути к величию. Теперь сделайте несколько упражнений для вашего мозга и ваших мышц. - -# 💻 День 1: Упражнения - -1. Написать однострочный комментарий, который говорит: _comments can make code readable_ -2. Написать еще один комментарий, который говорит: _welcome to 30DaysOfJavaScript_ -3. Написать многострочный комментарий, который говорит: _comments can make code readable, easy to use and informative_ -4. Создать файл _variable.js_, объявить переменные и назначить строковые, логические, undefined и null типы данных. -5. Создайте файл _datatypes.js_ и используйте оператор JavaScript `typeof` для проверки различных типов данных. Проверьте тип данных каждой переменной -6. Объявите четыре переменные без присвоения значений -7. Объявите четыре переменные с присвоением значений -8. Объявите переменные для хранения вашего имени, фамилии, семейного положения, страны и возраста в несколько строк -9. Объявите переменные, чтобы хранить ваши имя, фамилию, семейное положение, страну и возраст в одной строке -10. Объявите две переменные _myAge_ и _yourAge_, присвойте им начальные значения и войдите в консоль браузера. - -```sh -I am 25 years old. -You are 30 years old. -``` - -🎉 ПОЗДРАВЛЯЕМ ! 🎉 - -[День 2 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/RU/02_Day/02_day_data_types.md) diff --git a/RU/data/countries.js b/RU/data/countries.js deleted file mode 100644 index e57b005..0000000 --- a/RU/data/countries.js +++ /dev/null @@ -1,195 +0,0 @@ -const countries = [ - 'Afghanistan', - 'Albania', - 'Algeria', - 'Andorra', - 'Angola', - 'Antigua and Barbuda', - 'Argentina', - 'Armenia', - 'Australia', - 'Austria', - 'Azerbaijan', - 'Bahamas', - 'Bahrain', - 'Bangladesh', - 'Barbados', - 'Belarus', - 'Belgium', - 'Belize', - 'Benin', - 'Bhutan', - 'Bolivia', - 'Bosnia and Herzegovina', - 'Botswana', - 'Brazil', - 'Brunei', - 'Bulgaria', - 'Burkina Faso', - 'Burundi', - 'Cambodia', - 'Cameroon', - 'Canada', - 'Cape Verde', - 'Central African Republic', - 'Chad', - 'Chile', - 'China', - 'Colombi', - 'Comoros', - 'Congo (Brazzaville)', - 'Congo', - 'Costa Rica', - "Cote d'Ivoire", - 'Croatia', - 'Cuba', - 'Cyprus', - 'Czech Republic', - 'Denmark', - 'Djibouti', - 'Dominica', - 'Dominican Republic', - 'East Timor (Timor Timur)', - 'Ecuador', - 'Egypt', - 'El Salvador', - 'Equatorial Guinea', - 'Eritrea', - 'Estonia', - 'Ethiopia', - 'Fiji', - 'Finland', - 'France', - 'Gabon', - 'Gambia, The', - 'Georgia', - 'Germany', - 'Ghana', - 'Greece', - 'Grenada', - 'Guatemala', - 'Guinea', - 'Guinea-Bissau', - 'Guyana', - 'Haiti', - 'Honduras', - 'Hungary', - 'Iceland', - 'India', - 'Indonesia', - 'Iran', - 'Iraq', - 'Ireland', - 'Israel', - 'Italy', - 'Jamaica', - 'Japan', - 'Jordan', - 'Kazakhstan', - 'Kenya', - 'Kiribati', - 'Korea, North', - 'Korea, South', - 'Kuwait', - 'Kyrgyzstan', - 'Laos', - 'Latvia', - 'Lebanon', - 'Lesotho', - 'Liberia', - 'Libya', - 'Liechtenstein', - 'Lithuania', - 'Luxembourg', - 'Macedonia', - 'Madagascar', - 'Malawi', - 'Malaysia', - 'Maldives', - 'Mali', - 'Malta', - 'Marshall Islands', - 'Mauritania', - 'Mauritius', - 'Mexico', - 'Micronesia', - 'Moldova', - 'Monaco', - 'Mongolia', - 'Morocco', - 'Mozambique', - 'Myanmar', - 'Namibia', - 'Nauru', - 'Nepal', - 'Netherlands', - 'New Zealand', - 'Nicaragua', - 'Niger', - 'Nigeria', - 'Norway', - 'Oman', - 'Pakistan', - 'Palau', - 'Panama', - 'Papua New Guinea', - 'Paraguay', - 'Peru', - 'Philippines', - 'Poland', - 'Portugal', - 'Qatar', - 'Romania', - 'Russia', - 'Rwanda', - 'Saint Kitts and Nevis', - 'Saint Lucia', - 'Saint Vincent', - 'Samoa', - 'San Marino', - 'Sao Tome and Principe', - 'Saudi Arabia', - 'Senegal', - 'Serbia and Montenegro', - 'Seychelles', - 'Sierra Leone', - 'Singapore', - 'Slovakia', - 'Slovenia', - 'Solomon Islands', - 'Somalia', - 'South Africa', - 'Spain', - 'Sri Lanka', - 'Sudan', - 'Suriname', - 'Swaziland', - 'Sweden', - 'Switzerland', - 'Syria', - 'Taiwan', - 'Tajikistan', - 'Tanzania', - 'Thailand', - 'Togo', - 'Tonga', - 'Trinidad and Tobago', - 'Tunisia', - 'Turkey', - 'Turkmenistan', - 'Tuvalu', - 'Uganda', - 'Ukraine', - 'United Arab Emirates', - 'United Kingdom', - 'United States', - 'Uruguay', - 'Uzbekistan', - 'Vanuatu', - 'Vatican City', - 'Venezuela', - 'Vietnam', - 'Yemen', - 'Zambia', - 'Zimbabwe' -] diff --git a/RU/images/30DaysOfJavaScript.png b/RU/images/30DaysOfJavaScript.png deleted file mode 100644 index 4142286..0000000 Binary files a/RU/images/30DaysOfJavaScript.png and /dev/null differ diff --git a/RU/images/adding_project_to_vscode.png b/RU/images/adding_project_to_vscode.png deleted file mode 100644 index 1935860..0000000 Binary files a/RU/images/adding_project_to_vscode.png and /dev/null differ diff --git a/RU/images/arithmetic.png b/RU/images/arithmetic.png deleted file mode 100644 index 9830916..0000000 Binary files a/RU/images/arithmetic.png and /dev/null differ diff --git a/RU/images/array_index.png b/RU/images/array_index.png deleted file mode 100644 index 355324e..0000000 Binary files a/RU/images/array_index.png and /dev/null differ diff --git a/RU/images/assignment_operators.png b/RU/images/assignment_operators.png deleted file mode 100644 index 99d51d2..0000000 Binary files a/RU/images/assignment_operators.png and /dev/null differ diff --git a/RU/images/banners/Day -1 – 31.png b/RU/images/banners/Day -1 – 31.png deleted file mode 100644 index d9a9639..0000000 Binary files a/RU/images/banners/Day -1 – 31.png and /dev/null differ diff --git a/RU/images/banners/day_1_1.png b/RU/images/banners/day_1_1.png deleted file mode 100644 index dd583c7..0000000 Binary files a/RU/images/banners/day_1_1.png and /dev/null differ diff --git a/RU/images/banners/day_1_10.png b/RU/images/banners/day_1_10.png deleted file mode 100644 index e063dec..0000000 Binary files a/RU/images/banners/day_1_10.png and /dev/null differ diff --git a/RU/images/banners/day_1_11.png b/RU/images/banners/day_1_11.png deleted file mode 100644 index 0c2d60b..0000000 Binary files a/RU/images/banners/day_1_11.png and /dev/null differ diff --git a/RU/images/banners/day_1_12.png b/RU/images/banners/day_1_12.png deleted file mode 100644 index 232ac85..0000000 Binary files a/RU/images/banners/day_1_12.png and /dev/null differ diff --git a/RU/images/banners/day_1_13.png b/RU/images/banners/day_1_13.png deleted file mode 100644 index 488f522..0000000 Binary files a/RU/images/banners/day_1_13.png and /dev/null differ diff --git a/RU/images/banners/day_1_14.png b/RU/images/banners/day_1_14.png deleted file mode 100644 index 4c5a568..0000000 Binary files a/RU/images/banners/day_1_14.png and /dev/null differ diff --git a/RU/images/banners/day_1_15.png b/RU/images/banners/day_1_15.png deleted file mode 100644 index e3013f6..0000000 Binary files a/RU/images/banners/day_1_15.png and /dev/null differ diff --git a/RU/images/banners/day_1_16.png b/RU/images/banners/day_1_16.png deleted file mode 100644 index d116060..0000000 Binary files a/RU/images/banners/day_1_16.png and /dev/null differ diff --git a/RU/images/banners/day_1_17.png b/RU/images/banners/day_1_17.png deleted file mode 100644 index 69cf7ae..0000000 Binary files a/RU/images/banners/day_1_17.png and /dev/null differ diff --git a/RU/images/banners/day_1_18.png b/RU/images/banners/day_1_18.png deleted file mode 100644 index 8b69340..0000000 Binary files a/RU/images/banners/day_1_18.png and /dev/null differ diff --git a/RU/images/banners/day_1_19.png b/RU/images/banners/day_1_19.png deleted file mode 100644 index 2a785c9..0000000 Binary files a/RU/images/banners/day_1_19.png and /dev/null differ diff --git a/RU/images/banners/day_1_2.png b/RU/images/banners/day_1_2.png deleted file mode 100644 index 0f6eefb..0000000 Binary files a/RU/images/banners/day_1_2.png and /dev/null differ diff --git a/RU/images/banners/day_1_20.png b/RU/images/banners/day_1_20.png deleted file mode 100644 index befe1fc..0000000 Binary files a/RU/images/banners/day_1_20.png and /dev/null differ diff --git a/RU/images/banners/day_1_21.png b/RU/images/banners/day_1_21.png deleted file mode 100644 index 634d1eb..0000000 Binary files a/RU/images/banners/day_1_21.png and /dev/null differ diff --git a/RU/images/banners/day_1_22.png b/RU/images/banners/day_1_22.png deleted file mode 100644 index 81e33d9..0000000 Binary files a/RU/images/banners/day_1_22.png and /dev/null differ diff --git a/RU/images/banners/day_1_23.png b/RU/images/banners/day_1_23.png deleted file mode 100644 index ceb0321..0000000 Binary files a/RU/images/banners/day_1_23.png and /dev/null differ diff --git a/RU/images/banners/day_1_24.png b/RU/images/banners/day_1_24.png deleted file mode 100644 index 9c8ec46..0000000 Binary files a/RU/images/banners/day_1_24.png and /dev/null differ diff --git a/RU/images/banners/day_1_25.png b/RU/images/banners/day_1_25.png deleted file mode 100644 index 60a211e..0000000 Binary files a/RU/images/banners/day_1_25.png and /dev/null differ diff --git a/RU/images/banners/day_1_26.png b/RU/images/banners/day_1_26.png deleted file mode 100644 index f187f2c..0000000 Binary files a/RU/images/banners/day_1_26.png and /dev/null differ diff --git a/RU/images/banners/day_1_27.png b/RU/images/banners/day_1_27.png deleted file mode 100644 index 8637069..0000000 Binary files a/RU/images/banners/day_1_27.png and /dev/null differ diff --git a/RU/images/banners/day_1_28.png b/RU/images/banners/day_1_28.png deleted file mode 100644 index 1858aca..0000000 Binary files a/RU/images/banners/day_1_28.png and /dev/null differ diff --git a/RU/images/banners/day_1_29.png b/RU/images/banners/day_1_29.png deleted file mode 100644 index 959ee36..0000000 Binary files a/RU/images/banners/day_1_29.png and /dev/null differ diff --git a/RU/images/banners/day_1_3.png b/RU/images/banners/day_1_3.png deleted file mode 100644 index 1268d2c..0000000 Binary files a/RU/images/banners/day_1_3.png and /dev/null differ diff --git a/RU/images/banners/day_1_30.png b/RU/images/banners/day_1_30.png deleted file mode 100644 index 18a77c4..0000000 Binary files a/RU/images/banners/day_1_30.png and /dev/null differ diff --git a/RU/images/banners/day_1_4.png b/RU/images/banners/day_1_4.png deleted file mode 100644 index d5262c6..0000000 Binary files a/RU/images/banners/day_1_4.png and /dev/null differ diff --git a/RU/images/banners/day_1_5.png b/RU/images/banners/day_1_5.png deleted file mode 100644 index 21bc08c..0000000 Binary files a/RU/images/banners/day_1_5.png and /dev/null differ diff --git a/RU/images/banners/day_1_6.png b/RU/images/banners/day_1_6.png deleted file mode 100644 index dbea5fd..0000000 Binary files a/RU/images/banners/day_1_6.png and /dev/null differ diff --git a/RU/images/banners/day_1_7.png b/RU/images/banners/day_1_7.png deleted file mode 100644 index eff8dac..0000000 Binary files a/RU/images/banners/day_1_7.png and /dev/null differ diff --git a/RU/images/banners/day_1_8.png b/RU/images/banners/day_1_8.png deleted file mode 100644 index ddf9007..0000000 Binary files a/RU/images/banners/day_1_8.png and /dev/null differ diff --git a/RU/images/banners/day_1_9.png b/RU/images/banners/day_1_9.png deleted file mode 100644 index 1cf688b..0000000 Binary files a/RU/images/banners/day_1_9.png and /dev/null differ diff --git a/RU/images/comparison_operators.png b/RU/images/comparison_operators.png deleted file mode 100644 index 26ccb91..0000000 Binary files a/RU/images/comparison_operators.png and /dev/null differ diff --git a/RU/images/console_log_multipl_arguments.png b/RU/images/console_log_multipl_arguments.png deleted file mode 100644 index f324a90..0000000 Binary files a/RU/images/console_log_multipl_arguments.png and /dev/null differ diff --git a/RU/images/date_time_object.png b/RU/images/date_time_object.png deleted file mode 100644 index c5297c7..0000000 Binary files a/RU/images/date_time_object.png and /dev/null differ diff --git a/RU/images/day_1.png b/RU/images/day_1.png deleted file mode 100644 index 7daf57f..0000000 Binary files a/RU/images/day_1.png and /dev/null differ diff --git a/RU/images/day_1_1.png b/RU/images/day_1_1.png deleted file mode 100644 index dd583c7..0000000 Binary files a/RU/images/day_1_1.png and /dev/null differ diff --git a/RU/images/download_node.png b/RU/images/download_node.png deleted file mode 100644 index f290b20..0000000 Binary files a/RU/images/download_node.png and /dev/null differ diff --git a/RU/images/google_chrome.png b/RU/images/google_chrome.png deleted file mode 100644 index af06acd..0000000 Binary files a/RU/images/google_chrome.png and /dev/null differ diff --git a/RU/images/install_node.png b/RU/images/install_node.png deleted file mode 100644 index e5aecf1..0000000 Binary files a/RU/images/install_node.png and /dev/null differ diff --git a/RU/images/js_code_on_chrome_console.png b/RU/images/js_code_on_chrome_console.png deleted file mode 100644 index 7d6002c..0000000 Binary files a/RU/images/js_code_on_chrome_console.png and /dev/null differ diff --git a/RU/images/js_code_vscode.png b/RU/images/js_code_vscode.png deleted file mode 100644 index 6e1a661..0000000 Binary files a/RU/images/js_code_vscode.png and /dev/null differ diff --git a/RU/images/launched_on_new_tab.png b/RU/images/launched_on_new_tab.png deleted file mode 100644 index ed377dc..0000000 Binary files a/RU/images/launched_on_new_tab.png and /dev/null differ diff --git a/RU/images/local_storage.png b/RU/images/local_storage.png deleted file mode 100644 index 0876852..0000000 Binary files a/RU/images/local_storage.png and /dev/null differ diff --git a/RU/images/multiple_script.png b/RU/images/multiple_script.png deleted file mode 100644 index caa067f..0000000 Binary files a/RU/images/multiple_script.png and /dev/null differ diff --git a/RU/images/opening_chrome_console_shortcut.png b/RU/images/opening_chrome_console_shortcut.png deleted file mode 100644 index eace03f..0000000 Binary files a/RU/images/opening_chrome_console_shortcut.png and /dev/null differ diff --git a/RU/images/opening_developer_tool.png b/RU/images/opening_developer_tool.png deleted file mode 100644 index 6eb33dd..0000000 Binary files a/RU/images/opening_developer_tool.png and /dev/null differ diff --git a/RU/images/opening_project_on_vscode.png b/RU/images/opening_project_on_vscode.png deleted file mode 100644 index 908c8fd..0000000 Binary files a/RU/images/opening_project_on_vscode.png and /dev/null differ diff --git a/RU/images/projects/congratulations.gif b/RU/images/projects/congratulations.gif deleted file mode 100644 index cddd6c4..0000000 Binary files a/RU/images/projects/congratulations.gif and /dev/null differ diff --git a/RU/images/projects/dom_min_project_30DaysOfJavaScript_color_changing_day_9.1.gif b/RU/images/projects/dom_min_project_30DaysOfJavaScript_color_changing_day_9.1.gif deleted file mode 100644 index c8d2f2b..0000000 Binary files a/RU/images/projects/dom_min_project_30DaysOfJavaScript_color_changing_day_9.1.gif and /dev/null differ diff --git a/RU/images/projects/dom_min_project_bar_graph_day_5.1.gif b/RU/images/projects/dom_min_project_bar_graph_day_5.1.gif deleted file mode 100644 index a7d7962..0000000 Binary files a/RU/images/projects/dom_min_project_bar_graph_day_5.1.gif and /dev/null differ diff --git a/RU/images/projects/dom_min_project_bar_graph_day_5.1.png b/RU/images/projects/dom_min_project_bar_graph_day_5.1.png deleted file mode 100644 index 0b6ccf7..0000000 Binary files a/RU/images/projects/dom_min_project_bar_graph_day_5.1.png and /dev/null differ diff --git a/RU/images/projects/dom_min_project_challenge_info_day_1.1.gif b/RU/images/projects/dom_min_project_challenge_info_day_1.1.gif deleted file mode 100644 index 0551771..0000000 Binary files a/RU/images/projects/dom_min_project_challenge_info_day_1.1.gif and /dev/null differ diff --git a/RU/images/projects/dom_min_project_challenge_info_day_1.1.png b/RU/images/projects/dom_min_project_challenge_info_day_1.1.png deleted file mode 100644 index 01a8d4f..0000000 Binary files a/RU/images/projects/dom_min_project_challenge_info_day_1.1.png and /dev/null differ diff --git a/RU/images/projects/dom_min_project_countries_aray_day_2.2.png b/RU/images/projects/dom_min_project_countries_aray_day_2.2.png deleted file mode 100644 index ca0e344..0000000 Binary files a/RU/images/projects/dom_min_project_countries_aray_day_2.2.png and /dev/null differ diff --git a/RU/images/projects/dom_min_project_day_7.1.gif b/RU/images/projects/dom_min_project_day_7.1.gif deleted file mode 100644 index 51bdadb..0000000 Binary files a/RU/images/projects/dom_min_project_day_7.1.gif and /dev/null differ diff --git a/RU/images/projects/dom_min_project_day_number_generators_2.1.png b/RU/images/projects/dom_min_project_day_number_generators_2.1.png deleted file mode 100644 index d69a6c2..0000000 Binary files a/RU/images/projects/dom_min_project_day_number_generators_2.1.png and /dev/null differ diff --git a/RU/images/projects/dom_min_project_keycode_day_3.2.gif b/RU/images/projects/dom_min_project_keycode_day_3.2.gif deleted file mode 100644 index 7c75c14..0000000 Binary files a/RU/images/projects/dom_min_project_keycode_day_3.2.gif and /dev/null differ diff --git a/RU/images/projects/dom_min_project_number_generator_day_3.1.gif b/RU/images/projects/dom_min_project_number_generator_day_3.1.gif deleted file mode 100644 index 59a8dd0..0000000 Binary files a/RU/images/projects/dom_min_project_number_generator_day_3.1.gif and /dev/null differ diff --git a/RU/images/projects/dom_min_project_solar_system_day_4.1.gif b/RU/images/projects/dom_min_project_solar_system_day_4.1.gif deleted file mode 100644 index d88b04b..0000000 Binary files a/RU/images/projects/dom_min_project_solar_system_day_4.1.gif and /dev/null differ diff --git a/RU/images/projects/dom_min_project_solar_system_day_4.1.mkv b/RU/images/projects/dom_min_project_solar_system_day_4.1.mkv deleted file mode 100644 index 1ed941c..0000000 Binary files a/RU/images/projects/dom_min_project_solar_system_day_4.1.mkv and /dev/null differ diff --git a/RU/images/projects/dom_min_project_solar_system_day_4.1.mp4 b/RU/images/projects/dom_min_project_solar_system_day_4.1.mp4 deleted file mode 100644 index 69ce936..0000000 Binary files a/RU/images/projects/dom_min_project_solar_system_day_4.1.mp4 and /dev/null differ diff --git a/RU/images/projects/dom_mini_project_challenge_info_day_2.3.gif b/RU/images/projects/dom_mini_project_challenge_info_day_2.3.gif deleted file mode 100644 index 571ea6f..0000000 Binary files a/RU/images/projects/dom_mini_project_challenge_info_day_2.3.gif and /dev/null differ diff --git a/RU/images/projects/dom_mini_project_challenge_info_day_2.3.png b/RU/images/projects/dom_mini_project_challenge_info_day_2.3.png deleted file mode 100644 index 3387bea..0000000 Binary files a/RU/images/projects/dom_mini_project_challenge_info_day_2.3.png and /dev/null differ diff --git a/RU/images/projects/dom_mini_project_countries_day_6.1.gif b/RU/images/projects/dom_mini_project_countries_day_6.1.gif deleted file mode 100644 index 8a8f09a..0000000 Binary files a/RU/images/projects/dom_mini_project_countries_day_6.1.gif and /dev/null differ diff --git a/RU/images/projects/dom_mini_project_countries_object_day_10.1.gif b/RU/images/projects/dom_mini_project_countries_object_day_10.1.gif deleted file mode 100644 index 03b1e35..0000000 Binary files a/RU/images/projects/dom_mini_project_countries_object_day_10.1.gif and /dev/null differ diff --git a/RU/images/projects/dom_mini_project_form_validation_day_10.2.1.png b/RU/images/projects/dom_mini_project_form_validation_day_10.2.1.png deleted file mode 100644 index 9d2c2b3..0000000 Binary files a/RU/images/projects/dom_mini_project_form_validation_day_10.2.1.png and /dev/null differ diff --git a/RU/images/projects/dom_mini_project_form_validation_day_10.2.png b/RU/images/projects/dom_mini_project_form_validation_day_10.2.png deleted file mode 100644 index ca7cdd5..0000000 Binary files a/RU/images/projects/dom_mini_project_form_validation_day_10.2.png and /dev/null differ diff --git a/RU/images/projects/dom_mini_project_leaderboard_day_8.1.gif b/RU/images/projects/dom_mini_project_leaderboard_day_8.1.gif deleted file mode 100644 index 789d0cb..0000000 Binary files a/RU/images/projects/dom_mini_project_leaderboard_day_8.1.gif and /dev/null differ diff --git a/RU/images/projects/dom_mini_project_leaderboard_day_8.1.png b/RU/images/projects/dom_mini_project_leaderboard_day_8.1.png deleted file mode 100644 index 2956fa0..0000000 Binary files a/RU/images/projects/dom_mini_project_leaderboard_day_8.1.png and /dev/null differ diff --git a/RU/images/projects/dom_mini_project_slider_day_7.1.gif b/RU/images/projects/dom_mini_project_slider_day_7.1.gif deleted file mode 100644 index 51bdadb..0000000 Binary files a/RU/images/projects/dom_mini_project_slider_day_7.1.gif and /dev/null differ diff --git a/RU/images/raising_syntax_error.png b/RU/images/raising_syntax_error.png deleted file mode 100644 index 81f6245..0000000 Binary files a/RU/images/raising_syntax_error.png and /dev/null differ diff --git a/RU/images/regex.png b/RU/images/regex.png deleted file mode 100644 index c7116b4..0000000 Binary files a/RU/images/regex.png and /dev/null differ diff --git a/RU/images/running_script.png b/RU/images/running_script.png deleted file mode 100644 index deac13d..0000000 Binary files a/RU/images/running_script.png and /dev/null differ diff --git a/RU/images/scripts_on_vscode.png b/RU/images/scripts_on_vscode.png deleted file mode 100644 index f6257be..0000000 Binary files a/RU/images/scripts_on_vscode.png and /dev/null differ diff --git a/RU/images/string_indexes.png b/RU/images/string_indexes.png deleted file mode 100644 index cc2f638..0000000 Binary files a/RU/images/string_indexes.png and /dev/null differ diff --git a/RU/images/vscode.png b/RU/images/vscode.png deleted file mode 100644 index 724fc10..0000000 Binary files a/RU/images/vscode.png and /dev/null differ diff --git a/RU/images/vscode_ui.png b/RU/images/vscode_ui.png deleted file mode 100644 index 7210a08..0000000 Binary files a/RU/images/vscode_ui.png and /dev/null differ diff --git a/RU/images/web_storage.png b/RU/images/web_storage.png deleted file mode 100644 index 46f9311..0000000 Binary files a/RU/images/web_storage.png and /dev/null differ diff --git a/RU/index.html b/RU/index.html deleted file mode 100644 index 14e41c3..0000000 --- a/RU/index.html +++ /dev/null @@ -1,128 +0,0 @@ - - - - - Document Object Model:30 Days Of JavaScript - - - - - - -
-

Asabeneh Yetayeh challenges in 2020

-

30DaysOfJavaScript Challenge

-

- -
- - - - - \ No newline at end of file diff --git a/Spanish/dia_02_tipos_de_datos.md b/Spanish/dia_02_tipos_de_datos.md deleted file mode 100644 index b867967..0000000 --- a/Spanish/dia_02_tipos_de_datos.md +++ /dev/null @@ -1,992 +0,0 @@ -
-

30 Días de JavaScript: Tipos de Datos

- - - - - Twitter Follow - - -Author: -Asabeneh Yetayeh
- January, 2020 -
- -
- - -[<< Día 1](./readme.md) | [Day 3 >>](./dia_03_Booleanos_Operadores_Date/dia_03_Boleanos_Operadores_Date.md) - -![Thirty Days Of JavaScript](../images/banners/day_1_2.png) - -- [📔 Día 2](#-Día-2) - - [Tipos de Datos](#tipos-de-datos) - - [Tipos de datos primitivos](#tipos-de-datos-primitivos) - - [Tipos de datos no primitivos](#tipos-de-datos-no-primitivos) - - [Números](#números) - - [Declaración de tipos de datos numéricos](#declaración-de-tipos-de-datos-numéricos) - - [Objeto matemático](#objeto-matemático) - - [Generador de números aleatorios](#generador-de-números-aleatorios) - - [Cadenas](#cadenas) - - [Concatenación de cadenas](#concatenación-de-cadenas) - - [Concatenar usando el operador de suma](#concatenar-usando-el-operador-de-suma) - - [Cadenas literales largas](#cadenas-literales-largas) - - [Secuencias de escape en cadenas](#secuencias-de-escape-en-cadenas) - - [Literales de plantilla](#literales-de-plantilla) - - [Métodos de cadena](#métodos-de-cadena) - - [Comprobación de tipos de datos y conversión](#comprobación-de-tipos-de-datos-y-conversión) - - [Comprobación de tipos de datos](#comprobación-de-tipos-de-datos) - - [Cambio del tipo de datos](#cambio-del-tipo-de-datos) - - [Cadena a Int](#cadena-a-int) - - [Cadena a Floatante](#cadena-a-floatante) - - [Flotante a Int](#flotante-a-int) - - [💻 Día 2: Ejercicios](#-día-2-ejercicios) - - [Ejercicio: Nivel 1](#ejercicio-nivel-1) - - [Ejercicio: Nivel 2](#ejercicio-nivel-2) - - [Ejercicios: Nivel 3](#ejercicios-nivel-3) - -# 📔 Día 2 - -## Tipos de Datos - -En la sección anterior, mencionamos un poco sobre los tipos de datos. Los datos o valores tienen tipos de datos. Los tipos de datos describen las características de los datos. Los tipos de datos se pueden dividir en dos: - -1. Tipos de datos primitivos -2. Tipos de datos que no son primitivos (referencias de objetos) - -### Tipos de datos primitivos - -Los tipos de datos primitivos en JavaScript incluyen: - -1. Números: enteros, flotantes -2. Cadenas: cualquier dato entre comillas simples, comillas dobles o comillas invertidas -3. Booleanos: valor verdadero o falso -4. Nulo - valor vacío o sin valor -5. Indefinido - una variable declarada sin un valor - -Los tipos de datos que no son primitivos en JavaScript incluyen: - -1. Objetos -2. Funciones -3. Matrices - -Ahora, veamos qué significan exactamente los tipos de datos primitivos y no primitivos. -Los tipos de datos _primitivos_ son tipos de datos inmutables (no modificables). Una vez que se crea un tipo de datos primitivo, no podemos modificarlo. - -**Ejemplo:** - -```js -let word = "JavaScript"; -``` - -Si intentamos modificar la cadena almacenada en la variable _word_, JavaScript debería generar un error. Cualquier tipo de datos bajo comillas simples, comillas dobles o comillas invertidas son un tipo de datos de cadena. - -```js -word[0] = "Y"; -``` - -Esta expresión no cambia la cadena almacenada en la variable _word_. Entonces, podemos decir que las cadenas no son modificables o, en otras palabras, inmutables. Los tipos de datos primitivos se comparan por sus valores. Comparemos diferentes valores de datos. Vea el ejemplo a continuación: - -```js -let numOne = 3; -let numTwo = 3; - -console.log(numOne == numTwo); // Verdadero - -let js = "JavaScript"; -let py = "Python"; - -console.log(js == py); // Falso - -let lightOn = true; -let lightOff = false; - -console.log(lightOn == lightOff); // Falso -``` - -### Tipos de datos no primitivos - -Los tipos de datos _no primitivos_ son modificables o mutables. Podemos modificar el valor de los tipos de datos no primitivos después de su creación. -Veamos creando una matriz. Una matriz es una lista de valores de datos entre corchetes. Las matrices pueden contener tipos de datos iguales o diferentes. Los valores de matriz están referenciados por su índice. En el índice de matriz de JavaScript comienza en cero. Es decir, el primer elemento de una matriz se encuentra en el índice cero, el segundo elemento en el índice uno y el tercer elemento en el índice dos, etc. - -```js -let nums = [1, 2, 3]; -nums[0] = 10; - -console.log(nums); // [10, 2, 3] -``` - -Como puede ver, una matriz, que es un tipo de datos no primitivo, es mutable. Los tipos de datos no primitivos no se pueden comparar por valor. Incluso si dos tipos de datos no primitivos tienen las mismas propiedades y valores, no son estrictamente iguales. - -```js -let nums = [1, 2, 3]; -let numberos = [1, 2, 3]; - -console.log(nums == numbers); // Falso - -let usuarioUno = { - nombre: "Asabeneh", - papel: "teaching", - pais: "Finland", -}; - -let usuarioDos = { - nombre: "Asabeneh", - papel: "teaching", - pais: "Finland", -}; - -console.log(usuarioUno == usuarioDos); // Falso -``` - -Como regla general, no comparamos tipos de datos no primitivos. No compare matrices, funciones u objetos. -Los valores no primitivos se conocen como tipos de referencia, porque se comparan por referencia en lugar de por valor. Dos objetos solo son estrictamente iguales si se refieren al mismo objeto subyacente. - -```js -let nums = [1, 2, 3]; -let numberos = nums; - -console.log(nums == numbers); // Verdadero - -let usuarioUno = { - nombre: "Asabeneh", - papel: "teaching", - pais: "Finland", -}; - -let userTwo = userOne; - -console.log(usuarioUno == usuarioDos); // Verdadero -``` - -Si tiene dificultades comprendiendo la diferencia entre los tipos de datos primitivos y los tipos de datos no primitivos, no es el único. Cálmate y ve a la siguiente sección e intenta volver después de un tiempo. Ahora comencemos los tipos de datos por tipo de número. - -## Números - -Los números son números enteros y valores decimales que pueden hacer todas las operaciones aritméticas. -Veamos algunos ejemplos de Números. - -### Declaración de tipos de datos numéricos - -```js -let edad = 35; -const gravedad = 9.81; // usamos const para valores que no cambian, constante gravitacional en m/s2 -let masa = 72; // masa en Kilogramo -const PI = 3.14; // pi una constante geométrica - -// Más ejemplos -const boilingPoint = 100; // temperatura en oC, punto de ebullición del agua que es una constante -const bodyTemp = 37; // oC la temperatura corporal promedio del ser humano, que es una constante - -console.log(edad, gravedad, masa, PI, boilingPoint, bodyTemp); -``` - -### Objeto matemático - -En JavaScript, el objeto matemático proporciona muchos métodos para trabajar con números. - -```js -const PI = Math.PI; - -console.log(PI); // 3.141592653589793 - -// Redondeo al número más cercano -// si es superior a 0,5 hacia arriba si es inferior a 0,5 redondeo hacia abajo - -console.log(Math.round(PI)); // 3 para redondear valores al número más cercano - -console.log(Math.round(9.81)); // 10 - -console.log(Math.floor(PI)); // 3 redondeando hacia abajo - -console.log(Math.ceil(PI)); // 4 redondeando hacia arriba - -console.log(Math.min(-5, 3, 20, 4, 5, 10)); // -5, devuelve el valor mínimo - -console.log(Math.max(-5, 3, 20, 4, 5, 10)); // 20, devuelve el valor máximo - -const randNum = Math.random(); // crea un número aleatorio entre 0 y 0,999999 -console.log(randNum); - -// Vamos a crear un número aleatorio entre 0 y 10 - -const num = Math.floor(Math.random() * 11); // crea un número aleatorio entre 0 y 10 -console.log(num); - -//Valor absoluto -console.log(Math.abs(-10)); // 10 - -//Raíz cuadrada -console.log(Math.sqrt(100)); // 10 - -console.log(Math.sqrt(2)); // 1.4142135623730951 - -// Poder -console.log(Math.pow(3, 2)); // 9 - -console.log(Math.E); // 2.718 - -// Logaritmo -// Devuelve el logaritmo natural con base E de x, Math.log(x) -console.log(Math.log(2)); // 0.6931471805599453 -console.log(Math.log(10)); // 2.302585092994046 - -// Devuelve el logaritmo natural de 2 y 10 respectivamente -console.log(Math.LN2); // 0.6931471805599453 -console.log(Math.LN10); // 2.302585092994046 - -// Trigonometría -Math.sin(0); -Math.sin(60); - -Math.cos(0); -Math.cos(60); -``` - -#### Generador de números aleatorios - -El objeto matemático de JavaScript tiene un generador de números de método random() que genera un número de 0 a 0.999999999... - -```js -let randomNum = Math.random(); // genera 0 a 0.999... -``` - -Ahora, veamos cómo podemos usar el método random() para generar un número aleatorio entre 0 y 10: - -```js -let randomNum = Math.random(); // 0 a 0.999 -let numBtnZeroAndTen = randomNum * 11; - -console.log(numBtnZeroAndTen); // esto da: min 0 y max 10.99 - -let randomNumRoundToFloor = Math.floor(numBtnZeroAndTen); -console.log(randomNumRoundToFloor); // esto da entre 0 y 10 -``` - -## Cadenas - -Las cadenas son textos, que están debajo de **_single_** , **_double_**, **_back-tick_** comillas. Para declarar una cadena, necesitamos un nombre de variable, un operador de asignación, un valor entre comillas simples, comillas dobles o comillas invertidas. -Veamos algunos ejemplos de cadenas: - -```js -let espacio = " "; // una cadena de espacio vacío -let primerNombre = "Asabeneh"; -let apellido = "Yetayeh"; -let pais = "Finland"; -let ciudad = "Helsinki"; -let idioma = "JavaScript"; -let trabajo = "teacher"; -let cita = "The saying,'Seeing is Believing' is not correct in 2020."; -let quotConBackTick = `The saying,'Seeing is Believing' is not correct in 2020.`; -``` - -### Concatenación de cadenas - -La conexión de dos o más cadenas entre sí se llama concatenación. -Usando las cadenas declaradas en la sección de Cadenas anterior: - -```js -let nombreCompleto = primerNombre + espacio + apellido; // concatenación, fusionando dos cadenas juntas. -console.log(nombreCompleto); -``` - -```sh -Asabeneh Yetayeh -``` - -Podemos concatenar cadenas de diferentes formas. - -#### Concatenar usando el operador de suma - -Concatenar usando el operador de suma es una forma antigua. Esta forma de concatenar es tediosa y propensa a errores. Es bueno saber cómo concatenar de esta manera, pero recomiendo enfáticamente usar las cadenas de plantilla ES6 (explicadas más adelante). - -```js -// Declarar diferentes variables de diferentes tipos de datos -let espacio = " "; -let primerNombre = "Asabeneh"; -let apellido = "Yetayeh"; -let pais = "Finland"; -let ciudad = "Helsinki"; -let idioma = "JavaScript"; -let trabajo = "teacher"; -let edad = 250; - -let nombreCompleto = primerNombre + espacio + apellido; -let datosPersonaUno = - nombreCompleto + ". Yo tengo " + edad + ". Vivo en" + pais; // Adición de cadena ES5 - -console.log(personInfoOne); -``` - -```sh -Asabeneh Yetayeh. Yo tengo 250v Finland -``` - -#### Cadenas literales largas - -Una cadena puede ser un solo carácter, un párrafo o una página. Si la longitud de la cadena es demasiado grande, no cabe en una línea. Podemos usar el carácter de barra invertida (\\) al final de cada línea para indicar que la cadena continuará en la línea siguiente. -**Ejemplo:** - -```js -const parrafo = - "Mi nombre es Asabeneh Yetayeh. Vivo en Finlandia, Helsinki.\ -Soy profesora y me encanta enseñar. Enseño HTML, CSS, JavaScript, React, Redux, \ -Node.js, Python, Data Analysis y D3.js para cualquier persona interesada en aprender. \ -A fines de 2019, estaba pensando en expandir mi enseñanza y llegar a \ -a la audiencia global y comencé un desafío de Python del 20 de noviembre al 19 de diciembre.\ -Fue una de las experiencias más gratificantes e inspiradoras.\ -Ahora, estamos en 2020. Disfruto preparando el desafío 30DaysOfJavaScript y \ -Espero que tú también estés disfrutando."; - -console.log(parrafo); -``` - -#### Secuencias de escape en cadenas - -En JavaScript y otros lenguajes de programación \ seguido de algunos caracteres es una secuencia de escape. Veamos los caracteres de escape más comunes: - --\n: nueva linea - -- \t: Tabulador, significa 8 espacios -- \\\\: barra invertida -- \\': Una frase (') -- \\": comillas dobles (") - -```js -console.log( - "Espero que todos estén disfrutando el desafío de 30 días de JavaScript.¿Y tú?" -); // salto de línea -console.log("Días\temasEjercicios"); -console.log("Día 1\t3\t5"); -console.log("Día 2\t3\t5"); -console.log("Día 3\t3\t5"); -console.log("Día 4\t3\t5"); -console.log("Este es un símbolo de barra invertida (\\)"); // Para escribir una barra invertida -console.log( - 'En todos los lenguajes de programación comienza con "¡Hola, mundo!"' -); -console.log( - "En todos los lenguajes de programación comienza con '¡Hola, mundo!'" -); -console.log("El dicho 'Ver para creer' no es correcto en 2022"); -``` - -Salida en consola: - -```sh -Espero que todos estén disfrutando el desafío de 30 días de JavaScript. -¿Y tú? - -Días temas Ejercicios -Día 1 3 5 -Día 2 3 5 -Día 3 3 5 -Día 4 3 5 -Este es un símbolo de barra invertida (\) -En todos los lenguajes de programación comienza con"¡Hola, mundo!" -En todos los lenguajes de programación comienza con"¡Hola, mundo!" -El dicho 'Ver para creer' no es correcto en 2022 -``` - -#### Literales de plantilla - -Para crear una plantilla de cadenas(cadenas de plantilla), usamos dos tildes de retroceso. Podemos inyectar datos como expresiones dentro de una cadena de plantilla. Para inyectar datos, encerramos la expresión con un corchete ({}) precedido por un signo $. Consulte la sintaxis a continuación. - -```js -//Sintaxis -`Texto literal de cadena``Cadena de texto literal ${expresión}`; -``` - -**Ejemplo: 1** - -```js -console.log(`La suma de 2 y 3 es 5`); // escribiendo estáticamente los datos -let a = 2; -let b = 3; -console.log(`La suma de ${a} y ${b} es ${a + b}`); // inyectando los datos dinámicamente -``` - -**Ejemplo:2** - -```js -let espacio = " "; -let primerNombre = "Asabeneh"; -let apellido = "Yetayeh"; -let pais = "Finland"; -let ciudad = "Helsinki"; -let idioma = "JavaScript"; -let trabajo = "profesora"; -let edad = 250; -let nombreCompleto = primerNombre + espacio + apellido; - -let personaInfoDos = `Soy ${nombreCompleto}. Tengo ${edad} años. Vivo en ${pais}.`; //ES6 - Método de interpolación de cadenas -let personaInfoTres = `Soy ${nombreCompleto}. Vivo en ${ciudad}, ${pais}. Soy una ${trabajo}. Enseño ${idioma}.`; -console.log(personaInfoDos); -console.log(personaInfoTres); -``` - -```sh -Soy Asabeneh Yetayeh. Tengo 250 años. Vivo en in Finland. -Soy Asabeneh Yetayeh. Vivo en Helsinki, Finland. Soy una profesora. Enseño JavaScript. -``` - -Usando una plantilla de cadena o un método de interpolación de cadena, podemos agregar expresiones, que podrían ser un valor, o algunas operaciones (comparación, operaciones aritméticas, operación ternaria). - -```js -let a = 2; -let b = 3; -console.log(`${a} es mayor que ${b}: ${a > b}`); -``` - -```sh -2 es mayor que 3: false -``` - -### Métodos de cadena - -Todo en JavaScript es un objeto. Una cadena es un tipo de datos primitivo, lo que significa que no podemos modificarla una vez que se crea. El objeto de cadena tiene muchos métodos de cadena. Existen diferentes métodos de cadenas que nos pueden ayudar a trabajar con cadenas. - -1. _longitud_: el método de cadena _longitud_ devuelve el número de caracteres en una cadena incluido el espacio vacío. - -**Example:** - -```js -let js = "JavaScript"; -console.log(js.length); // 10 -let primerNombre = "Asabeneh"; -console.log(primerNombre.length); // 8 -``` - -2. _Acceder a los caracteres de una cadena_: Podemos acceder a cada carácter de una cadena usando su índice. En programación, el conteo comienza desde 0. El primer índice de la cadena es cero y el último índice es la longitud de la cadena menos uno. - -![Accessing sting by index](../images/string_indexes.png) - -Accedamos a diferentes caracteres en la cadena 'JavaScript'. - -```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()_: este método cambia la cadena a letras mayúsculas. - -```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()_: este método cambia la cadena a letras minúsculas. - -```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()_: Se necesitan dos argumentos, el índice inicial y el número de caracteres para dividir. - -```js -let string = "JavaScript"; -console.log(string.substr(4, 6)); // Script - -let country = "Finland"; -console.log(country.substr(3, 4)); // land -``` - -6. _substring()_: Toma dos argumentos, el índice inicial y el índice final, pero no incluye el carácter en el índice final. - -```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()_: El método split divide una cadena en un lugar específico. - -```js -let string = "30 Days Of JavaScript"; - -console.log(string.split()); // Cambios en una matriz -> ["30 Days Of JavaScript"] -console.log(string.split(" ")); // Dividir a una matriz en el espacio -> ["30", "Days", "Of", "JavaScript"] - -let firstName = "Asabeneh"; - -console.log(firstName.split()); // Cambiar a una matriz - > ["Asabeneh"] -console.log(firstName.split("")); // Dividir en una matriz en cada letra -> ["A", "s", "a", "b", "e", "n", "e", "h"] - -let countries = "Finland, Sweden, Norway, Denmark, and Iceland"; - -console.log(countries.split(",")); // Dividir en cualquier matriz en coma -> ["Finland", " Sweden", " Norway", " Denmark", " and Iceland"] -console.log(countries.split(", ")); //  ["Finland", "Sweden", "Norway", "Denmark", "and Iceland"] -``` - -8. _trim()_: Elimina el espacio final al principio o al final de una cadena. - -```js -let string = " 30 Days Of JavaScript "; - -console.log(string); -console.log(string.trim(" ")); - -let firstName = " Asabeneh "; - -console.log(firstName); -console.log(firstName.trim()); // todavía elimina espacios al principio y al final de la cadena -``` - -```sh - 30 Days Of JavasCript -30 Days Of JavasCript - Asabeneh -Asabeneh -``` - -9. _includes()_: Toma un argumento de subcadena y verifica si existe un argumento de subcadena en la cadena. _includes()_ devuelve un valor booleano. Si existe una subcadena en una cadena, devuelve verdadero; de lo contrario, devuelve falso. - -```js -let string = "30 Days Of JavaScript"; - -console.log(string.includes("Days")); // verdadero -console.log(string.includes("days")); // falso: ¡se distingue entre mayúsculas y minúsculas! -console.log(string.includes("Script")); // verdadero -console.log(string.includes("script")); // falso -console.log(string.includes("java")); // falso -console.log(string.includes("Java")); // verdadero - -let country = "Finland"; - -console.log(country.includes("fin")); // falso -console.log(country.includes("Fin")); // verdadero -console.log(country.includes("land")); // verdadero -console.log(country.includes("Land")); // falso -``` - -10. _replace()_: toma como parámetro la subcadena antigua y una nueva subcadena. - -```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()_: Toma índice y devuelve el valor en ese índice - -```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()_: Toma el índice y devuelve el código char (número ASCII) del valor en ese índice - -```js -string.charCodeAt(index); -``` - -```js -let string = "30 Days Of JavaScript"; -console.log(string.charCodeAt(3)); // D ASCII numbero es 68 - -let lastIndex = string.length - 1; -console.log(string.charCodeAt(lastIndex)); // t ASCII es 116 -``` - -13. _indexOf()_: Toma una subcadena y si la subcadena existe en una cadena, devuelve la primera posición de la subcadena; si no existe, devuelve -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()_: Toma una subcadena y si la subcadena existe en una cadena, devuelve la última posición de la subcadena; si no existe, devuelve -1 - -```js -//syntax -string.lastIndexOf(substring); -``` - -```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()_: toma muchas subcadenas y las une. - -```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_: toma una subcadena como argumento y verifica si la cadena comienza con esa subcadena especificada. Devuelve un valor booleano (verdadero o falso). - -```js -//syntax -string.startsWith(substring); -``` - -```js -let string = "Love is the best to in this world"; - -console.log(string.startsWith("Love")); // verdadero -console.log(string.startsWith("love")); // falso -console.log(string.startsWith("world")); // falso - -let country = "Finland"; - -console.log(country.startsWith("Fin")); // verdadero -console.log(country.startsWith("fin")); // falso -console.log(country.startsWith("land")); // falso -``` - -17. _endsWith_: toma una subcadena como argumento y verifica si la cadena termina con esa subcadena especificada. Devuelve un valor booleano (verdadero o falso). - -```js -string.endsWith(substring); -``` - -```js -let string = "Love is the most powerful feeling in the world"; - -console.log(string.endsWith("world")); // verdadero -console.log(string.endsWith("love")); // falso -console.log(string.endsWith("in the world")); // verdadero - -let country = "Finland"; - -console.log(country.endsWith("land")); // verdadero -console.log(country.endsWith("fin")); // falso -console.log(country.endsWith("Fin")); // falso -``` - -18. _search_: toma una subcadena como argumento y devuelve el índice de la primera coincidencia. El valor de búsqueda puede ser una cadena o un patrón de expresión regular. - -```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 -console.log(string.search(/javascript/gi)); // 7 -``` - -19. _match_: toma una subcadena o un patrón de expresión regular como argumento y devuelve una matriz si hay una coincidencia; de lo contrario, devuelve un valor nulo. Veamos cómo se ve un patrón de expresión regular. Comienza con /signo y termina con /signo. - -```js -let string = "love"; -let patternOne = /love/; // sin ninguna bandera -let patternTwo = /love/gi; // g-significa buscar en todo el texto, i - no distingue entre mayúsculas y minúsculas -``` - -Coincidencia de sintaxis - -```js -// sintaxis -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"] -``` - -Extraigamos números del texto usando una expresión regular. Esta no es la sección de expresiones regulares, ¡no se asuste! Cubriremos las expresiones regulares más adelante. - -```js -let txt = - "In 2019, I ran 30 Days of Python. Now, in 2020 I am super exited to start this challenge"; -let regEx = /\d+/; - -// d con carácter de escape significa que d no es una d normal sino que actúa como un dígito -// + significa uno o más dígitos, -// si hay g después de eso, significa global, busque en todas partes. - -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()_: toma un número como argumento y devuelve la versión repetida de la cadena. - -```js -string.repeat(n); -``` - -```js -let string = "love"; -console.log(string.repeat(10)); // lovelovelovelovelovelovelovelovelovelove -``` - -## Comprobación de tipos de datos y conversión - -### Comprobación de tipos de datos - -Para comprobar el tipo de datos de una determinada variable utilizamos el método _typeof_. - -**Ejemplo:** - -```js -// Diferentes tipos de datos javascript -// Declaremos diferentes tipos de datos - -let firstName = 'Asabeneh' // cadena -let lastName = 'Yetayeh' // cadena -let pais = 'Finlandia'. // cadena -let ciudad = 'Helsinki' // cadena -let edad = 250 // numero, no es mi edad real, no te preocupes -let trabajo // indefinido, porque no se asignó un valor - -console.log(typeof 'Asabeneh') // cadena -console.log(typeof firstName) // cadena -console.log(typeof 10) // numbero -console.log(typeof 3.14) // numbero -console.log(typeof true) // booleano -console.log(typeof false) // booleano -console.log(typeof NaN) // numbero -console.log(typeof job) // indefinido -console.log(typeof undefined) // indefinido -console.log(typeof null) // objeto -``` - -### Cambio del tipo de datos - -- Casting: Conversión de un tipo de datos a otro tipo de datos. Usamos _parseInt()_, _parseFloat()_, _Number()_, _+ sign_, _str()_ - Cuando hacemos operaciones aritméticas, los números de cadena deben convertirse primero en enteros o flotantes; de lo contrario, devuelve un error. - -#### Cadena a Int - -Podemos convertir el número de cadena en un número. Cualquier número dentro de una comilla es un número de cadena. Un ejemplo de un número de cadena: '10', '5', etc. -Podemos convertir cadena a número usando los siguientes métodos: - -- parseInt() -- Número() -- Signo más (+) - -```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 -``` - -#### Cadena a Floatante - -Podemos convertir un número flotante de cadena en un número flotante. Cualquier número flotante dentro de una comilla es un número flotante de cadena. Un ejemplo de un número flotante de cadena: '9.81', '3.14', '1.44', etc. -Podemos convertir cadenas flotantes en números usando los siguientes métodos: - -- parseFloat() -- Número() -- Signo más (+) - -```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(numFloat); // 9.81 -``` - -#### Flotante a Int - -Podemos convertir números flotantes a enteros. -Usamos el siguiente método para convertir float a int: - -- parseInt() - -```js -let num = 9.81; -let numInt = parseInt(num); - -console.log(numInt); // 9 -``` - -🌕 Usted es maravilloso. Acabas de completar los desafíos del día 2 y estás dos pasos adelante en tu camino hacia la grandeza. Ahora haz algunos ejercicios para tu cerebro y tus músculos. - -## 💻 Día 2: Ejercicios - -### Ejercicio: Nivel 1 - -1. Declare una variable llamada desafío y asígnele un valor inicial **'30 días de JavaScript'**. -2. Imprima la cadena en la consola del navegador usando **console.log()** -3. Imprima la **longitud** de la cadena en la consola del navegador usando _console.log()_ -4. Cambie todos los caracteres de cadena a letras mayúsculas usando el método **toUpperCase()** -5. Cambie todos los caracteres de la cadena a letras minúsculas usando el método **toLowerCase()** -6. Corta (segmenta) la primera palabra de la cadena usando el método **substr()** o **substring()** -7. Corta la frase _Days Of JavaScript_ de _30 Days Of JavaScript_. -8. Verifique si la cadena contiene una palabra **Script** usando el método **includes()** -9. Divide la **cadena** en un **array** usando el método **split()** -10. Divida la cadena 30 días de JavaScript en el espacio usando el método **split()** -11. 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon' **divide** la cadena en la coma y cámbiala a una matriz. -12. Cambie 30 días de JavaScript a 30 días de Python usando el método **replace()**. -13. ¿Qué es el carácter en el índice 15 en la cadena '30 días de JavaScript'? Utilice el método **charAt()**. -14. ¿Cuál es el código de carácter de J en la cadena '30 días de JavaScript' usando **charCodeAt()** -15. Use **indexOf** para determinar la posición de la primera aparición de **a** en 30 días de JavaScript -16. Utilice **lastIndexOf** para determinar la posición de la última aparición de **a** en 30 días de JavaScript. -17. Usa **indexOf** para encontrar la posición de la primera aparición de la palabra **porque** en la siguiente oración:**'No puedes terminar una oración con porque porque porque es una conjunción'** -18. Usa **lastIndexOf** para encontrar la posición de la última aparición de la palabra **porque** en la siguiente oración:**'No puedes terminar una oración con porque porque porque es una conjunción'** -19. Usa **buscar** para encontrar la posición de la primera aparición de la palabra **porque** en la siguiente oración:**'No puedes terminar una oración con porque porque porque es una conjunción'** -20. Use **trim()** para eliminar cualquier espacio en blanco final al principio y al final de una cadena. Por ejemplo, '30 días de JavaScript'. -21. Use el método **startsWith()** con la cadena _30 días de JavaScript_ y haga que el resultado sea verdadero -22. Use el método **endsWith()** con la cadena _30 días de JavaScript_ y haga que el resultado sea verdadero -23. Usa el método **match()** para encontrar todos los **a** en 30 días de JavaScript -24. Use **concat()** y fusione '30 días de' y 'JavaScript' en una sola cadena, '30 días de JavaScript' -25. Use el método **repeat()** para imprimir 30 días de JavaScript 2 veces - -### Ejercicio: Nivel 2 - -1. Usando console.log() imprima la siguiente declaración: - - ```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 one another. - ``` - -2. Usando console.log() imprima la siguiente cita de la Madre 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." - ``` - -3. Compruebe si typeof '10' es exactamente igual a 10. Si no, hágalo exactamente igual. -4. Compruebe si parseFloat('9.8') es igual a 10, si no, hágalo exactamente igual a 10. -5. Verifique si 'on' se encuentra tanto en Python como en la jerga -6. _Espero que este curso no esté lleno de jerga_. Compruebe si _jargon_ está en la oración. -7. Genere un número aleatorio entre 0 y 100 inclusive. -8. Genere un número aleatorio entre 50 y 100 inclusive. -9. Genere un número aleatorio entre 0 y 255 inclusive. -10. Acceda a los caracteres de la cadena 'JavaScript' utilizando un número aleatorio. -11. Use console.log() y caracteres de escape para imprimir el siguiente patrón. - - ```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 - ``` - -12. Usa **substr** para separar la frase **porque porque porque** de la siguiente oración:**'No puedes terminar una oración con porque porque porque es una conjunción'** - -### Ejercicios: Nivel 3 - -1. 'El amor es lo mejor que hay en este mundo. Algunos encontraron su amor y algunos todavía están buscando su amor. Cuente el número de palabras **amor** en esta oración. -2. Usa **match()** para contar el número de todos los **porque** en la siguiente oración:**'No puedes terminar una oración con porque porque porque es una conjunción'** -3. Limpia el siguiente texto y encuentra la palabra más frecuente (pista, usa replace y expresiones regulares). - - ```js - const sentence = - "%I $am@% a %tea@cher%, &and& I lo%#ve %te@a@ching%;. The@re $is no@th@ing; &as& mo@re rewarding as educa@ting &and& @emp%o@weri@ng peo@ple. ;I found tea@ching m%o@re interesting tha@n any ot#her %jo@bs. %Do@es thi%s mo@tiv#ate yo@u to be a tea@cher!? %Th#is 30#Days&OfJavaScript &is al@so $the $resu@lt of &love& of tea&ching"; - ``` - -4. Calcula el ingreso anual total de la persona extrayendo los números del siguiente texto. 'Él gana 5000 euros de salario por mes, bono anual de 10000 euros, cursos en línea de 15000 euros por mes.' - -🎉 ¡FELICITACIONES! 🎉 - -[<< Día 1](./readme.md) | [Day 3 >>](./dia_03_Booleanos_Operadores_Date/dia_03_Boleanos_Operadores_Date.md) diff --git a/Spanish/dia_03_Booleanos_Operadores_Date/dia_03_Boleanos_Operadores_Date.md b/Spanish/dia_03_Booleanos_Operadores_Date/dia_03_Boleanos_Operadores_Date.md deleted file mode 100644 index 6fb7a6f..0000000 --- a/Spanish/dia_03_Booleanos_Operadores_Date/dia_03_Boleanos_Operadores_Date.md +++ /dev/null @@ -1,632 +0,0 @@ -
-

30 Días De JavaScript: Booleanos, Operadores, Date

- - - - - Twitter Follow - - -Autor: -Asabeneh Yetayeh
- Enero, 2020 -
- -
- -[<< Day 2](../dia_02_tipos_de_datos.md) | [Day 4 >>](../dia_04_Condicionales/dia_04_Condicionales.md) - -![Thirty Days Of JavaScript](../images/banners/day_1_3.png) - -- [📔 Día 3](#-day-3) - - [Booleanos](#booleanos) - - [Valores verdaderos](#valores-verdaderos) - - [Valores falsos](#valores-falsos) - - [Undefined](#undefined) - - [Null](#null) - - [Operadores](#operadores) - - [Operadores de Asignación](#operadores-de-asignación) - - [Operadores Aritméticos](#operadores-aritméticos) - - [Operadores de Comparación](#operadores-de-comparación) - - [Operadores Lógicos](#operadores-lógicos) - - [Operadores de Incremento](#operadores-de-incremento) - - [Operadores de Decremento](#operadores-de-decremento) - - [Operadores Ternarios](#operadores-ternarios) - - [Precedencia de Operadores](#precedencia-de-operadores) - - [Métodos Window](#métodos-window) - - [Método Window alert()](#método-window-alert) - - [Método Window prompt() ](#método-window-prompt) - - [Método Window confirm() ](#método-window-confirm) - - [Objeto Date](#objeto-date) - - [Crear un objeto de tiempo](#crear-un-objeto-de-tiempo) - - [Obtener el año completo](#obtener-el-año-completo) - - [Obtener mes](#obtener-mes) - - [Obtener fecha](#obtener-fecha) - - [Obtener día](#obtener-día) - - [Obtener horas](#obtener-horas) - - [Obtener minutos](#obtener-minutos) - - [Obtener segundos](#obtener-segundos) - - [Obtener tiempo](#obtener-tiempo) - - [💻 Día 3: Ejercicios](#💻-día-3-ejercicios) - - [Ejercicios: Nivel 1](#ejercicios-nivel-1) - - [Ejercicios: Nivel 2](#ejercicios-nivel-2) - - [Ejercicios: Nivel 3](#ejercicios-nivel-3) - -# 📔 Day 3 - -## Booleanos - -Un tipo de dato booleano representa uno de los dos valores: _true_ o _false_. El valor booleano es true (verdadero) o false (falso) El uso de estos tipos de datos quedará claro cuando veas operadores de comparación. Cualquier comparación devuelve un valor booleano que es true o false. - -**Ejemplos: Valores Booleanos** - -```js -let isLightOn = true; -let isRaining = false; -let isHungry = false; -let isMarried = true; -let truValue = 4 > 3; // true -let falseValue = 4 < 3; // false -``` - -Acordamos que los valores booleanos son true o false. - -### Valores verdaderos - -- Todos los números (positivos y negativos) son verdaderos excepto cero -- Todos las string (cadenas) son verdaderos excepto un string vacío ('') -- El booleano true - -### Valores falsos - -- 0 -- 0n -- null -- undefined -- NaN -- El booleano false -- '', "", ``, string vacío - -Es bueno recordar esos valores verdaderos y falsos. En una sección posterior, los usaremos con condiciones para tomar decisiones. - -## Undefined - -Si declaramos una variable y no le asignamos un valor, el valor será undefined (indefinido). Además de esto, si una función no devuelve el valor, será undefined. - -```js -let firstName; -console.log(firstName); //no definido, porque aún no está asignado un valor -``` - -## Null - -```js -let empty = null; -console.log(empty); // -> null (nulo) , significa que no tiene valor -``` - -## Operadores - -### Operadores de Asignación - -Un signo igual en JavaScript es un operador de asignación. Se utiliza para asignar una variable. - -```js -let firstName = "Asabeneh"; -let country = "Finland"; -``` - -Operadores de asignación - -![Assignment operators](../images/assignment_operators.png) - -### Operadores Aritméticos - -Los operadores aritméticos son operadores matemáticos. - -- Suma(+): a + b -- Resta(-): a - b -- Multiplicación(_): a _ b -- División(/): a / b -- Módulo(%): a % b -- Exponencial(**): 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 -``` - -```js -const PI = 3.14; -let radius = 100; // longitud en metros - -//Calculemos el área de un circulo -const areaOfCircle = PI * radius * radius; -console.log(areaOfCircle); // 314 m - -const gravity = 9.81; // en m/s2 -let mass = 72; // en Kilogram - -// Calculemos el peso de un objeto. -const weight = mass * gravity; -console.log(weight); // 706.32 N(Newton) - -const boilingPoint = 100; // temperatura en °C, punto de ebullición del agua -const bodyTemp = 37; // temperatura corporal en °C - -// Concatenación de string con números usando interpolación de strings -/* - El punto de ebullición del agua es de 100 °C. - La temperatura del cuerpo humano es de 37 oC. - La gravedad de la tierra es de 9.81 m/s2. - */ -console.log( - `El punto de ebullición del agua es de ${boilingPoint} °C.\nLa temperatura del cuerpo humano es de ${bodyTemp} °C.\nLa gravedad de la tierra es de ${gravity} m / s2.` -); -``` - -### Operadores de Comparación - -En programación comparamos valores, usamos operadores de comparación para comparar dos valores. Comprobamos si un valor es mayor, menor o igual a otro valor. - -![Operadores de Comparación](../images/comparison_operators.png) -**Ejemplos: Operadores de Comparación** - -```js -console.log(3 > 2); // true, porque 3 es mayor que 2 -console.log(3 >= 2); // true, porque 3 es mayor que 2 -console.log(3 < 2); // false, porque 3 es mayor que 2 -console.log(2 < 3); // true, porque 2 es menor que 3 -console.log(2 <= 3); // true, porque 2 es menor que 3 -console.log(3 == 2); // false, porque 3 no es igual a 2 -console.log(3 != 2); // true, porque 3 no es igual a 2 -console.log(3 == "3"); // true, compara solamente el valor -console.log(3 === "3"); // false, compara tanto el valor como el tipo de dato -console.log(3 !== "3"); // true, compara tanto el valor como el tipo de dato -console.log(3 != 3); // false, compara solo valor -console.log(3 !== 3); // false, compara tanto el valor como el tipo de dato -console.log(0 == false); // true, equivalente -console.log(0 === false); // false, No exactamente igual -console.log(0 == ""); // true, equivalente -console.log(0 == " "); // true, equivalente -console.log(0 === ""); // false, No exactamente igual -console.log(1 == true); // true, equivalente -console.log(1 === true); // false, No exactamente igual -console.log(undefined == null); // true -console.log(undefined === null); // false -console.log(NaN == NaN); // false, diferente -console.log(NaN === NaN); // false -console.log(typeof NaN); // tipo número - -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); // true -console.log("milk".length != "meat".length); // false -console.log("tomato".length == "potato".length); // true -console.log("python".length > "dragon".length); // false -``` - -Trate de entender las comparaciones anteriores con algo de lógica. Recuerde que ninguna lógica puede ser difícil. -JavaScript es de alguna manera un lenguaje extraño de programación. El código JavaScript se ejecuta y le da un resultado, pero a menos que sea bueno en él, puede que no sea el resultado deseado. - -Como regla general, si un valor no es verdadero con == no será igual con ===. Usar === es más seguro que usar ==. El siguiente [link](https://dorey.github.io/JavaScript-Equality-Table/) tiene una lista exhaustiva de comparaciones de tipos de datos. - -### Operadores Lógicos - -Los siguientes símbolos son los operadores lógicos más comunes: -&&(ampersand) , ||(pipe) and !(negation). -El operador && se vuelve verdadero sólo si los dos operandos son verdaderos. -El operador || se vuelve verdadero cualquiera de los operandos es verdadero. -El operador ! niega true a false y false a true. - -```js -// && ejemplo de operador ampersand - -const check = 4 > 3 && 10 > 5; // true && true -> true -const check = 4 > 3 && 10 < 5; // true && false -> false -const check = 4 < 3 && 10 < 5; // false && false -> false - -// || ejemplo de operador pipe - -const check = 4 > 3 || 10 > 5; // true || true -> true -const check = 4 > 3 || 10 < 5; // true || false -> true -const check = 4 < 3 || 10 < 5; // false || false -> false - -//! ejemplos de negación - -let check = 4 > 3; // true -let check = !(4 > 3); // false -let isLightOn = true; -let isLightOff = !isLightOn; // false -let isMarried = !false; // true -``` - -### Operadores de Incremento - -En JavaScript usamos el operador de incremento para aumentar un valor almacenado en una variable. El incremento podría ser antes o después del incremento. Veamos cada uno de ellos: - -1. Pre-incremento - -```js -let count = 0; -console.log(++count); // 1 -console.log(count); // 1 -``` - -1. Post-incremento - -```js -let count = 0; -console.log(count++); // 0 -console.log(count); // 1 -``` - -Usamos la mayor parte del tiempo post-incremento. Pero debes recordar cómo usar el operador de incremento posterior. - -### Operadores de Decremento - -En JavaScript usamos el operador de decremento para disminuir un valor almacenado en una variable. El decremento puede ser previo o posterior al decremento. Veamos cada uno de ellos: - -1. Pre-decremento - -```js -let count = 0; -console.log(--count); // -1 -console.log(count); // -1 -``` - -2. Post-decremento - -```js -let count = 0; -console.log(count--); // 0 -console.log(count); // -1 -``` - -### Operadores Ternarios - -El operador ternario permite escribir una condición. -Otra forma de escribir condicionales es usando operadores ternarios. Mira los siguientes ejemplos: - -```js -let isRaining = true; -isRaining - ? console.log("Necesitas un impermeable.") - : console.log("No necesitas un impermeable."); -isRaining = false; - -isRaining - ? console.log("Necesitas un impermeable.") - : console.log("No necesitas un impermeable."); -``` - -```sh -Necesitas un impermeable. -No necesitas un impermeable. -``` - -```js -let number = 5; -number > 0 - ? console.log(`${number} is a positive number`) - : console.log(`${number} is a negative number`); -number = -5; - -number > 0 - ? console.log(`${number} is a positive number`) - : console.log(`${number} is a negative number`); -``` - -```sh -5 es un número positivo --5 es un número negativo -``` - -### Precedencia de Operadores - -Me gustaría recomendarle que lea sobre la precedencia de operadores en el siguiente [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence) - -## Métodos Window - -### Método Window alert() - -Cómo ha visto al principio, el método alert() muestra un cuadro de alerta con un mensaje específico y un botón Aceptar. Es un método incorporado y toma un argumento. - -```js -alert(message); -``` - -```js -alert("Bienvenido a 30DaysOfJavaScript"); -``` - -No uses demasiada alert (alertas) porque molesta, úsala solo para probar. - -### Método Window prompt() - -Los métodos window prompt (entrada) muestran un cuadro de solicitud con una entrada en su navegador para tomar valores de entrada y los datos de entrada se pueden almacenar en una variable. El método prompt() toma dos argumentos. El segundo argumento es opcional. - -```js -prompt("texto requerido", "texto opcional"); -``` - -```js -let number = prompt("Ingrese un número", "El número va aquí"); -console.log(number); -``` - -### Método Window confirm() - -El método confirm() muestra un cuadro de diálogo con un mensaje específico, junto con un botón Aceptar y Cancelar. Un cuadro de confirmación se usa a menudo para pedir permiso a un usuario para ejecutar algo. Window confirm() toma una cadena como argumento. Al hacer clic en Aceptar se obtiene un valor true, mientras que al hacer clic en el botón Cancelar se obtiene un valor false. - -```js -const agree = confirm("¿Estás seguro de que quieres eliminar? "); -console.log(agree); // el resultado será true o false según el click en el cuadro de diálogo -``` - -Estos no son todos los métodos de window, tendremos una sección separada para profundizar en los métodos de window. - -## Objeto Date - -El tiempo es una cosa importante. Nos gusta saber la hora de una determinada actividad o evento. En JavaScript, la hora y la fecha actuales se crean utilizando el objeto Date de JavaScript. El objeto que creamos usando el objeto Date proporciona muchos métodos para trabajar con fecha y hora. Los métodos que usamos para obtener información de fecha y hora de los valores de un objeto Date comienzan con una palabra _get_ porque proporciona la información. -_getFullYear(), getMonth(), getDate(), getDay(), getHours(), getMinutes, getSeconds(), getMilliseconds(), getTime(), getDay()_ - -![Date time Object](../images/date_time_object.png) - -### Crear un objeto de tiempo - -Una vez que creamos el objeto de tiempo. El objeto de tiempo proporcionará información sobre el tiempo. Vamos a crear un objeto de tiempo - -```js -const now = new Date(); -console.log(now); // Sáb 04 de enero de 2020 00:56:41 GMT+0200 (hora estándar de Europa del Este -``` - -Hemos creado un objeto de tiempo y podemos acceder a cualquier información de fecha y hora del objeto utilizando los métodos de obtención que hemos mencionado en la tabla. - -### Obtener el año completo - -Extraigamos u obtengamos el año completo de un objeto de tiempo. - -```js -const now = new Date(); -console.log(now.getFullYear()); // 2020 -``` - -### Obtener mes - -Extraigamos u obtengamos el mes de un objeto de tiempo. - -```js -const now = new Date(); -console.log(now.getMonth()); // 0, porque el mes es enero, meses(0-11) -``` - -### Obtener fecha - -Extraigamos u obtengamos la fecha del mes de un objeto de tiempo. - -```js -const now = new Date(); -console.log(now.getDate()); // 4, porque es el 4to dia del mes, día (1-31) -``` - -### Obtener día - -Extraigamos u obtengamos el día de la semana de un objeto de tiempo. - -```js -const now = new Date(); -console.log(now.getDay()); // 6, porque el día es sábado que es el día 7 -// El domingo es 0, el lunes es 1 y el sábado es 6 -// Obtener el día de la semana como un número (0-6) -``` - -### Obtener horas - -Extraigamos u obtengamos las horas de un objeto de tiempo. - -```js -const now = new Date(); -console.log(now.getHours()); // 0, porque el tiempo es 00:56:41 -``` - -### Obtener minutos - -Extraigamos u obtengamos los minutos de un objeto de tiempo. - -```js -const now = new Date(); -console.log(now.getMinutes()); // 56, porque el tiempo es 00:56:41 -``` - -### Obtener segundos - -Extraigamos u obtengamos los segundos de un objeto de tiempo. - -```js -const now = new Date(); -console.log(now.getSeconds()); // 41, porque el tiempo es 00:56:41 -``` - -### Obtener tiempo - -Este método da tiempo en milisegundos a partir del 1 de enero de 1970. También se conoce como tiempo Unix. Podemos obtener el tiempo de Unix de dos maneras: - -1. Usando _getTime()_ - -```js -const now = new Date(); // -console.log(now.getTime()); // 1578092201341, este es el número de segundos que han pasado desde el 1ero de Enero de 1970 al 4 de Enero del 2020 00:56:41 -``` - -2. Usando _Date.now()_ - -```js -const allSeconds = Date.now(); // -console.log(allSeconds); // 1578092201341, este es el número de segundos que han pasado desde el 1ero de Enero de 1970 al 4 de Enero del 2020 00:56:41 - -const timeInSeconds = new Date().getTime(); -console.log(allSeconds == timeInSeconds); // true -``` - -Vamos a formatear estos valores a un formato de tiempo legible por humanos. -**Ejemplo:** - -```js -const now = new Date(); -const year = now.getFullYear(); // return años -const month = now.getMonth() + 1; // return meses(0 - 11) -const date = now.getDate(); // return días (1 - 31) -const hours = now.getHours(); // return horas (0 - 23) -const minutes = now.getMinutes(); // return minutos (0 -59) - -console.log(`${date}/${month}/${year} ${hours}:${minutes}`); // 4/1/2020 0:56 -``` - -🌕 Tienes una energía ilimitada. Acabas de completar los desafíos del día 3 y estás a tres pasos de tu camino hacia la grandeza. Ahora haz algunos ejercicios para tu cerebro y tus músculos. - -## 💻 Día 3: Ejercicios - -### Ejercicios: Nivel 1 - -1. Declare las siguientes variables; firstName, lastName, country, city, age, isMarried, year y asignar un valor, use el operador typeof para verificar diferentes tipos de datos. -2. Verifique si typeof '10' es igual a 10 -3. Verifique si parseInt('9.8') es igual a 10 -4. Verifique cualquier valor booleano true o false. - - 1. Escriba tres declaraciones de JavaScript que proporcionen un valor verdadero. - 2. Escriba tres declaraciones de JavaScript que proporcionen un valor falso. - -5. Calcule primero el resultado de la siguiente expresión de comparación sin usar console.log(). Después de decidir el resultado, confirmelo usando console.log() - - 1. 4 > 3 - 2. 4 >= 3 - 3. 4 < 3 - 4. 4 <= 3 - 5. 4 == 4 - 6. 4 === 4 - 7. 4 != 4 - 8. 4 !== 4 - 9. 4 != '4' - 10. 4 == '4' - 11. 4 === '4' - 12. Encuentre la longitud de Python y jargon y haga una declaración de comparación falsa. - -6. Calcule primero el resultado de las siguientes expresiones sin usar console.log(). Después de decidir el resultado, confirmelo usando 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') - 11. No hay 'on' tanto en dragon como en python - -7. Utilice el objeto Date para realizar las siguientes actividades - 1. ¿Qué año es hoy? - 2. ¿Qué mes es hoy con un número? - 3. ¿Qué fecha es hoy? - 4. ¿Qué día es hoy con un número? - 5. ¿Cuál es la hora actual? - 6. ¿Cuántos minutos hay actualmente? - 7. Averigüe el número de segundos transcurridos desde el 1 de enero de 1970 hasta ahora. - -### Ejercicios: Nivel 2 - -1. Escriba un script que solicite al usuario que ingrese la base y la altura del triángulo y calcule el área de un triángulo (área = 0,5 x b x h). - - ```sh - Ingrese base: 20 - Ingrese altura: 10 - El área del triángulo es: 100 - ``` - -1. Escriba un script que solicite al usuario que ingrese el lado a, el lado b y el lado c del triángulo y calcule el perímetro del triángulo (perímetro = a + b + c) - - ```sh - Ingrese lado a: 5 - Ingrese lado b: 4 - Ingrese lado c: 3 - El perimetro del triangulo es: 12 - ``` - -1. Obtenga el largo y el ancho usando prompt y calcule el área del rectángulo (área = largo x ancho y el perímetro del rectángulo (perímetro = 2 x (largo + ancho)) -1. Obtenga el radio usando prompt y calcule el área de un círculo (área = pi x r x r) y la circunferencia de un círculo (c = 2 x pi x r) donde pi = 3.14. -1. Calcule la pendiente, la intersección X y la intersección Y de y = 2x -2 -1. La pendiente es m = (y2-y1)/(x2-x1). Encuentra la pendiente entre el punto (2, 2) y el punto (6,10) -1. Compare la pendiente de las dos preguntas anteriores. -1. Calcula el valor de y (y = x2 + 6x + 9). Trate de usar diferentes valores de x y averigüe en qué valor de x y es 0. -1. Escriba un script con prompt que solicite al usuario que ingrese las horas y la tarifa por hora. ¿Calcular el salario de la persona? - - ```sh - Ingrese horas: 40 - Introduce la tarifa por hora: 28 - Su ganancia semanal es 1120 - ``` - -1. Si la longitud de su nombre es mayor que 7, diga que su nombre es largo; de lo contrario, diga que su nombre es corto. -1. Compare la longitud de su nombre y la longitud de su apellido y debería obtener este resultado. - - ```js - let firstName = "Asabeneh"; - let lastName = "Yetayeh"; - ``` - - ```sh - Tu primer nombre, Asabeneh, es más largo que tu apellido, Yetayeh. - ``` - -1. Declare dos variables _myAge_ y _yourAge_ y asignarles los valores iniciales y myAge y yourAge. - - ```js - let myAge = 250; - let yourAge = 25; - ``` - - ```sh - Soy 225 años mayor que tú. - ``` - -1. Usando prompt, obtenga el año en que nació el usuario y, si el usuario tiene 18 años o más, permita que el usuario conduzca, si no dígale que espere una cierta cantidad de años. - - ```sh - - Introduzca el año de nacimiento: 1995 - Tienes 25 años. Tienes la edad suficiente para conducir. - - Introduzca el año de nacimiento: 2005 - Tienes 15 años. Podrás conducir después de 3 años. - ``` - -1. Escriba un script que solicite por prompt al usuario que ingrese el número de años. Calcular el número de segundos que puede vivir una persona. Supongamos que alguien vive solo cien años - - ```sh - Ingrese el número de años de vida: 100 - Viviste 3153600000 segundos. - ``` - -1. Cree un formato de hora legible por humanos usando el objeto Date. - 1. YYYY-MM-DD HH:mm - 2. DD-MM-YYYY HH:mm - 3. DD/MM/YYYY HH:mm - -### Ejercicios: Nivel 3 - -1. Cree un formato de hora legible por humanos usando el objeto Date. La hora y el minuto deben ser siempre dos dígitos (7 horas deben ser 07 y 5 minutos deben ser 05) - 1. YYY-MM-DD HH:mm eg. 20120-01-02 07:05 - -[<< Day 2](../dia_02_tipos_de_datos.md) | [Day 4 >>](../dia_04_Condicionales/dia_04_Condicionales.md) diff --git a/Spanish/dia_04_Condicionales/dia_04_Condicionales.md b/Spanish/dia_04_Condicionales/dia_04_Condicionales.md deleted file mode 100644 index 5713182..0000000 --- a/Spanish/dia_04_Condicionales/dia_04_Condicionales.md +++ /dev/null @@ -1,376 +0,0 @@ -
-

30 Días de JavaScript: Condicionales

- - - - - Twitter Follow - - -Autor: -Asabeneh Yetayeh
- Enero, 2020 -
- -
- -[<< Día 3](../dia_03_Booleanos_Operadores_Date/dia_03_Boleanos_Operadores_Date.md) | [Día 5 >>](../dia_05_Arreglos/dia_05_arreglos.md) - -![Thirty Days Of JavaScript](../images/banners/day_1_4.png) - -- [📔 Día 4](#📔-día-4) - - [Condicionales](#condicionales) - - [If](#if) - - [If Else](#if-else) - - [If Else if Else](#if-else-if-else) - - [Switch](#switch) - - [Operadores Ternarios](#operadores-ternarios) - - [💻 Ejercicios](#💻-ejercicios) - - [Ejercicios: Nivel 1](#ejercicios-nivel-1) - - [Ejercicios: Nivel 2](#ejercicios-nivel-2) - - [Ejercicios: Nivel 3](#ejercicios-nivel-3) - -# 📔 Día 4 - -## Condicionales - -Las declaraciones condicionales se utilizan para tomar decisiones basadas en diferentes condiciones. De forma predeterminada, las declaraciones en el script de JavaScript se ejecutan secuencialmente de arriba a abajo. Si la lógica de procesamiento lo requiere, el flujo secuencial de ejecución se puede alterar de dos formas: - -- Ejecución condicional: se ejecutará un bloque de una o más sentencias si cierta expresión es true -- Ejecución repetitiva: un bloque de una o más sentencias se ejecutará de forma repetitiva siempre que cierta expresión sea verdadera. En esta sección, cubriremos las declaraciones _if_, _else_ y _else if_. Los operadores lógicos y de comparación que aprendimos en las secciones anteriores serán útiles aquí. - -Las condiciones se pueden implementar de las siguientes maneras: - -- if -- if else -- if else if else -- switch -- operador ternario - -### If - -En JavaScript y otros lenguajes de programación, la palabra clave _if_ se usa para verificar si una condición es true y ejecutar el bloque de código. Para crear una condición if, necesitamos la palabra clave _if_, la condición va dentro de paréntesis y el bloque de código va dentro de llaves ({}). - -```js -// sintaxis -if (condition) { - //esta parte del código se ejecuta cuando es true -} -``` - -**Example:** - -```js -let num = 3; -if (num > 0) { - console.log(`${num} es un número positivo`); -} -// 3 es un número positivo -``` - -Como puede ver en el ejemplo de condición anterior, 3 es mayor que 0, por lo que es un número positivo. La condición era true y se ejecutó el bloque de código. Sin embargo, si la condición es falsa, no veremos ningún resultado. - -```js -let isRaining = true; -if (isRaining) { - console.log("Recuerda llevar tu impermeable."); -} -``` - -Lo mismo ocurre con la segunda condición, si isRaining es false, el bloque if no se ejecutará y no veremos ninguna respuesta. Para ver el resultado de una condición false, debemos tener otro bloque, que será _else_. - -### If Else - -Si la condición es true, se ejecutará el primer bloque, si no, se ejecutará la condición else. - -```js -// sintaxis -if (condition) { - // esta parte del código se ejecuta para la condición de verdad -} else { - // esta parte del código se ejecuta para una condición falsa -} -``` - -```js -let num = 3; -if (num > 0) { - console.log(`${num} es un número positivo`); -} else { - console.log(`${num} es un número negativo`); -} -// 3 es un número positivo - -num = -3; -if (num > 0) { - console.log(`${num} es un número positivo`); -} else { - console.log(`${num} es un número negativo`); -} -// -3 es un número negativo -``` - -```js -let isRaining = true; -if (isRaining) { - console.log("Necesitas un impermeable."); -} else { - console.log("No hay necesidad de un impermeable."); -} -// Necesitas un impermeable. - -isRaining = false; -if (isRaining) { - console.log("Necesitas un impermeable."); -} else { - console.log("No hay necesidad de un impermeable."); -} -// No hay necesidad de un impermeable. -``` - -La última condición es falsa, por lo que se ejecutó el bloque else. ¿Qué pasa si tenemos más de dos condiciones? En ese caso, usaremos las condiciones _else if_. - -### If Else if Else - -En nuestra vida, tomamos decisiones diariamente. Tomamos decisiones no comprobando una o dos condiciones, sino que tomamos decisiones basadas en múltiples condiciones. Al igual que nuestra vida diaria, la programación también está llena de condiciones. Usamos _else if_ cuando tenemos múltiples condiciones. - -```js -// sintaxis -if (condition) { - // código -} else if (condition) { - // código -} else { - // código -} -``` - -**Ejemplo:** - -```js -let a = 0; -if (a > 0) { - console.log(`${a} es un número positivo`); -} else if (a < 0) { - console.log(`${a} es un número negativo`); -} else if (a == 0) { - console.log(`${a} es cero`); -} else { - console.log(`${a} no es un número`); -} -``` - -```js -// if else if else -let weather = "sunny"; -if (weather === "rainy") { - console.log("Necesitas un impermeable."); -} else if (weather === "cloudy") { - console.log("Puede que haga frío, necesitas una chaqueta."); -} else if (weather === "sunny") { - console.log("Sal tranquilo."); -} else { - console.log("No hay necesidad de un impermeable."); -} -``` - -### Switch - -Switch es una alternativa para **if else if else else**. -La instrucción switch comienza con una palabra clave _switch_ seguida de un paréntesis y un bloque de código. Dentro del bloque de código tendremos diferentes casos. El bloque de casos se ejecuta si el valor en el paréntesis de la declaración de cambio coincide con el valor del caso. La declaración de break es para terminar la ejecución. Esto para que la ejecución del código se detenga después de que se cumpla la condición. El bloque default se ejecuta si todos los casos no cumplen la condición. - -```js -switch (caseValue) { - case 1: - // código - break; - case 2: - // código - break; - case 3: - // código - break; - default: - // código -} -``` - -```js -let weather = "cloudy"; -switch (weather) { - case "rainy": - console.log("Necesitas un impermeable."); - break; - case "cloudy": - console.log("Puede que haga frío, necesitas una chaqueta."); - break; - case "sunny": - console.log("Sal tranquilo."); - break; - default: - console.log("No hay necesidad de un impermeable."); -} - -// Más Ejemplos switch -let dayUserInput = prompt("¿Qué día es hoy?"); -let day = dayUserInput.toLowerCase(); - -switch (day) { - case "lunes": - console.log("Hoy es Lunes"); - break; - case "martes": - console.log("Hoy es Martes"); - break; - case "miércoles": - console.log("Hoy es Miércoles"); - break; - case "jueves": - console.log("Hoy es Jueves"); - break; - case "viernes": - console.log("Hoy es Viernes"); - break; - case "sábado": - console.log("Hoy es Sábado"); - break; - case "domingo": - console.log("Hoy es Domingo"); - break; - default: - console.log("No es un día de semana."); -} -``` - -// Ejemplos de condiciones en los casos - -```js -let num = prompt("Ingrese un número"); -switch (true) { - case num > 0: - console.log("El número es positivo"); - break; - case num == 0: - console.log("El número es cero"); - break; - case num < 0: - console.log("El número es negativo"); - break; - default: - console.log("El valor ingresado no era un número"); -} -``` - -### Operadores Ternarios - -Otra forma de escribir condicionales es usando operadores ternarios. Hemos cubierto esto en otras secciones, pero también deberíamos mencionarlo aquí. - -```js -let isRaining = true; -isRaining - ? console.log("Necesitas un impermeable.") - : console.log("No hay necesidad de un impermeable."); -``` - -🌕 Tienes una energía ilimitada. Acabas de completar los desafíos del día 4 y llevas cuatro pasos de tu camino hacia la grandeza. Ahora haz algunos ejercicios para tu cerebro y tus músculos. - -## 💻 Ejercicios - -### Ejercicios: Nivel 1 - -1. Obtenga la entrada del usuario usando el aviso ("Ingrese su edad:"). Si el usuario tiene 18 años o más, muestre el mensaje: 'Tiene la edad suficiente para conducir', pero si no tiene 18 años, brinde otro mensaje que indique que debe esperar la cantidad de años que necesita para cumplir 18. - - ```sh - Ingrese su edad: 30 - Tiene la edad suficiente para conducir. - - Ingrese su edad:15 - Te faltan 3 años para conducir. - ``` - -1. Compara los valores de myAge y yourAge usando if... else. Según la comparación, registre el resultado en la consola indicando quién es mayor (tú o yo). Utilice prompt(“Ingrese su edad:”) para obtener la edad como entrada. - - ```sh - Ingrese su edad: 30 - Eres 5 años mayor que yo. - ``` - -1. Si a es mayor que b, devuelve 'a es mayor que b'; de lo contrario, 'a es menor que b'. Trate de implementarlo de maneras diferentes - - - Usando if else - - operador ternario. - - ```js - let a = 4; - let b = 3; - ``` - - ```sh - 4 es mayor que 3 - ``` - -1. Los números pares son divisibles por 2 y el resto es cero. ¿Cómo verificar si un número es par o no usando JavaScript? - - ```sh - Ingrese un número: 2 - 2 es un número par - - Ingrese un número: 9 - 9 es un número impar - ``` - -### Ejercicios: Nivel 2 - -1. Escriba un código que pueda calificar a los estudiantes de acuerdo con sus puntajes: - - 80-100, A - - 70-89, B - - 60-69, C - - 50-59, D - - 0-49, F -1. Consulta si la temporada es Otoño, Invierno, Primavera o Verano. - Si la entrada del usuario es : - - - Septiembre, Octubre o Noviembre, la temporada es Otoño. - - Diciembre, Enero o Febrero, la temporada es Invierno. - - Marzo, Abril o Mayo, la temporada es Primavera - - Junio, Julio o Agosto, la temporada es Verano - -1. Compruebe si un día es un día de fin de semana o un día laborable. Su script tomará el día como entrada. - -```sh - ¿Qué día es hoy? Sábado - El sábado es fin de semana. - - ¿Qué día es hoy? sábAdo - El sábado es fin de semana. - - ¿Qué día es hoy? Viernes - El viernes es un día laborable. - - ¿Qué día es hoy? ViErNes - El viernes es un día laborable. -``` - -### Ejercicios: Nivel 3 - -1. Escribe un programa que diga el número de días en un mes. - -```sh - Introduce un mes: Enero - Enero tiene 31 días. - - Introduce un mes: ENERO - enero tiene 31 dias - - Introduce un mes: Febrero - Febrero tiene 28 días. - - Introduce un mes: FEbrero - Febrero tiene 28 días. -``` - -1. Escribe un programa que diga el número de días en un mes, ahora considera un año bisiesto. - -🎉 FELICITACIONES ! 🎉 - -[<< Día 3](../dia_03_Booleanos_Operadores_Date/dia_03_Boleanos_Operadores_Date.md) | [Día 5 >>](../dia_05_Arreglos/dia_05_arreglos.md) diff --git a/Spanish/dia_05_Arreglos/dia_05_arreglos.md b/Spanish/dia_05_Arreglos/dia_05_arreglos.md deleted file mode 100644 index 534effc..0000000 --- a/Spanish/dia_05_Arreglos/dia_05_arreglos.md +++ /dev/null @@ -1,781 +0,0 @@ -
-

30 Días de JavaScript: Arrays

- - - - - Twitter Follow - - -Autor: -Asabeneh Yetayeh
- January, 2020 -
- -
- -[<< Día 4](../dia_04_Condicionales/dia_04_Condicionales.md) | [Día 6 >>](../dia_06_Bucles/dia_06_bucles.md) - -![Day 5](../images/banners/day_1_5.png) - -- [📔 Día 5](#📔-día-5) - - [Arrays](#arrays) - - [Como crear un array vacío](#como-crear-un-array-vacío) - - [Como crear un array con valores](#como-crear-un-array-con-valores) - - [Creando un array usando split](#creando-un-array-usando-split) - - [Acceder a los elementos de un array usando el index](#acceder-a-los-elementos-de-un-array-usando-el-index) - - [Modificar elementos de array](#modificar-elementos-de-array) - - [Métodos para manipular arrays](#métodos-para-manipular-arrays) - - [Constructor de arrays](#constructor-de-arrays) - - [Creando valores estáticos con fill](#creando-valores-estáticos-con-fill) - - [Concatenación de arrays usando concat](#concatenación-de-arrays-usando-concat) - - [Obtener la longitud de array](#obtener-la-longitud-de-array) - - [Obtener el index de un elemento en un array](#obtener-el-index-de-un-elemento-en-un-array) - - [Obtener el último index de un elemento en un array](#obtener-el-último-index-de-un-elemento-en-un-array) - - [Comprobar un array](#comprobar-un-array) - - [Convertir array a string](#convertir-array-a-string) - - [Unir elementos de un array](#unir-elementos-de-un-array) - - [Cortar elementos de un array](#cortar-elementos-de-un-array) - - [Método splice en un array](#método-splice-en-un-array) - - [Agregar elementos a un array usando push](#agregar-elementos-a-un-array-usando-push) - - [Eliminar el último elemento usando pop](#eliminar-el-último-elemento-usando-pop) - - [Eliminar elemento al principio](#eliminar-elemento-al-principio) - - [Añade un elemento al inicio](#añade-un-elemento-al-inicio) - - [Invertir orden de un array](#invertir-orden-de-un-array) - - [Ordenar elementos en un array](#ordenar-elementos-en-un-array) - - [Array de arrays](#array-de-arrays) - - [💻 Ejercicios](#💻-ejercicios) - - [Ejercicios: Nivel 1](#ejercicios-nivel-1) - - [Ejercicios: Nivel 2](#ejercicios-nivel-2) - - [Ejercicios: Nivel 3](#ejercicios-nivel-3) - -# 📔 Día 5 - -## Arrays - -A diferencia de las variables, un array (matriz ó arreglo) puede almacenar _múltiples valores_.Cada valor en un array tiene un _index_ y cada index (índice) tiene _una referencia en una dirección de memoria_. Se puede acceder a cada valor usando sus _index_. El index de un array comienza desde _cero_, y el index del último elemento es menor a uno desde la longitud del array. - -Un array es una colección de diferentes tipos de datos que están ordenados y son cambiables (modificables). Un array permite almacenar elementos duplicados y diferentes tipos de datos. Un array puede estar vacío o puede tener diferentes valores de diferentes tipos de datos. - -### Como crear un array vacío - -En JavaScript, podemos crear una array de diferentes maneras. Veamos diferentes formas de crear un array. -Es muy común usar _const_ en lugar de _let_ para declarar una variable array. Si está utilizando const, significa que no volverás a utilizar ese nombre de variable. - -- Usando el constructor de arrays - -```js -// sintaxis -const arr = Array(); -// or -// let arr = new Array() -console.log(arr); // [] -``` - -- Usando corchetes([]) - -```js -// sintaxis -// Esto es lo más recomendable para crear una lista vacía -const arr = []; -console.log(arr); -``` - -### Como crear un array con valores - -Array con valores iniciales. Usamos _length_ para encontrar la longitud del array. - -```js -const numbers = [0, 3.14, 9.81, 37, 98.6, 100]; // array de números -const fruits = ["banana", "orange", "mango", "lemon"]; // array de strings, Fruits -const vegetables = ["Tomato", "Potato", "Cabbage", "Onion", "Carrot"]; // array de strings, vegetables -const animalProducts = ["milk", "meat", "butter", "yoghurt"]; // array de strings, products -const webTechs = ["HTML", "CSS", "JS", "React", "Redux", "Node", "MongDB"]; // array web, technology -const countries = ["Finland", "Denmark", "Sweden", "Norway", "Iceland"]; // array de strings, country - -// Imprimimos el array y su longitud - -console.log("Numbers:", numbers); -console.log("Number of numbers:", numbers.length); - -console.log("Fruits:", fruits); -console.log("Number of fruits:", fruits.length); - -console.log("Vegetables:", vegetables); -console.log("Number of vegetables:", vegetables.length); - -console.log("Animal products:", animalProducts); -console.log("Number of animal products:", animalProducts.length); - -console.log("Web technologies:", webTechs); -console.log("Number of web technologies:", webTechs.length); - -console.log("Countries:", countries); -console.log("Number of countries:", countries.length); -``` - -```sh -Numbers: [0, 3.14, 9.81, 37, 98.6, 100] -Number of numbers: 6 -Fruits: ['banana', 'orange', 'mango', 'lemon'] -Number of fruits: 4 -Vegetables: ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] -Number of vegetables: 5 -Animal products: ['milk', 'meat', 'butter', 'yoghurt'] -Number of animal products: 4 -Web technologies: ['HTML', 'CSS', 'JS', 'React', 'Redux', 'Node', 'MongDB'] -Number of web technologies: 7 -Countries: ['Finland', 'Estonia', 'Denmark', 'Sweden', 'Norway'] -Number of countries: 5 -``` - -- Array puede tener elementos de diferentes tipos de datos - -```js -const arr = [ - "Asabeneh", - 250, - true, - { country: "Finland", city: "Helsinki" }, - { skills: ["HTML", "CSS", "JS", "React", "Python"] }, -]; // arr contiene diferentes tipos de datos -console.log(arr); -``` - -### Creando un array usando split - -Como hemos visto en la sección anterior, podemos dividir un string en diferentes posiciones y podemos cambiar a un array. Veamos los ejemplos a continuación - -```js -let js = "JavaScript"; -const charsInJavaScript = js.split(""); - -console.log(charsInJavaScript); // ["J", "a", "v", "a", "S", "c", "r", "i", "p", "t"] - -let companiesString = "Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon"; -const companies = companiesString.split(","); - -console.log(companies); // ["Facebook", " Google", " Microsoft", " Apple", " IBM", " Oracle", " Amazon"] -let txt = - "I love teaching and empowering people. I teach HTML, CSS, JS, React, Python."; -const words = txt.split(" "); - -console.log(words); -// el texto tiene caracteres especiales piensa cómo puedes obtener solo las palabras -// ["I", "love", "teaching", "and", "empowering", "people.", "I", "teach", "HTML,", "CSS,", "JS,", "React,", "Python"] -``` - -### Acceder a los elementos de un array usando el index - -Accedemos a cada elemento en un array usando su index. El index de un array comienza desde 0. La siguiente imagen muestra claramente el index de cada elemento en un array - -![arr index](../images/array_index.png) - -```js -const fruits = ["banana", "orange", "mango", "lemon"]; -let firstFruit = fruits[0]; // estamos accediendo al primer elemento usando su index - -console.log(firstFruit); // banana - -secondFruit = fruits[1]; -console.log(secondFruit); // orange - -let lastFruit = fruits[3]; -console.log(lastFruit); // lemon -// El último index se puede calcular de la siguiente manera - -let lastIndex = fruits.length - 1; -lastFruit = fruits[lastIndex]; - -console.log(lastFruit); // lemon -``` - -```js -const numbers = [0, 3.14, 9.81, 37, 98.6, 100]; // set of numbers - -console.log(numbers.length); // => para saber el tamaño de la array, que es 6 -console.log(numbers); // -> [0, 3.14, 9.81, 37, 98.6, 100] -console.log(numbers[0]); // -> 0 -console.log(numbers[5]); // -> 100 - -let lastIndex = numbers.length - 1; -console.log(numbers[lastIndex]); // -> 100 -``` - -```js -const webTechs = [ - "HTML", - "CSS", - "JavaScript", - "React", - "Redux", - "Node", - "MongoDB", -]; // Lista de tecnologías web - -console.log(webTechs); // Todos los elementos del array -console.log(webTechs.length); // => para saber el tamaño de la array, que es 7 -console.log(webTechs[0]); // -> HTML -console.log(webTechs[6]); // -> MongoDB - -let lastIndex = webTechs.length - 1; -console.log(webTechs[lastIndex]); // -> MongoDB -``` - -```js -const countries = [ - "Albania", - "Bolivia", - "Canada", - "Denmark", - "Ethiopia", - "Finland", - "Germany", - "Hungary", - "Ireland", - "Japan", - "Kenya", -]; // Lista de países - -console.log(countries); // -> Todas los países del array -console.log(countries[0]); // -> Albania -console.log(countries[10]); // -> Kenya - -let lastIndex = countries.length - 1; -console.log(countries[lastIndex]); // -> Kenya -``` - -```js -const shoppingCart = [ - "Milk", - "Mango", - "Tomato", - "Potato", - "Avocado", - "Meat", - "Eggs", - "Sugar", -]; // Lista de productos alimenticios - -console.log(shoppingCart); // -> todo el carrito de compras en array -console.log(shoppingCart[0]); // -> Milk -console.log(shoppingCart[7]); // -> Sugar - -let lastIndex = shoppingCart.length - 1; -console.log(shoppingCart[lastIndex]); // -> Sugar -``` - -### Modificar elementos de array - -Un array es mutable (modificable). Una vez que un array es creado, podemos modificar el contenido de los elementos del array. - -```js -const numbers = [1, 2, 3, 4, 5]; -numbers[0] = 10; // cambiando 1 en el índice 0 a 10 -numbers[1] = 20; // cambiando 2 en el índice 1 a 20 - -console.log(numbers); // [10, 20, 3, 4, 5] - -const countries = [ - "Albania", - "Bolivia", - "Canada", - "Denmark", - "Ethiopia", - "Finland", - "Germany", - "Hungary", - "Ireland", - "Japan", - "Kenya", -]; - -countries[0] = "Afghanistan"; // Sustitución de Albania por Afganistán -let lastIndex = countries.length - 1; -countries[lastIndex] = "Korea"; // Sustitución de Kenia por Corea -console.log(countries); -``` - -```sh -["Afghanistan", "Bolivia", "Canada", "Denmark", "Ethiopia", "Finland", "Germany", "Hungary", "Ireland", "Japan", "Korea"] -``` - -### Métodos para manipular arrays - -Existen diferentes métodos para manipular un array. Estos son algunos de los métodos disponibles para manejar arrays:_Array, length, concat, indexOf, slice, splice, join, toString, includes, lastIndexOf, isArray, fill, push, pop, shift, unshift_ - -#### Constructor de arrays - -Array:Para crear un array. - -```js -const arr = Array(); // crea un array vacío -console.log(arr); - -const eightEmptyValues = Array(8); // crea ocho valores vacíos -console.log(eightEmptyValues); // [empty x 8] -``` - -#### Creando valores estáticos con fill - -fill: Rellena todos los elementos del array con un valor estático. - -```js -const arr = Array(); // crea un array vacío -console.log(arr); - -const eightXvalues = Array(8).fill("X"); // crea ocho valores de elementos llenos de 'X' -console.log(eightXvalues); // ['X', 'X','X','X','X','X','X','X'] - -const eight0values = Array(8).fill(0); // crea ocho valores de elementos llenos de '0' -console.log(eight0values); // [0, 0, 0, 0, 0, 0, 0, 0] - -const four4values = Array(4).fill(4); // crea 4 valores de elementos llenos de '4' -console.log(four4values); // [4, 4, 4, 4] -``` - -#### Concatenación de arrays usando concat - -concat:Para concatenar dos arrays. - -```js -const firstList = [1, 2, 3]; -const secondList = [4, 5, 6]; -const thirdList = firstList.concat(secondList); - -console.log(thirdList); // [1, 2, 3, 4, 5, 6] -``` - -```js -const fruits = ["banana", "orange", "mango", "lemon"]; // array de fruits -const vegetables = ["Tomato", "Potato", "Cabbage", "Onion", "Carrot"]; // array de vegetables -const fruitsAndVegetables = fruits.concat(vegetables); // concatena los dos arrays - -console.log(fruitsAndVegetables); -``` - -```sh -["banana", "orange", "mango", "lemon", "Tomato", "Potato", "Cabbage", "Onion", "Carrot"] -``` - -#### Obtener la longitud de array - -Length:Para saber el tamaño del array - -```js -const numbers = [1, 2, 3, 4, 5]; -console.log(numbers.length); // -> 5 es el tamaño del array -``` - -#### Obtener el index de un elemento en un array - -indexOf:Para verificar si un elemento existe en un array. Si existe, devuelve el index, de lo contrario devuelve -1. - -```js -const numbers = [1, 2, 3, 4, 5]; - -console.log(numbers.indexOf(5)); // -> 4 -console.log(numbers.indexOf(0)); // -> -1 -console.log(numbers.indexOf(1)); // -> 0 -console.log(numbers.indexOf(6)); // -> -1 -``` - -Comprobar si un elemento existe en un array. - -- Comprobar elementos en una lista - -```js -// vamos a comprobar si existe banana en el array - -const fruits = ["banana", "orange", "mango", "lemon"]; -let index = fruits.indexOf("banana"); // 0 - -if (index === -1) { - console.log("Esta fruta no existe en el array."); -} else { - console.log("Esta fruta existe en el array."); -} -// Esta fruta existe en el array. - -// we can use also ternary here -index === -1 - ? console.log("Esta fruta no existe en el array.") - : console.log("Esta fruta existe en el array."); - -// let us check if an avocado exist in the array -let indexOfAvocado = fruits.indexOf("avocado"); // -1, if the element not found index is -1 -if (indexOfAvocado === -1) { - console.log("Esta fruta no existe en el array."); -} else { - console.log("Esta fruta existe en el array."); -} -// Esta fruta no existe en el array. -``` - -#### Obtener el último index de un elemento en un array - -lastIndexOf: Da la posición del último elemento en el array. Si existe, devuelve el index, de lo contrario, devuelve -1. - -```js -const numbers = [1, 2, 3, 4, 5, 3, 1, 2]; - -console.log(numbers.lastIndexOf(2)); // 7 -console.log(numbers.lastIndexOf(0)); // -1 -console.log(numbers.lastIndexOf(1)); // 6 -console.log(numbers.lastIndexOf(4)); // 3 -console.log(numbers.lastIndexOf(6)); // -1 -``` - -includes:Para verificar si un elemento existe en un array. Si existe, devuelve true, de lo contrario devuelve false. - -```js -const numbers = [1, 2, 3, 4, 5]; - -console.log(numbers.includes(5)); // true -console.log(numbers.includes(0)); // false -console.log(numbers.includes(1)); // true -console.log(numbers.includes(6)); // false - -const webTechs = [ - "HTML", - "CSS", - "JavaScript", - "React", - "Redux", - "Node", - "MongoDB", -]; // Lista de tecnologías web - -console.log(webTechs.includes("Node")); // true -console.log(webTechs.includes("C")); // false -``` - -#### Comprobar un array - -Array.isArray:Para verificar si el tipo de dato en un array - -```js -const numbers = [1, 2, 3, 4, 5]; -console.log(Array.isArray(numbers)); // true - -const number = 100; -console.log(Array.isArray(number)); // false -``` - -#### Convertir array a string - -toString:Convierte un array a string - -```js -const numbers = [1, 2, 3, 4, 5]; -console.log(numbers.toString()); // 1,2,3,4,5 - -const names = ["Asabeneh", "Mathias", "Elias", "Brook"]; -console.log(names.toString()); // Asabeneh,Mathias,Elias,Brook -``` - -#### Unir elementos de un array - -join: Se usa para unir los elementos del array, el argumento que pasamos en el método join se unirá en array y regresará como una cadena. De forma predeterminada, se une con una coma, pero podemos pasar diferentes parámetros de string que se pueden unir entre los elementos. - -```js -const numbers = [1, 2, 3, 4, 5]; -console.log(numbers.join()); // 1,2,3,4,5 - -const names = ["Asabeneh", "Mathias", "Elias", "Brook"]; - -console.log(names.join()); // Asabeneh,Mathias,Elias,Brook -console.log(names.join("")); //AsabenehMathiasEliasBrook -console.log(names.join(" ")); //Asabeneh Mathias Elias Brook -console.log(names.join(", ")); //Asabeneh, Mathias, Elias, Brook -console.log(names.join(" # ")); //Asabeneh # Mathias # Elias # Brook - -const webTechs = [ - "HTML", - "CSS", - "JavaScript", - "React", - "Redux", - "Node", - "MongoDB", -]; // Lista de tecnologías web - -console.log(webTechs.join()); // "HTML,CSS,JavaScript,React,Redux,Node,MongoDB" -console.log(webTechs.join(" # ")); // "HTML # CSS # JavaScript # React # Redux # Node # MongoDB" -``` - -#### Cortar elementos de un array - -Slice: Para cortar varios elementos en el rango. Toma dos parámetros: posición inicial y final. Puede no incluir la posición final - -```js -const numbers = [1, 2, 3, 4, 5]; - -console.log(numbers.slice()); // -> copia todos los elementos -console.log(numbers.slice(0)); // -> copia todos los elementos -console.log(numbers.slice(0, numbers.length)); // copia todos los elementos -console.log(numbers.slice(1, 4)); // -> [2,3,4] // no incluye la posición final -``` - -#### Método splice en un array - -Splice: Toma tres parámetros: posición inicial, número de elementos a eliminar y cantidad de elementos que se agregarán. - -```js -const numbers = [1, 2, 3, 4, 5]; -numbers.splice(); -console.log(numbers); // -> elimina todos los elementos -``` - -```js -const numbers = [1, 2, 3, 4, 5]; -numbers.splice(0, 1); -console.log(numbers); // elimina el primer elemento -``` - -```js -const numbers = [1, 2, 3, 4, 5, 6]; -numbers.splice(3, 3, 7, 8, 9); -console.log(numbers.splice(3, 3, 7, 8, 9)); // -> [1, 2, 3, 7, 8, 9] //elimina tres elementos y reemplaza tres elementos -``` - -#### Agregar elementos a un array usando push - -Push: agrega elementos al final. Para agregar un elemento al final de un array existente, usamos el método push. - -```js -// syntax -const arr = ["item1", "item2", "item3"]; -arr.push("new item"); -console.log(arr); -// ['item1', 'item2','item3','new item'] -``` - -```js -const numbers = [1, 2, 3, 4, 5]; -numbers.push(6); -console.log(numbers); // -> [1,2,3,4,5,6] - -numbers.pop(); // -> eliminar un elemento del final -console.log(numbers); // -> [1,2,3,4,5] -``` - -```js -let fruits = ["banana", "orange", "mango", "lemon"]; -fruits.push("apple"); -console.log(fruits); // ['banana', 'orange', 'mango', 'lemon', 'apple'] - -fruits.push("lime"); -console.log(fruits); // ['banana', 'orange', 'mango', 'lemon', 'apple', 'lime'] -``` - -#### Eliminar el último elemento usando pop - -pop: Elimina el elemento final. - -```js -const numbers = [1, 2, 3, 4, 5]; -numbers.pop(); // -> eliminar un elemento del final -console.log(numbers); // -> [1,2,3,4] -``` - -#### Eliminar elemento al principio - -shift: Eliminación de un elemento de un array al comienzo de un array. - -```js -const numbers = [1, 2, 3, 4, 5]; -numbers.shift(); // -> elimina un elemento del principio -console.log(numbers); // -> [2,3,4,5] -``` - -#### Añade un elemento al inicio - -unshift: Agrega un elemento al inicio del array - -```js -const numbers = [1, 2, 3, 4, 5]; -numbers.unshift(0); // -> Añadir un elemento al inicio -console.log(numbers); // -> [0,1,2,3,4,5] -``` - -#### Invertir orden de un array - -reverse: invertir el orden de un array. - -```js -const numbers = [1, 2, 3, 4, 5]; -numbers.reverse(); // -> reverse array order -console.log(numbers); // [5, 4, 3, 2, 1] - -numbers.reverse(); -console.log(numbers); // [1, 2, 3, 4, 5] -``` - -#### Ordenar elementos en un array - -sort: Ordena los elementos de un array en orden ascendente. Sort toma una función call back, Veremos cómo usamos sort con una función call back en las próximas secciones. - -```js -const webTechs = [ - "HTML", - "CSS", - "JavaScript", - "React", - "Redux", - "Node", - "MongoDB", -]; - -webTechs.sort(); -console.log(webTechs); // ["CSS", "HTML", "JavaScript", "MongoDB", "Node", "React", "Redux"] - -webTechs.reverse(); // after sorting we can reverse it -console.log(webTechs); // ["Redux", "React", "Node", "MongoDB", "JavaScript", "HTML", "CSS"] -``` - -### Array de arrays - -Un array puede almacenar diferentes tipos de datos, incluido un array en sí mismo. Vamos a crear un array de arrays - -```js -const firstNums = [1, 2, 3]; -const secondNums = [1, 4, 9]; - -const arrayOfArray = [ - [1, 2, 3], - [1, 2, 3], -]; -console.log(arrayOfArray[0]); // [1, 2, 3] - -const frontEnd = ["HTML", "CSS", "JS", "React", "Redux"]; -const backEnd = ["Node", "Express", "MongoDB"]; -const fullStack = [frontEnd, backEnd]; -console.log(fullStack); // [["HTML", "CSS", "JS", "React", "Redux"], ["Node", "Express", "MongoDB"]] -console.log(fullStack.length); // 2 -console.log(fullStack[0]); // ["HTML", "CSS", "JS", "React", "Redux"] -console.log(fullStack[1]); // ["Node", "Express", "MongoDB"] -``` - -🌕 Tienes una energía ilimitada. Acabas de completar los desafíos del día 5 y llevas cinco pasos de tu camino hacia la grandeza. Ahora haz algunos ejercicios para tu cerebro y tus músculos. - -## 💻 Ejercicios - -### Ejercicios: Nivel 1 - -```js -const countries = [ - "Albania", - "Bolivia", - "Canada", - "Denmark", - "Ethiopia", - "Finland", - "Germany", - "Hungary", - "Ireland", - "Japan", - "Kenya", -]; - -const webTechs = [ - "HTML", - "CSS", - "JavaScript", - "React", - "Redux", - "Node", - "MongoDB", -]; -``` - -1. Declara un array _vacío_. -2. Declara un array com mas de 5 elementos. -3. Encuentra la longitud de tu array. -4. Obtenga el primer elemento, el elemento del medio y el último elemento de un array. -5. Declara un array llamado _mixedDataTypes_, coloque diferentes tipos de datos en el array y encuentre la longitud del array. El tamaño del array debe ser mayor que 5. -6. Declare un variable array de nombre _itCompanies_ y asignarles valores iniciales Facebook, Google, Microsoft, Apple, IBM, Oracle y Amazon. -7. Imprima el array usando _console.log()_. -8. Imprima el número de empresas en el array. -9. Imprime la primer empresa , la intermedia y la última empresa -10. Imprime cada empresa. -11. Cambie el nombre de cada empresa a mayúsculas uno por uno e imprímalos. -12. Imprime el array como una oración: Facebook, Google, Microsoft, Apple, IBM, Oracle y Amazon son grandes empresas de TI. -13. Compruebe si existe una determinada empresa en el array itCompanies. Si existe, retorna la empresa; de lo contrario, retorna la empresa _no existe_ -14. Filtre las empresas que tienen más de una 'o' sin el método _filter()_ -15. Ordene el array usando el método _sort()_ -16. Invierte la array usando el método _reverse()_ -17. Cortar las primeras 3 empresas del array -18. Cortar las últimas 3 empresas del array -19. Cortar la empresa o empresas intermedias de TI del array -20. Eliminar la primera empresa de TI del array -21. Eliminar la empresa o empresas intermedias de TI del array -22. Elimine la última empresa de TI del array -23. Eliminar todas las empresas de TI - -### Ejercicios: Nivel 2 - -1. Cree un archivo de countries.js separado y almacene el array de países en este archivo, cree un archivo separado web_techs.js y almacene el array de webTechs en este archivo. Acceda a ambos archivos en el archivo main.js -1. Primero elimine todos los signos de puntuación y cambie de string a array y cuente el número de palabras en el array - - ```js - let text = - "I love teaching and empowering people. I teach HTML, CSS, JS, React, Python."; - console.log(words); - console.log(words.length); - ``` - - ```sh - ["I", "love", "teaching", "and", "empowering", "people", "I", "teach", "HTML", "CSS", "JS", "React", "Python"] - - 13 - ``` - -1. En el siguiente carrito de compras agregue, elimine, edite artículos - - ```js - const shoppingCart = ["Milk", "Coffee", "Tea", "Honey"]; - ``` - - - Agregue 'Meat' al comienzo de su carrito de compras si aún no se ha agregado - - Agregue 'Sugar' al final de su carrito de compras si aún no se ha agregado - - Elimine 'Honey' si es alérgico a la miel (honey) - - Modificar Tea a 'Green Tea' - -1. En el array de países, verifique si 'Ethiopia' existe en el array si existe, imprima 'ETHIOPIA'. Si no existe agregar a la lista de países. -1. En el array webTechs, verifique si Sass existe en el array y si existe, imprima 'Sass es un preproceso de CSS'. Si no existe, agregue Sass al array e imprima el array. -1. Concatene las siguientes dos variables y guardelas en una variable fullStack. - - ```js - const frontEnd = ["HTML", "CSS", "JS", "React", "Redux"]; - const backEnd = ["Node", "Express", "MongoDB"]; - - console.log(fullStack); - ``` - - ```sh - ["HTML", "CSS", "JS", "React", "Redux", "Node", "Express", "MongoDB"] - ``` - -### Ejercicios: Nivel 3 - -1. El siguiente es un array de 10 edades de estudiantes: - - ```js - const ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24] - ``` - - - Ordene el array y encuentre la edad mínima y máxima - - Encuentre la edad media (un elemento intermedio o dos elementos intermedios divididos por dos) - - Encuentre la edad promedio (todos los elementos divididos por el número de elementos) - - Encuentre el rango de las edades (max menos min) - - Compare el valor de (mín - promedio) y (máx - promedio), use el método _abs()_ - - 1.Cortar los diez primeros países de la [array de países](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) - -1. Encuentre el país o países de en medio en el [array de países](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) -1. Divide el array de países en dos arrays iguales si es par. Si el array de países no es par, agregue un país más para la primera mitad. - -🎉 ¡Felicitaciones! 🎉 - -[<< Day 4](../dia_04_Condicionales/dia_04_Condicionales.md) | [Day 6 >>](../dia_06_Bucles/dia_06_bucles.md) diff --git a/Spanish/dia_06_Bucles/dia_06_bucles.md b/Spanish/dia_06_Bucles/dia_06_bucles.md deleted file mode 100644 index 70d3c9b..0000000 --- a/Spanish/dia_06_Bucles/dia_06_bucles.md +++ /dev/null @@ -1,481 +0,0 @@ -
-

30 Días de JavaScript: Bucles

- - - - - Twitter Follow - - -Autor: -Asabeneh Yetayeh
- Enero, 2020 -
- -
- -[<< Día 5](../dia_05_Arreglos/dia_05_arreglos.md) | [ Día 7 >>](../dia_07_Funciones/dia_07_funciones.md) - -![Day 6](../images/banners/day_1_6.png) - -- [📔 Día 6](#📔-día-6) - - [Bucles](#bucles) - - [Bucle for](#bucle-for) - - [Bucle while](#bucle-while) - - [Bucle do while](#bucle-do-while) - - [Bucle for of](#bucle-for-of) - - [break](#break) - - [continue](#continue) - - [💻 Ejercicios: Día 6](#💻-ejerciciosdía-6) - - [Ejercicios: Nivel 1](#ejercicios-nivel-1) - - [Ejercicios: Nivel 2](#ejercicios-nivel-2) - - [Ejercicios: Nivel 3](#ejercicios-nivel-3) - -# 📔 Día 6 - -## Bucles - -La mayoría de las actividades que hacemos en la vida están llenas de repeticiones. Imagina que tienes que imprimir de 0 a 100 usando console.log(). Para implementar esta simple tarea, puede tomar de 2 a 5 minutos, este tipo de tarea tediosa y repetitiva se puede llevar a cabo usando un bucle. Si prefieres ver los videos, puedes revisar el [video tutorials](https://www.youtube.com/channel/UCM4xOopkYiPwJqyKsSqL9mw) - -En los lenguajes de programación para realizar tareas repetitivas utilizamos diferentes tipos de bucles. Los siguientes ejemplos son los bucles de uso común en JavaScript y otros lenguajes de programación. - -### Bucle for - -```js -// Estructura del bucle for -for(inicialización, condición, incremento/decremento){ - // el código va aquí -} -``` - -```js -for (let i = 0; i <= 5; i++) { - console.log(i); -} - -// 0 1 2 3 4 5 -``` - -```js -for (let i = 5; i >= 0; i--) { - console.log(i); -} - -// 5 4 3 2 1 0 -``` - -```js -for (let i = 0; i <= 5; i++) { - console.log(`${i} * ${i} = ${i * i}`); -} -``` - -```sh -0 * 0 = 0 -1 * 1 = 1 -2 * 2 = 4 -3 * 3 = 9 -4 * 4 = 16 -5 * 5 = 25 -``` - -```js -const countries = ["Finland", "Sweden", "Denmark", "Norway", "Iceland"]; -const newArr = []; -for (let i = 0; i < countries.length; i++) { - newArr.push(countries[i].toUpperCase()); -} - -// ["FINLAND", "SWEDEN", "DENMARK", "NORWAY", "ICELAND"] -``` - -Agregar todos los elementos en un array - -```js -const numbers = [1, 2, 3, 4, 5]; -let sum = 0; -for (let i = 0; i < numbers.length; i++) { - sum = sum + numbers[i]; // can be shorten, sum += numbers[i] -} - -console.log(sum); // 15 -``` - -Crea un nuevo array basado en el array existente - -```js -const numbers = [1, 2, 3, 4, 5]; -const newArr = []; -let sum = 0; -for (let i = 0; i < numbers.length; i++) { - newArr.push(numbers[i] ** 2); -} - -console.log(newArr); // [1, 4, 9, 16, 25] -``` - -```js -const countries = ["Finland", "Sweden", "Norway", "Denmark", "Iceland"]; -const newArr = []; -for (let i = 0; i < countries.length; i++) { - newArr.push(countries[i].toUpperCase()); -} - -console.log(newArr); // ["FINLAND", "SWEDEN", "NORWAY", "DENMARK", "ICELAND"] -``` - -### Bucle while - -```js -let i = 0; -while (i <= 5) { - console.log(i); - i++; -} - -// 0 1 2 3 4 5 -``` - -### Bucle do while - -```js -let i = 0; -do { - console.log(i); - i++; -} while (i <= 5); - -// 0 1 2 3 4 5 -``` - -### Bucle for of - -Usamos el bucle for of para arrays. Es una forma muy práctica de iterar a través de un array, si no estamos interesados en el index de cada elemento del array. - -```js -for (const element of arr) { - // el código va aquí -} -``` - -```js -const numbers = [1, 2, 3, 4, 5]; - -for (const num of numbers) { - console.log(num); -} - -// 1 2 3 4 5 - -for (const num of numbers) { - console.log(num * num); -} - -// 1 4 9 16 25 - -// sumando todos los números del array -let sum = 0; -for (const num of numbers) { - sum = sum + num; - // también se puede acortar así, sum += num - // después de esto usaremos la sintaxis más corta (+=, -=, *=, /= etc) -} -console.log(sum); // 15 - -const webTechs = [ - "HTML", - "CSS", - "JavaScript", - "React", - "Redux", - "Node", - "MongoDB", -]; - -for (const tech of webTechs) { - console.log(tech.toUpperCase()); -} - -// HTML CSS JAVASCRIPT REACT NODE MONGODB - -for (const tech of webTechs) { - console.log(tech[0]); // obtiene solo la primera letra de cada elemento, H C J R N M -} -``` - -```js -const countries = ["Finland", "Sweden", "Norway", "Denmark", "Iceland"]; -const newArr = []; -for (const country of countries) { - newArr.push(country.toUpperCase()); -} - -console.log(newArr); // ["FINLAND", "SWEDEN", "NORWAY", "DENMARK", "ICELAND"] -``` - -### break - -Break se utiliza para interrumpir un bucle. - -```js -for (let i = 0; i <= 5; i++) { - if (i == 3) { - break; - } - console.log(i); -} - -// 0 1 2 -``` - -El código anterior se detiene si se encuentran 3 en el proceso de iteración. - -### continue - -Usamos la palabra clave _continue_ para omitir ciertas iteraciones. - -```js -for (let i = 0; i <= 5; i++) { - if (i == 3) { - continue; - } - console.log(i); -} - -// 0 1 2 4 5 -``` - -🌕 Tienes una energía ilimitada. Acabas de completar los desafíos del día 6 y llevas seis pasos de tu camino hacia la grandeza. Ahora haz algunos ejercicios para tu cerebro y tus músculos. - -## 💻 Ejercicios:Día 6 - -### Ejercicios: Nivel 1 - -```js -const countries = [ - "Albania", - "Bolivia", - "Canada", - "Denmark", - "Ethiopia", - "Finland", - "Germany", - "Hungary", - "Ireland", - "Japan", - "Kenya", -]; - -const webTechs = [ - "HTML", - "CSS", - "JavaScript", - "React", - "Redux", - "Node", - "MongoDB", -]; - -const mernStack = ["MongoDB", "Express", "React", "Node"]; -``` - -1. Itera de 0 a 10 usando el bucle for, haga lo mismo usando los bucles while y do while -2. Itera 10 to 0 usando el bucle for, haga lo mismo usando los bucles while y do while -3. Itera de 0 a n usando el bucle for -4. Escribe un bucle que haga el siguiente patrón usando console.log(): - - ```js - # - ## - ### - #### - ##### - ###### - ####### - ``` - -5. Usa un bucle para imprimir el siguiente patrón: - - ```sh - 0 x 0 = 0 - 1 x 1 = 1 - 2 x 2 = 4 - 3 x 3 = 9 - 4 x 4 = 16 - 5 x 5 = 25 - 6 x 6 = 36 - 7 x 7 = 49 - 8 x 8 = 64 - 9 x 9 = 81 - 10 x 10 = 100 - ``` - -6. Usando un bucle imprime el siguiente patrón: - - ```sh - i i^2 i^3 - 0 0 0 - 1 1 1 - 2 4 8 - 3 9 27 - 4 16 64 - 5 25 125 - 6 36 216 - 7 49 343 - 8 64 512 - 9 81 729 - 10 100 1000 - ``` - -7. Usa el bucle for para iterar de 0 a 100 e imprima solo números pares -8. Usa el bucle for para iterar de 0 a 100 e imprima solo números impares -9. Usa el bucle for para iterar de 0 a 100 e imprima los solo números primos -10. Usa el bucle for para iterar de 0 a 100 e imprima la suma de todos los números. - - ```sh - La suma de todos los números de 0 a 100 es 5050. - ``` - -11. Usa el bucle para iterar de 0 a 100 e imprimir la suma de todos los pares y la suma de todos los impares. - - ```sh - La suma de todos los pares de 0 a 100 es 2550. Y la suma de todos los impares de 0 a 100 es 2500. - ``` - -12. Usa el bucle para iterar de 0 a 100 e imprimir la suma de todos los pares y la suma de todos los impares. Imprimir suma de pares y suma de impares como un array - - ```sh - [2550, 2500] - ``` - -13. Desarrolla un pequeño script que genera una matriz de 5 números aleatorios -14. Desarrolla un pequeño script que genera una matriz de 5 números aleatorios. Los números debe ser únicos -15. Desarrolla un pequeño script que genera un id aleatorio de seis caracteres: - - ```sh - 5j2khz - ``` - -### Ejercicios: Nivel 2 - -1. Desarrolla un pequeño script que genera un id con cualquier número de caracteres aleatorios: - - ```sh - fe3jo1gl124g - ``` - - ```sh - xkqci4utda1lmbelpkm03rba - ``` - -1. Escribe un script que genere un número hexadecimal aleatorio. - - ```sh - '#ee33df' - ``` - -1. Escribe un script que genere un número de color rgb aleatorio. - - ```sh - rgb(240,180,80) - ``` - -1. Usando el array countries anterior, crea un array como el siguiente. - - ```sh - ["ALBANIA", "BOLIVIA", "CANADA", "DENMARK", "ETHIOPIA", "FINLAND", "GERMANY", "HUNGARY", "IRELAND", "JAPAN", "KENYA"] - ``` - -1. Usando el array countries anterior, crea un array para saber la longitud de cada país. - - ```sh - [7, 7, 6, 7, 8, 7, 7, 7, 7, 5, 5] - ``` - -1. Utiliza el array countries para crear la siguiente array de arrays - - ```sh - [ - ['Albania', 'ALB', 7], - ['Bolivia', 'BOL', 7], - ['Canada', 'CAN', 6], - ['Denmark', 'DEN', 7], - ['Ethiopia', 'ETH', 8], - ['Finland', 'FIN', 7], - ['Germany', 'GER', 7], - ['Hungary', 'HUN', 7], - ['Ireland', 'IRE', 7], - ['Iceland', 'ICE', 7], - ['Japan', 'JAP', 5], - ['Kenya', 'KEN', 5] - ] - ``` - -1. En el array countries anterior, verifica si hay un país que contenga la palabra 'land'. Si hay países que contienen 'land', imprimelo cono array. Si no hay ningún país que contenga la palabra'land', imprima 'Todos estos países no tienen la palabra land'. - - ```sh - ['Finland','Ireland', 'Iceland'] - ``` - -1. En el array countries anterior, verifica si hay un país que termina con una subcadena (substring) 'ia'. Si hay países que terminan con 'ia', imprimelo como un array. Si no hay ningún país que contenga la palabra 'ia', imprime 'Estos países no terminan con ia'. - - ```sh - ['Albania', 'Bolivia','Ethiopia'] - ``` - -1. Usando el array countries anterior, encuentre el país que contiene la mayor cantidad de caracteres. - - ```sh - Ethiopia - ``` - -1. Usando el array countries anterior, encuentre el país que contiene sólo 5 caracteres. - - ```sh - ['Japan', 'Kenya'] - ``` - -1. Encuentra la palabra más larga en el array webTechs -1. Utiliza el array de webTechs para crear la el siguiente array de arrays: - - ```sh - [["HTML", 4], ["CSS", 3],["JavaScript", 10],["React", 5],["Redux", 5],["Node", 4],["MongoDB", 7]] - ``` - -1. Una aplicación creada con MongoDB, Express, React y Node se denomina MERN stack app. Crea el acrónimo MERN usando el array mernStack -1. Iterar a través del array, ["HTML", "CSS", "JS", "React", "Redux", "Node", "Express", "MongoDB"] usando el bucle for o el bucle for of e imprime los elementos. -1. Este es un array de frutas, ['banana', 'orange', 'mango', 'lemon'] invierte el orden usando un bucle sin usar el método reverse(). -1. Imprime todos los elementos del array como se muestra a continuación: - - ```js - const fullStack = [ - ["HTML", "CSS", "JS", "React"], - ["Node", "Express", "MongoDB"], - ]; - ``` - - ```sh - HTML - CSS - JS - REACT - NODE - EXPRESS - MONGODB - ``` - -### Ejercicios: Nivel 3 - -1. Copia el array countries (Evita mutaciones) -1. Los arrays son mutables. Crea una copia del array que no modifique el original. Ordena la copia del array y guárdala en una variable sortedCountries -1. Ordena el array webTechs y el array mernStack -1. Extrae todos los países que contengan la palabra 'land' del [array countries](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) e imprimela como un array -1. Encuentra el país que contiene la mayor cantidad de caracteres en el [array countries](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) -1. Extrae todos los países que contienen la palabra 'land' del [array countries](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) e imprimela como un array -1. Extrae todos los países que contengan solo cuatro caracters del [array countries](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) e impremela como un array -1. Extrae todos los paíse que contengan dos o más palabras del [array countries](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) e imprimela como un array -1. Invertir el [array countries](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) y poner en mayúscula cada país y almacenalo en un array - -🎉 ¡FELICITACIONES! 🎉 - -[<< Día 5](../dia_05_Arreglos/dia_05_arreglos.md) | [Día 7 >>](../dia_07_Funciones/dia_07_funciones.md) diff --git a/Spanish/dia_07_Funciones/dia_07_funciones.md b/Spanish/dia_07_Funciones/dia_07_funciones.md deleted file mode 100644 index aaf820f..0000000 --- a/Spanish/dia_07_Funciones/dia_07_funciones.md +++ /dev/null @@ -1,702 +0,0 @@ -
-

30 Días de JavaScript: Funciones

- - - - - Twitter Follow - - -Autor: -Asabeneh Yetayeh
- Enero, 2020 -
- -
- -[<< Day 6](../dia_06_Bucles/dia_06_bucles.md) | [Día 8 >>](../dia_08_Objetos/dia_08_objetos.md) - -![Thirty Days Of JavaScript](../images/banners/day_1_7.png) - -- [📔 Día 7](#📔-día-7) - - [Funciones](#funciones) - - [Función declarativa](#función-declarativa) - - [Función sin parámetros y return](#función-sin-parámetros-y-return) - - [Función que retorna un valor](#función-que-retorna-un-valor) - - [Función con un parámetro](#función-con-un-parámetro) - - [Función con dos parámetros](#función-con-dos-parámetros) - - [Función con muchos parámetros](#función-con-muchos-parámetros) - - [Función con número ilimitado de parámetros](#función-con-número-ilimitado-de-parámetros) - - [Número ilimitado de parámetros en una función regular](#número-ilimitado-de-parámetros-en-una-función-regular) - - [Número ilimitado de parámetros en una función flecha](#número-ilimitado-de-parámetros-en-una-función-flecha) - - [Función anónima](#función-anónima) - - [Función de expresión](#función-de-expresión) - - [Funciones de autoinvocación](#función-de-autoinvocación) - - [Función flecha](#función-flecha) - - [Función con parámetros por defecto](#función-con-parámetros-por-defecto) - - [Función declarativa versus función flecha](#función-declarativa-versus-función-flecha) - - [💻 Ejercicios](#💻-ejercicios) - - [Ejercicios: Nivel 1](#ejercicios-nivel-1) - - [Ejercicios: Nivel 2](#ejercicios-nivel-2) - - [Ejercicios: Nivel 3](#ejercicios-nivel-3) - -# 📔 Día 7 - -## Funciones - -Hasta ahora hemos visto muchas funciones JavaScript integradas. En esta sección, nos centraremos en las funciones personalizadas. ¿Qué es una función? Antes de comenzar a hacer funciones, comprendamos ¿Qué es una función? y ¿Por qué necesitamos una función? - -Una función es un bloque reutilizable de código o declaraciones de programación diseñadas para realizar una determinada tarea. - -Una función se declara mediante la palabra clave function seguida de un nombre, seguido de paréntesis (). Un paréntesis puede tomar un parámetro. Si una función toma un parámetro, se llamará con un argumento. Una función también puede tomar un parámetro predeterminado. Para almacenar datos en una función, una función debe devolver ciertos tipos de datos. Para obtener el valor llamamos o invocamos a la función. - -La función hace código: - -- limpio y fácil de leer -- reutilizable -- fácil de probar - -Una función se puede declarar o crear de un par de maneras: - -- _Función declarativa_ -- _Función de expresión_ -- _Función anonima_ -- _Función flecha_ - -### Función declarativa - -Veamos cómo declaramos una función y cómo llamar a una función. - -```js -//declaramos una función sin un parámetro -function functionName() { - // el código va aquí -} -functionName(); // llamando a la función por su nombre con paréntesis -``` - -### Función sin parámetros y return - -La función se puede declarar sin un parámetro. - -**Ejemplo:** - -```js -// función sin parámetros. La función eleva al cuadrado un número -function square() { - let num = 2; - let sq = num * num; - console.log(sq); -} - -square(); // 4 - -// función sin parámetro -function addTwoNumbers() { - let numOne = 10; - let numTwo = 20; - let sum = numOne + numTwo; - - console.log(sum); -} - -addTwoNumbers(); // una función tiene que ser llamada por su nombre para ser ejecutada -``` - -```js -function printFullName() { - let firstName = "Asabeneh"; - let lastName = "Yetayeh"; - let space = " "; - let fullName = firstName + space + lastName; - console.log(fullName); -} - -printFullName(); // llamando a una función -``` - -### Función que retorna un valor - -La función también puede devolver valores, si una función no devuelve valores, el valor de la función no está definido. Escribamos las funciones anteriores con return. A partir de ahora, retornaremos el valor a una función en lugar de imprimirlo. - -```js -function printFullName() { - let firstName = "Asabeneh"; - let lastName = "Yetayeh"; - let space = " "; - let fullName = firstName + space + lastName; - return fullName; -} -console.log(printFullName()); -``` - -```js -function addTwoNumbers() { - let numOne = 2; - let numTwo = 3; - let total = numOne + numTwo; - return total; -} - -console.log(addTwoNumbers()); -``` - -### Función con un parámetro - -En una función podemos pasar diferentes tipos de datos(number, string, boolean, object, function) como un parámetro. - -```js -// función con un parámetro -function functionName(parm1) { - //el código va aquí -} -functionName(parm1); // durante la llamada o la invocación es necesario un argumento - -function areaOfCircle(r) { - let area = Math.PI * r * r; - return area; -} - -console.log(areaOfCircle(10)); // debe ser llamado con un argumento - -function square(number) { - return number * number; -} - -console.log(square(10)); -``` - -### Función con dos parámetros - -```js -// función con dos parámetros -function functionName(parm1, parm2) { - //el código va aquí -} -functionName(parm1, parm2); // durante la llamada o invocación se necesitan dos argumentos -// la función sin parámetros no recibe entrada, así que hagamos una función con parámetros -function sumTwoNumbers(numOne, numTwo) { - let sum = numOne + numTwo; - console.log(sum); -} -sumTwoNumbers(10, 20); // llamando a la función -// si una función no es retorna esta no almacena datos, por lo que debe retornar - -function sumTwoNumbers(numOne, numTwo) { - let sum = numOne + numTwo; - return sum; -} - -console.log(sumTwoNumbers(10, 20)); -function printFullName(firstName, lastName) { - return `${firstName} ${lastName}`; -} -console.log(printFullName("Asabeneh", "Yetayeh")); -``` - -### Función con muchos parámetros - -```js -// función con múltiples parámetros -function functionName(parm1, parm2, parm3,...){ - //el código va aquí -} -functionName(parm1,parm2,parm3,...) // durante la llamada o la invocación necesita tres argumentos - - -// esta función toma un array como un parámetro y suma los números en el array -function sumArrayValues(arr) { - let sum = 0; - for (let i = 0; i < arr.length; i++) { - sum = sum + arr[i]; - } - return sum; -} -const numbers = [1, 2, 3, 4, 5]; - //llamada a la función -console.log(sumArrayValues(numbers)); - - - const areaOfCircle = (radius) => { - let area = Math.PI * radius * radius; - return area; - } -console.log(areaOfCircle(10)) - -``` - -### Función con número ilimitado de parámetros - -A veces no sabemos cuántos argumentos va a pasar el usuario. Por lo tanto, debemos saber cómo escribir una función que pueda tomar un número ilimitado de argumentos. La forma en que lo hacemos tiene una diferencia significativa entre una función declarativa (función regular) y una función flecha. Veamos ejemplos tanto en la función declarativa como en la función flecha. - -#### Número ilimitado de parámetros en una función regular - -Una función declarativa proporciona una función con alcance de argumentos array como objeto. Se puede acceder a cualquier cosa que pasemos como argumento en la función desde el objeto de argumentos dentro de las funciones. Veamos un ejemplo - -```js -// Accedemos a los argumentos del objeto -​ -function sumAllNums() { - console.log(arguments) -} - -sumAllNums(1, 2, 3, 4) -// Arguments(4) [1, 2, 3, 4, callee: ƒ, Symbol(Symbol.iterator): ƒ] - -``` - -```js -// declaración -​ -function sumAllNums() { - let sum = 0 - for (let i = 0; i < arguments.length; i++) { - sum += arguments[i] - } - return sum -} - -console.log(sumAllNums(1, 2, 3, 4)) // 10 -console.log(sumAllNums(10, 20, 13, 40, 10)) // 93 -console.log(sumAllNums(15, 20, 30, 25, 10, 33, 40)) // 173 -``` - -#### Número ilimitado de parámetros en una función flecha - -La función flecha no tiene el objeto de alcance de los argumentos -Para implementar una función que toma un número ilimitado de argumentos en una función de flecha, usamos el operador de propagación seguido de cualquier nombre de parámetro. Se puede acceder a cualquier elemento que hayamos pasado como argumento en la función como array en la función de flecha. Veamos un ejemplo - -```js -// Accedemos a los argumentos del objeto -​ -const sumAllNums = (...args) => { - // console.log(arguments), objeto de argumentos no encontrado en la función flecha - // en su lugar, usamos un parámetro seguido de un operador de propagación (...) - console.log(args) -} - -sumAllNums(1, 2, 3, 4) -// [1, 2, 3, 4] - -``` - -```js -// declaración -​ -const sumAllNums = (...args) => { - let sum = 0 - for (const element of args) { - sum += element - } - return sum -} - -console.log(sumAllNums(1, 2, 3, 4)) // 10 -console.log(sumAllNums(10, 20, 13, 40, 10)) // 93 -console.log(sumAllNums(15, 20, 30, 25, 10, 33, 40)) // 173 -``` - -### Función anónima - -Función anónima o sin nombre - -```js -const anonymousFun = function () { - console.log("Soy una función anónima y mi valor se almacena en anonymousFun"); -}; -``` - -### Función de expresión - -Las funciones de expresión son funciones anónimas. Después creamos una función sin nombre y la asignamos a una variable. Para retornar un valor de la función debemos llamar a la variable. Mira el ejemplo de abajo. - -```js -// Function expression -const square = function (n) { - return n * n; -}; - -console.log(square(2)); // -> 4 -``` - -### Función de autoinvocación - -Las funciones de autoinvocación son funciones anónimas que no necesitan ser llamadas para devolver un valor. - -```js -(function (n) { - console.log(n * n); -})(2); // 4, pero en lugar de solo imprimir si queremos regresar y almacenar los datos, hacemos lo que se muestra a continuación - -let squaredNum = (function (n) { - return n * n; -})(10); - -console.log(squaredNum); -``` - -### Función flecha - -La función flecha es una alternativa para escribir una función, sin embargo, la función declarativa y la función flecha tienen algunas diferencias menores. - -La función flecha usa una flecha en lugar de la palabra clave _function_ para declarar una función. Veamos tanto la función declarativa como la función flecha. - -```js -// Así es como escribimos una función normal o declarativa -// Cambiemos esta función de declarativa a una función flecha -function square(n) { - return n * n; -} - -console.log(square(2)); // 4 - -const square = (n) => { - return n * n; -}; - -console.log(square(2)); // -> 4 - -// si tenemos solo una línea en el bloque de código, se puede escribir de la siguiente manera, return explícito -const square = (n) => n * n; // -> 4 -``` - -```js -const changeToUpperCase = (arr) => { - const newArr = []; - for (const element of arr) { - newArr.push(element.toUpperCase()); - } - return newArr; -}; - -const countries = ["Finland", "Sweden", "Norway", "Denmark", "Iceland"]; -console.log(changeToUpperCase(countries)); - -// ["FINLAND", "SWEDEN", "NORWAY", "DENMARK", "ICELAND"] -``` - -```js -const printFullName = (firstName, lastName) => { - return `${firstName} ${lastName}`; -}; - -console.log(printFullName("Asabeneh", "Yetayeh")); -``` - -La función anterior solo tiene la declaración de return, por lo tanto, podemos retornar explícitamente de la siguiente manera. - -```js -const printFullName = (firstName, lastName) => `${firstName} ${lastName}`; - -console.log(printFullName("Asabeneh", "Yetayeh")); -``` - -### Función con parámetros por defecto - -A veces, pasamos valores predeterminados a los parámetros, cuando invocamos la función, si no pasamos un argumento, se usará el valor predeterminado. Tanto la función declarativa como la función flecha pueden tener un valor o valores predeterminados. - -```js -// sintaxis -// Declarando una función -function functionName(param = value) { - //código -} - -// Llamando una función -functionName(); -functionName(arg); -``` - -**Example:** - -```js -function greetings(name = "Peter") { - let message = `${name}, welcome to 30 Days Of JavaScript!`; - return message; -} - -console.log(greetings()); -console.log(greetings("Asabeneh")); -``` - -```js -function generateFullName(firstName = "Asabeneh", lastName = "Yetayeh") { - let space = " "; - let fullName = firstName + space + lastName; - return fullName; -} - -console.log(generateFullName()); -console.log(generateFullName("David", "Smith")); -``` - -```js -function calculateAge(birthYear, currentYear = 2019) { - let age = currentYear - birthYear; - return age; -} - -console.log("Age: ", calculateAge(1819)); -``` - -```js -function weightOfObject(mass, gravity = 9.81) { - let weight = mass * gravity + " N"; // el valor tiene que ser cambiado a string primero - return weight; -} - -console.log("Weight of an object in Newton: ", weightOfObject(100)); // 9.81 es la gravedad en la superficie de la tierra -console.log("Weight of an object in Newton: ", weightOfObject(100, 1.62)); // gravedad en la superficie de la luna -``` - -Veamos cómo escribimos las funciones anteriores con funciones flecha. - -```js -// sintaxis -// declarando una función -const functionName = (param = value) => { - //código -}; - -// Llamando a la función -functionName(); -functionName(arg); -``` - -**Example:** - -```js -const greetings = (name = "Peter") => { - let message = name + ", welcome to 30 Days Of JavaScript!"; - return message; -}; - -console.log(greetings()); -console.log(greetings("Asabeneh")); -``` - -```js -const generateFullName = (firstName = "Asabeneh", lastName = "Yetayeh") => { - let space = " "; - let fullName = firstName + space + lastName; - return fullName; -}; - -console.log(generateFullName()); -console.log(generateFullName("David", "Smith")); -``` - -```js -const calculateAge = (birthYear, currentYear = 2019) => currentYear - birthYear; -console.log("Age: ", calculateAge(1819)); -``` - -```js -const weightOfObject = (mass, gravity = 9.81) => mass * gravity + " N"; - -console.log("Weight of an object in Newton: ", weightOfObject(100)); // 9.81 es la gravedad en la superficie de la tierra -console.log("Weight of an object in Newton: ", weightOfObject(100, 1.62)); // gravedad en la superficie de la luna -``` - -### Función declarativa versus función flecha - -Será cubierto en otra sección. - -🌕 Tienes una energía ilimitada. Acabas de completar los desafíos del día 7 y llevas siete pasos de tu camino hacia la grandeza. Ahora haz algunos ejercicios para tu cerebro y tus músculos. - -## 💻 Ejercicios - -### Ejercicios: Nivel 1 - -1. Declare una función _fullName_ e imprima su nombre completo. -2. Declare una función _fullName_ y ahora toma firstName, lastName como parámetro y retorna su nombre completo. -3. Declare una función _addNumbers_ que toma dos parámetros y retorna la suma de ambos. -4. El área de un rectángulo se calcula de la siguiente manera: _area = length x width_. Escribe una función _areaOfRectangle_ que calcule el área de un rectángulo. -5. El perímetro de un rectángulo se calcula de la siguiente manera: _perimeter= 2x(length + width)_. Escribe una función _perimeterOfRectangle_ que calcule el perímetro de un rectángulo. -6. El volumen de un prisma rectangular se calcula de la siguiente manera: _volume = length x width x height_. Escribe una función _volumeOfRectPrism_ que calcule el volumen de un prisma. -7. El área de un círculo se calcula de la siguiente manera: _area = π x r x r_. Escribe una función _areaOfCircle_ que calcule el área de un círculo. -8. La circunferencia de un círculo se calcula de la siguiente manera: _circumference = 2πr_. Escribe una función _circumOfCircle_ que calcule la circunferencia de un círculo. -9. La densidad de una sustancia se calcula de la siguiente manera:_density= mass/volume_. Escribe una función _density_ que calcule la densidad de una sustancia. -10. La velocidad se calcula dividiendo el total de la distancia recorrida por un objeto en movimiento entre el tiempo total. Escribe una función que calcule la velocidad de un objeto en movimiento, _speed_. -11. El peso de una sustancia se calcula de la siguiente manera: _weight = mass x gravity_. Escribe una función _weight_ que calcule el peso de una sustancia. -12. La temperatura en °C se puede convertir a °F usando esta fórmula: _°F = (°C x 9/5) + 32_. Escribe una función _convertCelsiusToFahrenheit_ que convierta °C a °F. -13. El índice de masa corporal (IMC) se calcula de la siguiente manera: _imc = peso en Kg / (altura x altura) en m2_. Escribe una función que calcule _imc_. El IMC se utiliza para definir de forma amplia diferentes grupos de peso en adultos de 20 años o más. Compruebe si una persona tiene un _peso bajo, peso normal, con sobrepeso_ u _obeso_ según la información que se proporciona a continuación. - - - Se aplican los mismos parámetros de grupos tanto a hombres como a mujeres. - - _Peso bajo_: IMC inferior a 18,5 - - _Peso normal_: IMC de 18,5 a 24,9 - - _Sobrepeso_: IMC de 25 a 29,9 - - _Obeso_: IMC es 30 o más - -14. Escribe una función llamada _checkSeason_, toma un parámetro de mes y retorna la estación: Otoño, Invierno, Primavera o Verano. -15. Math.max retorna su argumento más grande. Escriba una función findMax que tome tres argumentos y devuelva su máximo sin usar el método Math.max. - - ```js - console.log(findMax(0, 10, 5)); - 10; - console.log(findMax(0, -10, -2)); - 0; - ``` - -### Ejercicios: Nivel 2 - -1. La ecuación lineal se calcula de la siguiente manera: _ax + by + c = 0_. Escribe una función que calcule el valor de una ecuación lineal, _solveLinEquation_. -1. La ecuación cuadrática se calcula de la siguiente manera: _ax2 + bx + c = 0_. Escribe una función que calcule el valor o los valores de una ecuación cuadrática, _solveQuadEquation_. - - ```js - console.log(solveQuadratic()); // {0} - console.log(solveQuadratic(1, 4, 4)); // {-2} - console.log(solveQuadratic(1, -1, -2)); // {2, -1} - console.log(solveQuadratic(1, 7, 12)); // {-3, -4} - console.log(solveQuadratic(1, 0, -4)); //{2, -2} - console.log(solveQuadratic(1, -1, 0)); //{1, 0} - ``` - -1. Declare una función llamada _printArray_. Toma un array como parámetro e imprime cada valor del array. -1. Declare una función llamada _showDateTime_ que muestre la hora en este formato: 01/08/2020 04:08 usando el objeto Date. - - ```sh - showDateTime() - 08/01/2020 04:08 - ``` - -1. Declare una función llamada _swapValues_. Esta función intercambia el valor de x a y. - - ```js - swapValues(3, 4); // x => 4, y=>3 - swapValues(4, 5); // x = 5, y = 4 - ``` - -1. Declare una función llamada _reverseArray_. Toma un array como parámetro y retorna el array invertido (no use el método reverse()). - - ```js - console.log(reverseArray([1, 2, 3, 4, 5])); - //[5, 4, 3, 2, 1] - console.log(reverseArray(["A", "B", "C"])); - //['C', 'B', 'A'] - ``` - -1. Declare una función llamada _capitalizeArray_. Toma un array como parámetro y retorna el array - capitalizedarray. -1. Declare una función llamada _addItem_. Toma un elemento de paŕametro y retorna un array después de agregar el un elemento. -1. Declare una función llamada _removeItem_. Toma como parámetro un index y retorna un array después de eleminar el elemento con ese index. -1. Declare una función llamada _sumOfNumbers_. Toma un número como parámetro y suma todos los números en ese rango. -1. Declare una función llamada _sumOfOdds_. Toma un parámetro numérico y suma todos los números impares en ese rango. -1. Declare una función llamada _sumOfEven_. Toma un parámetro numérico y suma todos los números pares en ese rango. -1. Declare una función llamada _evensAndOdds_ . Toma un entero positivo como parámetro y cuenta el número de pares e impares. - - ```sh - evensAndOdds(100); - El número de impares son 50. - El número de pares es 51. - ``` - -1. Escriba una función que tome cualquier número de argumentos y retorne la suma de los argumentos - - ```js - sum(1, 2, 3); // -> 6 - sum(1, 2, 3, 4); // -> 10 - ``` - -1. Escriba una función _randomUserIp_ que genere una ip de usuario aleatoria. -1. Escriba una función _randomMacAddress_ que genere una dirección mac aleatoria. -1. Declare una función llamada _randomHexaNumberGenerator_. Cuando se llama a esta función, genera un número hexadecimal aleatorio. La función retorna el número hexadecimal. - - ```sh - console.log(randomHexaNumberGenerator()); - '#ee33df' - ``` - -1. Declare una función llamada _userIdGenerator_. Cuando se llama a esta función, genera un id de siete caracteres. La función devuelve el id. - - ```sh - console.log(userIdGenerator()); - 41XTDbE - ``` - -### Ejercicios: Nivel 3 - -1. Modifique la función _userIdGenerator_. Declare una función de nombre _userIdGeneratedByUser_. No toma ningún parámetro pero toma dos entradas usando prompt(). Una de las entradas es la cantidad de caracteres y la segunda entrada es la cantidad de ID que se supone que se generarán. - - ```sh - userIdGeneratedByUser() - 'kcsy2 - SMFYb - bWmeq - ZXOYh - 2Rgxf - ' - userIdGeneratedByUser() - '1GCSgPLMaBAVQZ26 - YD7eFwNQKNs7qXaT - ycArC5yrRupyG00S - UbGxOFI7UXSWAyKN - dIV0SSUTgAdKwStr - ' - ``` - -1. Escriba una función llamada _rgbColorGenerator_ que genera colores rgb - - ```sh - rgbColorGenerator() - rgb(125,244,255) - ``` - -1. Escriba una función **_arrayOfHexaColors_** que retorna cualquier cantidad de colores hexadecimales en un array. -1. Escriba una función **_arrayOfRgbColors_** que retorna cualquier cantidad de colores RGB en un array. -1. Escriba una función **_convertHexaToRgb_** que convierta el color hexa a rgb y retorna un color rgb. -1. Escriba una función **_convertRgbToHexa_** que convierta rgb a color hexa y retorna un color hexa. -1. Escriba una función **_generateColors_** que pueda generar cualquier número de colores hexa o rgb. - - ```js - console.log(generateColors("hexa", 3)); // ['#a3e12f', '#03ed55', '#eb3d2b'] - console.log(generateColors("hexa", 1)); // '#b334ef' - console.log(generateColors("rgb", 3)); // ['rgb(5, 55, 175)', 'rgb(50, 105, 100)', 'rgb(15, 26, 80)'] - console.log(generateColors("rgb", 1)); // 'rgb(33,79, 176)' - ``` - -1. Llame a su función _shuffleArray_, toma un array como parámetro y devuelve un array mezclada -1. Llame a su función _factorial_, toma un número entero como parámetro y devuelve un factorial del número. -1. Llame a su función _isEmpty_, toma un parámetro y verifica si está vacío o no. -1. Llame a su función _sum_, toma cualquier cantidad de argumentos y devuelve la suma. -1. Escriba una función llamada _sumOfArrayItems_, toma un array como parámetro y retorna la suma de todos los elementos. Compruebe si todos los elementos de la matriz son tipos de números. Si no, dé una respuesta razonable. -1. Escribe una función llamada _average_, toma un array como parámetro y retorna el promedio de los elementos. Compruebe si todos los elementos de la matriz son tipos de números. Si no, dé una respuesta adecuada. -1. Escriba una función llamada _modifyArray_ que tome un array como parámetro y modifique el quinto elemento del array y retorna el array. Si la longitud del array es inferior a cinco, retorna 'elemento no encontrado'. - - ```js - console.log(modifyArray(['Avocado', 'Tomato', 'Potato','Mango', 'Lemon','Carrot']); - ``` - - ```sh - ['Avocado', 'Tomato', 'Potato','Mango', 'LEMON', 'Carrot'] - ``` - - ```js - console.log(modifyArray(['Google', 'Facebook','Apple', 'Amazon','Microsoft', 'IBM']); - ``` - - ```sh - ['Google', 'Facebook','Apple', 'Amazon','MICROSOFT', 'IBM'] - ``` - - ```js - console.log(modifyArray(['Google', 'Facebook','Apple', 'Amazon']); - ``` - - ```sh - 'Not Found' - ``` - -1. Escribe una función llamada _isPrime_, que verifica si un número es un número primo. -1. Escriba una función que verifique si todos los elementos son únicos en un array. -1. Escriba una función que verifique si todos los elementos de un array son del mismo tipo de datos. -1. El nombre de las variables de JavaScript no admite caracteres o símbolos especiales, excepto \$ o \_. Escriba una función **isValidVariable** que verifique si una variable es válida o inválida. -1. Escriba una función que devuelva un array de siete números aleatorios en un rango de 0-9. Todos los números deben ser únicos. - - ```js - sevenRandomNumbers()[(1, 4, 5, 7, 9, 8, 0)]; - ``` - -1. Escriba una función llamada reverseCountries, toma el array de países y primero copia el array y retorna el array original invertido - 🎉 ¡FELICITACIONES! 🎉 - -[<< Day 6](../dia_06_Bucles/dia_06_bucles.md) | [Day 8 >>](../dia_08_Objetos/dia_08_objetos.md) diff --git a/Spanish/dia_08_Objetos/dia_08_objetos.md b/Spanish/dia_08_Objetos/dia_08_objetos.md deleted file mode 100644 index 88a1e9d..0000000 --- a/Spanish/dia_08_Objetos/dia_08_objetos.md +++ /dev/null @@ -1,592 +0,0 @@ -
-

30 Días de JavaScript: Objetos

- - - - - Twitter Follow - - -Autor: -Asabeneh Yetayeh
- Enero, 2020 -
- -
- -[<< Día 7](../dia_07_Funciones/dia_07_funciones.md) | [Día 9 >>](../dia_09_Funciones_De_Orden_Superior/dia_09_funciones_de_orden_superior.md) - -![Thirty Days Of JavaScript](../images/banners/day_1_8.png) - -- [📔 Día 8](#📔-día-8) - - [Scope](#scope-alcance) - - [Objeto Global Window](#objeto-global-window) - - [Global scope](#global-scope) - - [Local scope](#local-scope) - - [📔 Objeto](#📔-objeto) - - [Crear un objeto vacío](#crear-un-objeto-vacío) - - [Crear un objeto con valores](#crear-un-objeto-con-valores) - - [Obtener valores de un objeto](#obtener-valores-de-un-objeto) - - [Crear métodos de objetos](#crear-métodos-de-objetos) - - [Establecer una nueva clave para un objeto](#establecer-una-nueva-clave-para-un-objeto) - - [Métodos de los objetos](#métodos-de-los-objetos) - - [Obtención de claves de objetos mediante Object.keys()](#obtención-de-claves-de-objetos-mediante-objectkeys) - - [Obtención de valores de objetos mediante Object.values()](#obtención-de-valores-de-objetos-mediante-objectvalues) - - [Obtención de claves y valores de objetos mediante Object.entries()](#obtención-de-claves-y-valores-de-objetos-mediante-objectentries) - - [Comprobación de propiedades mediante hasOwnProperty()](#comprobación-de-propiedades-mediante-hasownproperty) - - [💻 Ejercicios](#💻-ejercicios) - - [Ejercicios: Nivel 1](#ejercicios-nivel-1) - - [Ejercicios: Nivel 2](#ejercicios-nivel-2) - - [Ejercicios: Nivel 3](#ejercicios-nivel-3) - -# 📔 Día 8 - -## Scope (alcance) - -La variable es la parte fundamental en la programación. Declaramos variables para almacenar diferentes tipos de datos. Para declarar una variable usamos la palabra clave _var_, _let_, y _const_. Una variable puede declararse en diferentes scope. En esta sección, veremos el alcance de las variables, el alcance de las variables cuando usamos var o let. -El scope de las variables pueden ser: - -- Global -- Local - -Las variables pueden ser declaradas con un scope global o local. Veremos tanto el scope global como el local. Cualquier cosa declarada sin let, var o const tiene un alcance global. - -Imaginemos que tenemos un fichero scope.js. - -### Objeto Global Window - -Sin usar console.log() abre tu navegador y comprueba, verás el valor de a y b si escribes a o b en el navegador. Eso significa que a y b ya están disponibles en window - -```js -//scope.js -a = "JavaScript"; // declarar una variable sin let o const la hace disponible en el objeto window y esta se encuentra en cualquier lugar -b = 10; // es una variable de scope global y se encuentra en el objeto ventana -function letsLearnScope() { - console.log(a, b); - if (true) { - console.log(a, b); - } -} -console.log(a, b); // accesibles -``` - -### Global scope - -Una variable declarada globalmente puede ser accedida en cualquier lugar del mismo archivo. Pero el término global es relativo. Puede ser global al archivo o puede ser global relativo a algún bloque de códigos. - -```js -//scope.js -let a = "JavaScript"; // es un scope global que se encontrará en cualquier parte de este archivo -let b = 10; // es un scope global que se encontrará en cualquier parte de este archivo -function letsLearnScope() { - console.log(a, b); // JavaScript 10, accesible - if (true) { - let a = "Python"; - let b = 100; - console.log(a, b); // Python 100 - } - console.log(a, b); -} -letsLearnScope(); -console.log(a, b); // JavaScript 10, accesible -``` - -### Local scope - -Una variable declarada como local sólo puede ser accedida en determinados bloques de código. - -- Scope del bloque -- Scope de la función - -```js -//scope.js -let a = "JavaScript"; // es un scope global que se encontrará en cualquier parte de este archivo -let b = 10; // es un scope global que se encontrará en cualquier parte de este archivo -// Scope de la función -function letsLearnScope() { - console.log(a, b); // JavaScript 10, accesible - let value = false; - // Scope del bloque - if (true) { - // podemos acceder desde la función y fuera de la función pero - // las variables declaradas dentro del if no serán accesibles fuera del bloque if - let a = "Python"; - let b = 20; - let c = 30; - let d = 40; - value = !value; - console.log(a, b, c, value); // Python 20 30 true - } - // no podemos acceder a c porque el scope de c es sólo el bloque if - console.log(a, b, value); // JavaScript 10 true -} -letsLearnScope(); -console.log(a, b); // JavaScript 10, accesible -``` - -Ahora, usted tiene una comprensión del scope. Una variable declarada con _var_ sólo tiene ámbito de función, pero una variable declarada con _let_ o _const_ tiene scope de bloque (bloque de función, bloque if, bloque de bucle, etc). El bloque en JavaScript es un código entre dos llaves({}). - -```js -//scope.js -function letsLearnScope() { - var gravity = 9.81; - console.log(gravity); -} -// console.log(gravity), Uncaught ReferenceError: la gravedad no está definida - -if (true) { - var gravity = 9.81; - console.log(gravity); // 9.81 -} -console.log(gravity); // 9.81 - -for (var i = 0; i < 3; i++) { - console.log(i); // 0, 1, 2 -} -console.log(i); // 3 -``` - -En ES6 y superiores existe _let_ y _const_, por lo que no sufrirás la insidia de _var_. Cuando usamos _let_ nuestra variable tiene alcance de bloque y no infectara otras partes de nuestro código. - -```js -//scope.js -function letsLearnScope() { - // puedes usar let o const, pero la gravedad es constante prefiero usar const - const gravity = 9.81; - console.log(gravity); -} -// console.log(gravity), Uncaught ReferenceError: la gravedad no está definida - -if (true) { - const gravity = 9.81; - console.log(gravity); // 9.81 -} -// console.log(gravity), Uncaught ReferenceError: la gravedad no está definida - -for (let i = 0; i < 3; i++) { - console.log(i); // 0, 1, 2 -} -// console.log(i), Uncaught ReferenceError: i no está definida -``` - -El ámbito _let_ y _const_ es el mismo. La diferencia es sólo la reasignación. No podemos cambiar o reasignar el valor de la variable `const`. Te sugiero encarecidamente que utilices _let_ y _const_, utilizando _let_ y _const_ escribirás un código limpio y evitarás errores difíciles de depurar. Como regla general, puedes usar _let_ para cualquier valor que cambie, _const_ para cualquier valor constante, y para un array, objeto, función de flecha y expresión de función. - -## 📔 Objeto - -Todo puede ser un objeto y los objetos tienen propiedades y las propiedades tienen valores, por lo que un objeto es un par clave-valor. El orden de la clave no está reservado, o no hay orden. Para crear un objeto literal, utilizamos dos llaves. - -### Crear un objeto vacío - -Un objeto vacío - -```js -const person = {}; -``` - -### Crear un objeto con valores - -Ahora, el objeto persona tiene las propiedades firstName, lastName, age, location, skills y isMarried. El valor de las propiedades o claves puede ser una cadena, un número, un booleano, un objeto, null, undefined o una función. - -Veamos algunos ejemplos de objetos. Cada clave tiene un valor en el objeto. - -```js -const rectangle = { - length: 20, - width: 20, -}; -console.log(rectangle); // {length: 20, width: 20} - -const person = { - firstName: "Asabeneh", - lastName: "Yetayeh", - age: 250, - country: "Finland", - city: "Helsinki", - skills: [ - "HTML", - "CSS", - "JavaScript", - "React", - "Node", - "MongoDB", - "Python", - "D3.js", - ], - isMarried: true, -}; -console.log(person); -``` - -### Obtener valores de un objeto - -Podemos acceder a los valores del objeto utilizando dos métodos: - -- usando . seguido del nombre de la clave si el nombre de la clave es de una sola palabra -- utilizando corchetes y comillas - -```js -const person = { - firstName: "Asabeneh", - lastName: "Yetayeh", - age: 250, - country: "Finland", - city: "Helsinki", - skills: [ - "HTML", - "CSS", - "JavaScript", - "React", - "Node", - "MongoDB", - "Python", - "D3.js", - ], - getFullName: function () { - return `${this.firstName}${this.lastName}`; - }, - "phone number": "+3584545454545", -}; - -// acceder a los valores mediante . -console.log(person.firstName); -console.log(person.lastName); -console.log(person.age); -console.log(person.location); // undefined - -// se puede acceder al valor utilizando corchetes y el nombre de la clave -console.log(person["firstName"]); -console.log(person["lastName"]); -console.log(person["age"]); -console.log(person["age"]); -console.log(person["location"]); // undefined - -// por ejemplo, para acceder al número de teléfono sólo utilizamos el método del corchete -console.log(person["phone number"]); -``` - -### Crear métodos de objetos - -Ahora, el objeto persona tiene las propiedades getFullName. El getFullName es una función dentro del objeto persona y lo llamamos un método del objeto. La palabra clave _this_ se refiere al objeto mismo. Podemos utilizar la palabra _this_ para acceder a los valores de diferentes propiedades del objeto. No podemos usar una función de flecha como método de objeto porque la palabra this se refiere a window dentro de una función de flecha en lugar del objeto mismo. Ejemplo de objeto: - -```js -const person = { - firstName: "Asabeneh", - lastName: "Yetayeh", - age: 250, - country: "Finland", - city: "Helsinki", - skills: [ - "HTML", - "CSS", - "JavaScript", - "React", - "Node", - "MongoDB", - "Python", - "D3.js", - ], - getFullName: function () { - return `${this.firstName} ${this.lastName}`; - }, -}; - -console.log(person.getFullName()); -// Asabeneh Yetayeh -``` - -### Establecer una nueva clave para un objeto - -Un objeto es una estructura de datos mutable y podemos modificar el contenido de un objeto después de su creación. - -Establecer una nueva clave en un objeto - -```js -const person = { - firstName: "Asabeneh", - lastName: "Yetayeh", - age: 250, - country: "Finland", - city: "Helsinki", - skills: [ - "HTML", - "CSS", - "JavaScript", - "React", - "Node", - "MongoDB", - "Python", - "D3.js", - ], - getFullName: function () { - return `${this.firstName} ${this.lastName}`; - }, -}; -person.nationality = "Ethiopian"; -person.country = "Finland"; -person.title = "teacher"; -person.skills.push("Meteor"); -person.skills.push("SasS"); -person.isMarried = true; - -person.getPersonInfo = function () { - let skillsWithoutLastSkill = this.skills - .splice(0, this.skills.length - 1) - .join(", "); - let lastSkill = this.skills.splice(this.skills.length - 1)[0]; - - let skills = `${skillsWithoutLastSkill}, and ${lastSkill}`; - let fullName = this.getFullName(); - let statement = `${fullName} is a ${this.title}.\nHe lives in ${this.country}.\nHe teaches ${skills}.`; - return statement; -}; -console.log(person); -console.log(person.getPersonInfo()); -``` - -```sh -Asabeneh Yetayeh is a teacher. -He lives in Finland. -He teaches HTML, CSS, JavaScript, React, Node, MongoDB, Python, D3.js, Meteor, and SasS. -``` - -### Métodos de los objetos - -Existen diferentes métodos para manipular un objeto. Veamos algunos de los métodos disponibles. - -_Object.assign_: Para copiar un objeto sin modificar el objeto original - -```js -const person = { - firstName: "Asabeneh", - age: 250, - country: "Finland", - city: "Helsinki", - skills: ["HTML", "CSS", "JS"], - title: "teacher", - address: { - street: "Heitamienkatu 16", - pobox: 2002, - city: "Helsinki", - }, - getPersonInfo: function () { - return `I am ${this.firstName} and I live in ${this.city}, ${this.country}. I am ${this.age}.`; - }, -}; - -//Métodos de objetos: Object.assign, Object.keys, Object.values, Object.entries -//hasOwnProperty - -const copyPerson = Object.assign({}, person); -console.log(copyPerson); -``` - -#### Obtención de claves de objetos mediante Object.keys() - -_Object.keys_: Para obtener las claves o propiedades de un objeto como un array - -```js -const keys = Object.keys(copyPerson); -console.log(keys); //['firstName', 'age', 'country','city', 'skills','title', 'address', 'getPersonInfo'] -const address = Object.keys(copyPerson.address); -console.log(address); //['street', 'pobox', 'city'] -``` - -#### Obtención de valores de objetos mediante Object.values() - -_Object.values_:Para obtener los valores de un objeto como un array - -```js -const values = Object.values(copyPerson); -console.log(values); -``` - -#### Obtención de claves y valores de objetos mediante Object.entries() - -_Object.entries_:Para obtener las claves y valores de un array - -```js -const entries = Object.entries(copyPerson); -console.log(entries); -``` - -#### Comprobación de propiedades mediante hasOwnProperty() - -_hasOwnProperty_: Para comprobar si una clave o propiedad específica existe en un objeto - -```js -console.log(copyPerson.hasOwnProperty("name")); -console.log(copyPerson.hasOwnProperty("score")); -``` - -🌕 Eres asombroso. Ahora, estás súper cargado con el poder de los objetos. Acabas de completar los desafíos del día 8 y llevas 8 pasos de tu camino a la grandeza. Ahora haz algunos ejercicios para tu cerebro y para tus músculos. - -## 💻 Ejercicios - -### Ejercicios: Nivel 1 - -1. Crear un objeto vacío llamado dog -1. Imprime el objeto dog en la consola -1. Añade las propiedades name, legs, color, age y bark para el objeto dog. La propiedad bark es un método que devuelve _woof woof_ -1. Obtener name, legs, color, age y el valor de bark del objeto dog -1. Establecer nuevas propiedades al objeto dog: breed, getDogInfo - -### Ejercicios: Nivel 2 - -1. Encuentra a la persona que tiene muchas habilidades en el objeto de los usuarios. -1. Contar los usuarios conectados, contar los usuarios que tienen más de 50 puntos del siguiente objeto. - - ````js - const users = { - Alex: { - email: 'alex@alex.com', - skills: ['HTML', 'CSS', 'JavaScript'], - age: 20, - isLoggedIn: false, - points: 30 - }, - Asab: { - email: 'asab@asab.com', - skills: ['HTML', 'CSS', 'JavaScript', 'Redux', 'MongoDB', 'Express', 'React', 'Node'], - age: 25, - isLoggedIn: false, - points: 50 - }, - Brook: { - email: 'daniel@daniel.com', - skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'], - age: 30, - isLoggedIn: true, - points: 50 - }, - Daniel: { - email: 'daniel@alex.com', - skills: ['HTML', 'CSS', 'JavaScript', 'Python'], - age: 20, - isLoggedIn: false, - points: 40 - }, - John: { - email: 'john@john.com', - skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node.js'], - age: 20, - isLoggedIn: true, - points: 50 - }, - Thomas: { - email: 'thomas@thomas.com', - skills: ['HTML', 'CSS', 'JavaScript', 'React'], - age: 20, - isLoggedIn: false, - points: 40 - }, - Paul: { - email: 'paul@paul.com', - skills: ['HTML', 'CSS', 'JavaScript', 'MongoDB', 'Express', 'React', 'Node'], - age: 20, - isLoggedIn: false, - points: 40 - } - }``` - - ```` - -1. Encontrar personas que sean desarrolladores MERN stack del objeto de los usuarios -1. Establezca su nombre en el objeto usuarios sin modificar el objeto usuarios original -1. Obtener todas las claves o propiedades del objeto usuarios -1. Obtener todos los valores del objeto usuarios -1. Utilice el objeto países para imprimir el nombre del país, la capital, la población y los idiomas. - -### Ejercicios: Nivel 3 - -1. Crea un objeto literal llamado _personAccount_. Tiene las propiedades _firstName, lastName, incomes, expenses_ y tiene los metodos _totalIncome, totalExpense, accountInfo,addIncome, addExpense_ y _accountBalance_. Incomes es un conjunto de ingresos y su descripción y expenses es un conjunto de ingresos y su descripción. - -2. \*\*\*\* Preguntas:2, 3 y 4 se basan en los siguientes dos arrays: users y products () - -```js -const users = [ - { - _id: "ab12ex", - username: "Alex", - email: "alex@alex.com", - password: "123123", - createdAt: "08/01/2020 9:00 AM", - isLoggedIn: false, - }, - { - _id: "fg12cy", - username: "Asab", - email: "asab@asab.com", - password: "123456", - createdAt: "08/01/2020 9:30 AM", - isLoggedIn: true, - }, - { - _id: "zwf8md", - username: "Brook", - email: "brook@brook.com", - password: "123111", - createdAt: "08/01/2020 9:45 AM", - isLoggedIn: true, - }, - { - _id: "eefamr", - username: "Martha", - email: "martha@martha.com", - password: "123222", - createdAt: "08/01/2020 9:50 AM", - isLoggedIn: false, - }, - { - _id: "ghderc", - username: "Thomas", - email: "thomas@thomas.com", - password: "123333", - createdAt: "08/01/2020 10:00 AM", - isLoggedIn: false, - }, -]; - -const products = [ - { - _id: "eedfcf", - name: "mobile phone", - description: "Huawei Honor", - price: 200, - ratings: [ - { userId: "fg12cy", rate: 5 }, - { userId: "zwf8md", rate: 4.5 }, - ], - likes: [], - }, - { - _id: "aegfal", - name: "Laptop", - description: "MacPro: System Darwin", - price: 2500, - ratings: [], - likes: ["fg12cy"], - }, - { - _id: "hedfcg", - name: "TV", - description: "Smart TV:Procaster", - price: 400, - ratings: [{ userId: "fg12cy", rate: 5 }], - likes: ["fg12cy"], - }, -]; -``` - -Imagina que estás obteniendo la colección de usuarios anterior de una base de datos MongoDB. -a. Crear una función llamada signUp que permita al usuario añadirse a la colección. Si el usuario existe, informar al usuario que ya tiene una cuenta. - b. Crear una función llamada signIn que permita al usuario iniciar sesión en la aplicación - -3. El array de productos tiene tres elementos y cada uno de ellos tiene seis propiedades. - a. Crear una función llamada rateProduct que califique el producto - b. Crear una función llamada averageRating que calcule la valoración media de un producto - -4. Crear una función llamada likeProduct. Esta función ayuda a dar un like al producto. Si no le gusta eliminar el like y si le gusta darle like - -🎉 ¡FELICITACIONES! 🎉 - -[<< Día 7](../dia_07_Funciones/dia_07_funciones.md) | [Día 9 >>](../dia_09_Funciones_De_Orden_Superior/dia_09_funciones_de_orden_superior.md) diff --git a/Spanish/dia_09_Funciones_De_Orden_Superior/dia_09_funciones_de_orden_superior.md b/Spanish/dia_09_Funciones_De_Orden_Superior/dia_09_funciones_de_orden_superior.md deleted file mode 100644 index 6e6ccf8..0000000 --- a/Spanish/dia_09_Funciones_De_Orden_Superior/dia_09_funciones_de_orden_superior.md +++ /dev/null @@ -1,707 +0,0 @@ -
-

30 Días De JavaScript: Función De Orden Superior

- - - - - Twitter Follow - - -Autor: -Asabeneh Yetayeh
- Enero, 2020 -
- -
- -[<< Día 8](../dia_08_Objetos/dia_08_objetos.md) | [Día 10 >>](../10_Day_Sets_and_Maps/10_day_Sets_and_Maps.md) - -![Day 5](../images/banners/day_1_9.png) - -- [Día 9](#día-9) - - [Función De Orden Superior](#función-de-orden-superior) - - [Callback](#callback) - - [Retornar una función](#retornar-una-función) - - [Configuración de tiempo](#configuración-de-tiempo) - - [Configuración del intervalo mediante la función setInterval](#configuración-del-intervalo-mediante-la-función-setinterval) - - [Configurar tiempo mediante un setTimeout](#configurar-tiempo-mediante-un-settimeout) - - [Programación funcional](#programación-funcional) - - [forEach](#foreach) - - [map](#map) - - [filter](#filter) - - [reduce](#reduce) - - [every](#every) - - [find](#find) - - [findIndex](#findindex) - - [some](#some) - - [sort](#sort) - - [Ordenar los valores strings](#ordenar-los-valores-strings) - - [Ordenar valores numéricos](#ordenar-valores-numéricos) - - [Ordenar arrays de objetos](#ordenar-arrays-de-objetos) - - [💻 Ejercicios](#💻-ejercicios) - - [Ejercicios: Nivel 1](#ejercicios-nivel-1) - - [Ejercicios: Nivel 2](#ejercicios-nivel-2) - - [Ejercicios: Nivel 3](#ejercicios-nivel-3) - -# Día 9 - -## Función De Orden Superior - -Las funciones de orden superior son funciones que toman otra función como parámetro o retorna una función como valor. La función que se pasa como parámetro se llama callback. - -### Callback - -Un callback es una función que puede ser pasada como parámetro a otra función. Véase el ejemplo siguiente. - -```js -// una función callback, el nombre de la función puede ser cualquier nombre -const callback = (n) => { - return n ** 2 -} -​ -// función que toma otra función como callback -function cube(callback, n) { - return callback(n) * n -} -​ -console.log(cube(callback, 3)) -``` - -### Retornar una función - -Las funciones de orden superior retorna la función como valor -​ - -```js -// Función de orden superior que devuelve otra función -const higherOrder = (n) => { - const doSomething = (m) => { - const doWhatEver = (t) => { - return 2 * n + 3 * m + t; - }; - return doWhatEver; - }; - return doSomething; -}; -console.log(higherOrder(2)(3)(10)); -``` - -Veamos dónde utilizamos las funciones de callback. Por ejemplo, el método _forEach_ utiliza callback. - -```js -const numbers = [1, 2, 3, 4, 5]; -const sumArray = (arr) => { - let sum = 0; - const callback = function (element) { - sum += element; - }; - arr.forEach(callback); - return sum; -}; -console.log(sumArray(numbers)); -``` - -```sh -15 -``` - -El ejemplo anterior puede simplificarse como el siguiente: - -```js -const numbers = [1, 2, 3, 4] -​ -const sumArray = arr => { - let sum = 0 - arr.forEach(function(element) { - sum += element - }) - return sum - -} -console.log(sumArray(numbers)) -``` - -```sh -15 -``` - -### Configuración de tiempo - -En JavaScript podemos ejecutar algunas actividades en un determinado intervalo de tiempo o podemos programar (esperar) algún tiempo para ejecutar algunas actividades. - -- setInterval -- setTimeout - -#### Configuración del intervalo mediante la función setInterval - -In JavaScript, we use setInterval higher order function to do some activity continuously with in some interval of time. El método global setInterval toma una función callback y una duración como parámetro. La duración está en milisegundos y la llamada de retorno siempre será llamada en ese intervalo de tiempo. - -```js -// sintaxis -function callback() { - // el código va aquí -} -setInterval(callback, duration); -``` - -```js -function sayHello() { - console.log("Hello"); -} -setInterval(sayHello, 1000); // imprime hola cada segundo, 1000ms es 1s -``` - -#### Configurar tiempo mediante un setTimeout - -En JavaScript, utilizamos la función de orden superior setTimeout para ejecutar alguna acción en algún momento en el futuro. El método global setTimeout toma una función callback y una duración como parámetro. La duración está en milisegundos y el callback espera esa cantidad de tiempo. - -```js -// sintaxis -function callback() { - // el código va aquí -} -setTimeout(callback, duration); // duración en milliseconds -``` - -```js -function sayHello() { - console.log("Hello"); -} -setTimeout(sayHello, 2000); // imprime hola después de esperar 2 segundos. -``` - -## Programación funcional - -En lugar de escribir un bucle regular, la última versión de JavaScript introdujo un montón de métodos incorporados que pueden ayudarnos a resolver problemas complicados. - -Instead of writing regular loop, latest version of JavaScript introduced lots of built in methods which can help us to solve complicated problems. Todos los métodos incorporados toman la función callback. En esta sección, veremos _forEach_, _map_, _filter_, _reduce_, _find_, _every_, _some_, y _sort_. - -### forEach - -_forEach_: Iterar los elementos de un array. Utilizamos _forEach_ sólo con arrays. Toma una función callback con elementos, parámetro de índice y el propio array. El índice y el array son opcionales. - -```js -arr.forEach(function (element, index, arr) { - console.log(index, element, arr); -}); -// El código anterior puede escribirse utilizando la función de flecha -arr.forEach((element, index, arr) => { - console.log(index, element, arr); -}); -// El código anterior puede escribirse utilizando la función de flecha y return explícito -arr.forEach((element, index, arr) => console.log(index, element, arr)); -``` - -```js -let sum = 0; -const numbers = [1, 2, 3, 4, 5]; -numbers.forEach((num) => console.log(num)); -console.log(sum); -``` - -```sh -1 -2 -3 -4 -5 -``` - -```js -let sum = 0; -const numbers = [1, 2, 3, 4, 5]; -numbers.forEach((num) => (sum += num)); - -console.log(sum); -``` - -```sh -15 -``` - -```js -const countries = ["Finland", "Denmark", "Sweden", "Norway", "Iceland"]; -countries.forEach((element) => console.log(element.toUpperCase())); -``` - -```sh -FINLAND -DENMARK -SWEDEN -NORWAY -ICELAND -``` - -### map - -_map_: Iterar los elementos de un array y modificar los elementos del mismo. Toma una función callback con elementos, índice , parámetro del array y devuelve un nuevo array. - -```js -const modifiedArray = arr.map(function (element, index, arr) { - return element; -}); -``` - -```js -/*Función flecha y return explícito -const modifiedArray = arr.map((element,index) => element); -*/ -//Ejemplo -const numbers = [1, 2, 3, 4, 5]; -const numbersSquare = numbers.map((num) => num * num); - -console.log(numbersSquare); -``` - -```sh -[1, 4, 9, 16, 25] -``` - -```js -const names = ["Asabeneh", "Mathias", "Elias", "Brook"]; -const namesToUpperCase = names.map((name) => name.toUpperCase()); -console.log(namesToUpperCase); -``` - -```sh -['ASABENEH', 'MATHIAS', 'ELIAS', 'BROOK'] -``` - -```js -const countries = [ - "Albania", - "Bolivia", - "Canada", - "Denmark", - "Ethiopia", - "Finland", - "Germany", - "Hungary", - "Ireland", - "Japan", - "Kenya", -]; -const countriesToUpperCase = countries.map((country) => country.toUpperCase()); -console.log(countriesToUpperCase); - -/* -// Función flecha -const countriesToUpperCase = countries.map((country) => { - return country.toUpperCase(); -}) -//Función flecha de return explícita -const countriesToUpperCase = countries.map(country => country.toUpperCase()); -*/ -``` - -```sh -['ALBANIA', 'BOLIVIA', 'CANADA', 'DENMARK', 'ETHIOPIA', 'FINLAND', 'GERMANY', 'HUNGARY', 'IRELAND', 'JAPAN', 'KENYA'] -``` - -```js -const countriesFirstThreeLetters = countries.map((country) => - country.toUpperCase().slice(0, 3) -); -``` - -```sh - ["ALB", "BOL", "CAN", "DEN", "ETH", "FIN", "GER", "HUN", "IRE", "JAP", "KEN"] -``` - -### filter - -_Filter_: Filtra los elementos que cumplen las condiciones de filtrado y devuelve un nuevo array. - -```js -//Filtrar los países que contienen land -const countriesContainingLand = countries.filter((country) => - country.includes("land") -); -console.log(countriesContainingLand); -``` - -```sh -['Finland', 'Ireland'] -``` - -```js -const countriesEndsByia = countries.filter((country) => country.endsWith("ia")); -console.log(countriesEndsByia); -``` - -```sh -['Albania', 'Bolivia','Ethiopia'] -``` - -```js -const countriesHaveFiveLetters = countries.filter( - (country) => country.length === 5 -); -console.log(countriesHaveFiveLetters); -``` - -```sh -['Japan', 'Kenya'] -``` - -```js -const scores = [ - { name: "Asabeneh", score: 95 }, - { name: "Lidiya", score: 98 }, - { name: "Mathias", score: 80 }, - { name: "Elias", score: 50 }, - { name: "Martha", score: 85 }, - { name: "John", score: 100 }, -]; - -const scoresGreaterEighty = scores.filter((score) => score.score > 80); -console.log(scoresGreaterEighty); -``` - -```sh -[{name: 'Asabeneh', score: 95}, { name: 'Lidiya', score: 98 },{name: 'Martha', score: 85},{name: 'John', score: 100}] -``` - -### reduce - -_reduce_: Reduce toma una función callback. La función callback toma como parámetro el acumulador, el valor actual y opcional el valor inicial y retorna un único valor. Es una buena práctica definir un valor inicial para el valor del acumulador. Si no especificamos este parámetro, por defecto el acumulador obtendrá el `primer valor` del array. Si nuestro array es un _array vacío_, entonces `Javascript` lanzará un error. - -```js -arr.reduce((acc, cur) => { - // algunas operaciones van aquí antes de devolver un valor - return; -}, initialValue); -``` - -```js -const numbers = [1, 2, 3, 4, 5]; -const sum = numbers.reduce((acc, cur) => acc + cur, 0); - -console.log(sum); -``` - -```js -15; -``` - -### every - -_every_: Comprueba si todos los elementos son similares en un aspecto. Devuelve un booleano - -```js -const names = ["Asabeneh", "Mathias", "Elias", "Brook"]; -const areAllStr = names.every((name) => typeof name === "string"); // ¿Son todas strings? - -console.log(areAllStr); -``` - -```sh -true -``` - -```js -const bools = [true, true, true, true]; -const areAllTrue = bools.every((b) => b === true); // ¿Son todas true? - -console.log(areAllTrue); // true -``` - -```sh -true - -``` - -### find - -_find_: Retorna el primer elemento que cumple la condición - -```js -const ages = [24, 22, 25, 32, 35, 18]; -const age = ages.find((age) => age < 20); - -console.log(age); -``` - -```js -18; -``` - -```js -const names = ["Asabeneh", "Mathias", "Elias", "Brook"]; -const result = names.find((name) => name.length > 7); -console.log(result); -``` - -```sh -Asabeneh -``` - -```js -const scores = [ - { name: "Asabeneh", score: 95 }, - { name: "Mathias", score: 80 }, - { name: "Elias", score: 50 }, - { name: "Martha", score: 85 }, - { name: "John", score: 100 }, -]; - -const score = scores.find((user) => user.score > 80); -console.log(score); -``` - -```sh -{ name: "Asabeneh", score: 95 } -``` - -### findIndex - -_findIndex_: Retorna la posición del primer elemento que cumple la condición - -```js -const names = ["Asabeneh", "Mathias", "Elias", "Brook"]; -const ages = [24, 22, 25, 32, 35, 18]; - -const result = names.findIndex((name) => name.length > 7); -console.log(result); // 0 - -const age = ages.findIndex((age) => age < 20); -console.log(age); // 5 -``` - -### some - -_some_: Comprueba si algunos de los elementos son similares en un aspecto. Retorna un booleano - -```js -const names = ["Asabeneh", "Mathias", "Elias", "Brook"]; -const bools = [true, true, true, true]; - -const areSomeTrue = bools.some((b) => b === true); - -console.log(areSomeTrue); //true -``` - -```js -const areAllStr = names.some((name) => typeof name === "number"); // ¿Son todas strings ? -console.log(areAllStr); // false -``` - -### sort - -_sort_: El método "sort" ordena los elementos del array de forma ascendente o descendente. Por defecto, el método **_sort()_** ordena los valores como strings. Esto funciona bien para los elementos del array de strings pero no para los números. Si los valores numéricos se ordenan como strings y nos da un resultado erróneo. El método de Sort modifica el array original. Se recomienda copiar los datos originales antes de empezar a utilizar el método _sort_. - -#### Ordenar los valores strings - -```js -const products = ["Milk", "Coffee", "Sugar", "Honey", "Apple", "Carrot"]; -console.log(products.sort()); // ['Apple', 'Carrot', 'Coffee', 'Honey', 'Milk', 'Sugar'] -//Ahora la matriz original de productos también está ordenada -``` - -#### Ordenar valores numéricos - -Como puede ver en el ejemplo de abajo, el 100 fue el primero después de ser clasificado en orden ascendente. Ordenar convierte los elementos en string , ya que '100' y otros números comparados, 1 que el principio del string '100' se convirtió en el más pequeño. Para evitar esto, utilizamos una función de callback de comparación dentro del método sort, que devuelve un negativo, un cero o un positivo. - -```js -const numbers = [9.81, 3.14, 100, 37]; -// El uso del método sort para ordenar los elementos numéricos proporciona un resultado erróneo. -console.log(numbers.sort()); //[100, 3.14, 37, 9.81] -numbers.sort(function (a, b) { - return a - b; -}); - -console.log(numbers); // [3.14, 9.81, 37, 100] - -numbers.sort(function (a, b) { - return b - a; -}); -console.log(numbers); //[100, 37, 9.81, 3.14] -``` - -#### Ordenar arrays de objetos - -Siempre que ordenamos objetos en un array, utilizamos la clave del objeto para comparar. Veamos el siguiente ejemplo. - -```js -objArr.sort(function (a, b) { - if (a.key < b.key) return -1; - if (a.key > b.key) return 1; - return 0; -}); - -// o - -objArr.sort(function (a, b) { - if (a["key"] < b["key"]) return -1; - if (a["key"] > b["key"]) return 1; - return 0; -}); - -const users = [ - { name: "Asabeneh", age: 150 }, - { name: "Brook", age: 50 }, - { name: "Eyob", age: 100 }, - { name: "Elias", age: 22 }, -]; -users.sort((a, b) => { - if (a.age < b.age) return -1; - if (a.age > b.age) return 1; - return 0; -}); -console.log(users); // ordenados de forma ascendente -// [{…}, {…}, {…}, {…}] -``` - -🌕 Lo estás haciendo muy bien. Nunca te rindas porque las grandes cosas llevan su tiempo. Acabas de completar el día 9 de desafíos y llevas nueve pasos de tu camino hacia la grandeza. Ahora haz algunos ejercicios para tu cerebro y para tus músculos. - -## 💻 Ejercicios - -### Ejercicios: Nivel 1 - -```js -const countries = ["Finland", "Sweden", "Denmark", "Norway", "IceLand"]; -const names = ["Asabeneh", "Mathias", "Elias", "Brook"]; -const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; -const products = [ - { product: "banana", price: 3 }, - { product: "mango", price: 6 }, - { product: "potato", price: " " }, - { product: "avocado", price: 8 }, - { product: "coffee", price: 10 }, - { product: "tea", price: "" }, -]; -``` - -1. Explique la diferencia entre **_forEach, map, filter, and reduce_**. -2. Defina una función callback antes de utilizarla en forEach, map, filter o reduce. -3. Utiliza **_forEach_** para mostrar con console.log cada país del array de países. -4. Utiliza **_forEach_** para mostrar con console.log cada nombre del array de nombres. -5. Utiliza **_forEach_** para mostrar con console.log cada número del array de números. -6. Utiliza **_map_** para crear un nuevo array cambiando cada país a mayúsculas en el array de países. -7. Utilice **_map_** para crear un array de longitudes de países a partir del array de países. -8. Usa **_map_** para crear un nuevo array cambiando cada número al cuadrado en el array de números. -9. Utilice **_map_** para cambiar cada nombre a mayúsculas en el array de nombres. -10. Utilice **_map_** para asignar el array de productos a sus correspondientes precios. -11. Utilice **_filter_** para filtrar los países que contienen **_land_**. -12. Utilice **_filter_** para filtrar los países que tienen seis caracteres. -13. Utilice **_filter_** para filtrar los países que contengan seis letras o más en el array de países. -14. Utilice **_filter_** para filtrar los países que empiezan por "E"; -15. Utilice **_filter_** para filtrar sólo los precios con valores. -16. Declara una función llamada getStringLists que toma un array como parámetro y devuelve un array sólo con elementos string. -17. Usa **_reduce_** para sumar todos los números del array de números. -18. Utiliza **_reduce_** para concatenar todos los países y producir esta frase: **_Estonia, Finland, Sweden, Denmark, Norway, y IceLand son países del norte de Europa_** -19. Explique la diferencia entre **_some_** y **_every_** -20. Utilice **_some_** para comprobar si la longitud de algunos nombres es superior a siete en el array de nombres. -21. Utilice **_every_** para comprobar si todos los países contienen la palabra land. -22. Explique la diferencia entre **_find_** y **_findIndex_**. -23. Utilice **_find_** para encontrar el primer país que contenga sólo seis letras en el array de países. -24. Utilice **_findIndex_** para encontrar la posición del primer país que contenga sólo seis letras en el array de países. -25. Utilice **_findIndex_** para encontrar la posición de **_Norway_** si no existe en el array obtendrá -1. -26. Utilice **_findIndex_** para encontrar la posición de **_Russia_** si no existe en el array obtendrá -1. - -### Ejercicios: Nivel 2 - -1. Encuentre el precio total de los productos encadenando dos o más iteradores de matrices (por ejemplo, arr.map(callback).filter(callback).reduce(callback)). -1. Encuentre la suma del precio de los productos usando sólo reduce(callback)). -1. Declara una función llamada **_categorizeCountries_** que retorna un array de países que tienen algún patrón común (encuentras el array de países en este repositorio como countries.js(ej 'land', 'ia', 'island','stan')). -1. Cree una función que retorne un array de objetos, que es la letra y el número de veces que la letra usa para empezar el nombre de un país. -1. Declara una función **_getFirstTenCountries_** y retorna un array de diez países. Utiliza diferente programación funcional para trabajar en el array countries.js. -1. Declara una función **_getLastTenCountries_** que devuelve los últimos diez países del array de países. -1. Encuentre qué _letra_ se utiliza muchas _veces_ como inicial de un nombre de país del array de países (ej. Finland, Fiji, France etc) - -### Ejercicios: Nivel 3 - -1. Utiliza la información de los países, en la carpeta de datos. Ordena los países por nombre, por capital, por población -1. \*\*\* Encuentre las 10 lenguas más habladas: - - ````js - // El resultado debería ser el siguiente - console.log(mostSpokenLanguages(countries, 10)) - [ - {country: 'English',count:91}, - {country: 'French',count:45}, - {country: 'Arabic',count:25}, - {country: 'Spanish',count:24}, - {country:'Russian',count:9}, - {country:'Portuguese', count:9}, - {country:'Dutch',count:8}, - {country:'German',count:7}, - {country:'Chinese',count:5}, - {country:'Swahili',count:4} - ] - - // El resultado debería ser el siguiente - console.log(mostSpokenLanguages(countries, 3)) - [ - {country: 'English',count: 91}, - {country: 'French',count: 45}, - {country: 'Arabic',count: 25}, - ]``` - - ```` - -1. \*\*\* Utilice el archivo countries_data.js para crear una función que cree los diez países más poblados. - - ````js - console.log(mostPopulatedCountries(countries, 10)) - - [ - {country: 'China', population: 1377422166}, - {country: 'India', population: 1295210000}, - {country: 'United States of America', population: 323947000}, - {country: 'Indonesia', population: 258705000}, - {country: 'Brazil', population: 206135893}, - {country: 'Pakistan', population: 194125062}, - {country: 'Nigeria', population: 186988000}, - {country: 'Bangladesh', population: 161006790}, - {country: 'Russian Federation', population: 146599183}, - {country: 'Japan', population: 126960000} - ] - - console.log(mostPopulatedCountries(countries, 3)) - [ - {country: 'China', population: 1377422166}, - {country: 'India', population: 1295210000}, - {country: 'United States of America', population: 323947000} - ] - ``` - - ```` - -1. \*\*\* Intenta desarrollar un programa que calcule la medida de tendencia central de una muestra(mean, median, mode) y medida de la variabilidad(range, variance, standard deviation). Además de esas medidas, encuentre el mínimo, el máximo, el recuento, el porcentaje y la distribución de frecuencias de la muestra. Puede crear un objeto llamado estadísticas y crear todas las funciones que hacen cálculos estadísticos como método para el objeto estadísticas. Comprueba el resultado que aparece a continuación. - - ```js - const ages = [31, 26, 34, 37, 27, 26, 32, 32, 26, 27, 27, 24, 32, 33, 27, 25, 26, 38, 37, 31, 34, 24, 33, 29, 26] - - console.log('Count:', statistics.count()) // 25 - console.log('Sum: ', statistics.sum()) // 744 - console.log('Min: ', statistics.min()) // 24 - console.log('Max: ', statistics.max()) // 38 - console.log('Range: ', statistics.range() // 14 - console.log('Mean: ', statistics.mean()) // 30 - console.log('Median: ',statistics.median()) // 29 - console.log('Mode: ', statistics.mode()) // {'mode': 26, 'count': 5} - console.log('Variance: ',statistics.var()) // 17.5 - console.log('Standard Deviation: ', statistics.std()) // 4.2 - console.log('Variance: ',statistics.var()) // 17.5 - console.log('Frequency Distribution: ',statistics.freqDist()) # [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)] - ``` - - ```sh - console.log(statistics.describe()) - Count: 25 - Sum: 744 - Min: 24 - Max: 38 - Range: 14 - Mean: 30 - Median: 29 - Mode: (26, 5) - Variance: 17.5 - Standard Deviation: 4.2 - Frequency Distribution: [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)] - ``` - -🎉 ¡FELICITACIONES! 🎉 - -[<< Día 8](../dia_08_Objetos/dia_08_objetos.md) | [Day 10 >>](../10_Day_Sets_and_Maps/10_day_Sets_and_Maps.md) diff --git a/Spanish/images/30DaysOfJavaScript.png b/Spanish/images/30DaysOfJavaScript.png deleted file mode 100644 index 4142286..0000000 Binary files a/Spanish/images/30DaysOfJavaScript.png and /dev/null differ diff --git a/Spanish/images/adding_project_to_vscode.png b/Spanish/images/adding_project_to_vscode.png deleted file mode 100644 index 1935860..0000000 Binary files a/Spanish/images/adding_project_to_vscode.png and /dev/null differ diff --git a/Spanish/images/arithmetic.png b/Spanish/images/arithmetic.png deleted file mode 100644 index 9830916..0000000 Binary files a/Spanish/images/arithmetic.png and /dev/null differ diff --git a/Spanish/images/array_index.png b/Spanish/images/array_index.png deleted file mode 100644 index 355324e..0000000 Binary files a/Spanish/images/array_index.png and /dev/null differ diff --git a/Spanish/images/assignment_operators.png b/Spanish/images/assignment_operators.png deleted file mode 100644 index 99d51d2..0000000 Binary files a/Spanish/images/assignment_operators.png and /dev/null differ diff --git a/Spanish/images/banners/Day -1 – 31.png b/Spanish/images/banners/Day -1 – 31.png deleted file mode 100644 index d9a9639..0000000 Binary files a/Spanish/images/banners/Day -1 – 31.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_1.png b/Spanish/images/banners/day_1_1.png deleted file mode 100644 index dd583c7..0000000 Binary files a/Spanish/images/banners/day_1_1.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_10.png b/Spanish/images/banners/day_1_10.png deleted file mode 100644 index e063dec..0000000 Binary files a/Spanish/images/banners/day_1_10.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_11.png b/Spanish/images/banners/day_1_11.png deleted file mode 100644 index 0c2d60b..0000000 Binary files a/Spanish/images/banners/day_1_11.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_12.png b/Spanish/images/banners/day_1_12.png deleted file mode 100644 index 232ac85..0000000 Binary files a/Spanish/images/banners/day_1_12.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_13.png b/Spanish/images/banners/day_1_13.png deleted file mode 100644 index 488f522..0000000 Binary files a/Spanish/images/banners/day_1_13.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_14.png b/Spanish/images/banners/day_1_14.png deleted file mode 100644 index 4c5a568..0000000 Binary files a/Spanish/images/banners/day_1_14.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_15.png b/Spanish/images/banners/day_1_15.png deleted file mode 100644 index e3013f6..0000000 Binary files a/Spanish/images/banners/day_1_15.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_16.png b/Spanish/images/banners/day_1_16.png deleted file mode 100644 index d116060..0000000 Binary files a/Spanish/images/banners/day_1_16.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_17.png b/Spanish/images/banners/day_1_17.png deleted file mode 100644 index 69cf7ae..0000000 Binary files a/Spanish/images/banners/day_1_17.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_18.png b/Spanish/images/banners/day_1_18.png deleted file mode 100644 index 8b69340..0000000 Binary files a/Spanish/images/banners/day_1_18.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_19.png b/Spanish/images/banners/day_1_19.png deleted file mode 100644 index 2a785c9..0000000 Binary files a/Spanish/images/banners/day_1_19.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_2.png b/Spanish/images/banners/day_1_2.png deleted file mode 100644 index 0f6eefb..0000000 Binary files a/Spanish/images/banners/day_1_2.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_20.png b/Spanish/images/banners/day_1_20.png deleted file mode 100644 index befe1fc..0000000 Binary files a/Spanish/images/banners/day_1_20.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_21.png b/Spanish/images/banners/day_1_21.png deleted file mode 100644 index 634d1eb..0000000 Binary files a/Spanish/images/banners/day_1_21.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_22.png b/Spanish/images/banners/day_1_22.png deleted file mode 100644 index 81e33d9..0000000 Binary files a/Spanish/images/banners/day_1_22.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_23.png b/Spanish/images/banners/day_1_23.png deleted file mode 100644 index ceb0321..0000000 Binary files a/Spanish/images/banners/day_1_23.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_24.png b/Spanish/images/banners/day_1_24.png deleted file mode 100644 index 9c8ec46..0000000 Binary files a/Spanish/images/banners/day_1_24.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_25.png b/Spanish/images/banners/day_1_25.png deleted file mode 100644 index 60a211e..0000000 Binary files a/Spanish/images/banners/day_1_25.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_26.png b/Spanish/images/banners/day_1_26.png deleted file mode 100644 index f187f2c..0000000 Binary files a/Spanish/images/banners/day_1_26.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_27.png b/Spanish/images/banners/day_1_27.png deleted file mode 100644 index 8637069..0000000 Binary files a/Spanish/images/banners/day_1_27.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_28.png b/Spanish/images/banners/day_1_28.png deleted file mode 100644 index 1858aca..0000000 Binary files a/Spanish/images/banners/day_1_28.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_29.png b/Spanish/images/banners/day_1_29.png deleted file mode 100644 index 959ee36..0000000 Binary files a/Spanish/images/banners/day_1_29.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_3.png b/Spanish/images/banners/day_1_3.png deleted file mode 100644 index 1268d2c..0000000 Binary files a/Spanish/images/banners/day_1_3.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_30.png b/Spanish/images/banners/day_1_30.png deleted file mode 100644 index 18a77c4..0000000 Binary files a/Spanish/images/banners/day_1_30.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_4.png b/Spanish/images/banners/day_1_4.png deleted file mode 100644 index d5262c6..0000000 Binary files a/Spanish/images/banners/day_1_4.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_5.png b/Spanish/images/banners/day_1_5.png deleted file mode 100644 index 21bc08c..0000000 Binary files a/Spanish/images/banners/day_1_5.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_6.png b/Spanish/images/banners/day_1_6.png deleted file mode 100644 index dbea5fd..0000000 Binary files a/Spanish/images/banners/day_1_6.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_7.png b/Spanish/images/banners/day_1_7.png deleted file mode 100644 index eff8dac..0000000 Binary files a/Spanish/images/banners/day_1_7.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_8.png b/Spanish/images/banners/day_1_8.png deleted file mode 100644 index ddf9007..0000000 Binary files a/Spanish/images/banners/day_1_8.png and /dev/null differ diff --git a/Spanish/images/banners/day_1_9.png b/Spanish/images/banners/day_1_9.png deleted file mode 100644 index 1cf688b..0000000 Binary files a/Spanish/images/banners/day_1_9.png and /dev/null differ diff --git a/Spanish/images/comparison_operators.png b/Spanish/images/comparison_operators.png deleted file mode 100644 index 26ccb91..0000000 Binary files a/Spanish/images/comparison_operators.png and /dev/null differ diff --git a/Spanish/images/console_log_multipl_arguments.png b/Spanish/images/console_log_multipl_arguments.png deleted file mode 100644 index f324a90..0000000 Binary files a/Spanish/images/console_log_multipl_arguments.png and /dev/null differ diff --git a/Spanish/images/date_time_object.png b/Spanish/images/date_time_object.png deleted file mode 100644 index c5297c7..0000000 Binary files a/Spanish/images/date_time_object.png and /dev/null differ diff --git a/Spanish/images/day_1.png b/Spanish/images/day_1.png deleted file mode 100644 index 7daf57f..0000000 Binary files a/Spanish/images/day_1.png and /dev/null differ diff --git a/Spanish/images/day_1_1.png b/Spanish/images/day_1_1.png deleted file mode 100644 index dd583c7..0000000 Binary files a/Spanish/images/day_1_1.png and /dev/null differ diff --git a/Spanish/images/download_node.png b/Spanish/images/download_node.png deleted file mode 100644 index f290b20..0000000 Binary files a/Spanish/images/download_node.png and /dev/null differ diff --git a/Spanish/images/google_chrome.png b/Spanish/images/google_chrome.png deleted file mode 100644 index af06acd..0000000 Binary files a/Spanish/images/google_chrome.png and /dev/null differ diff --git a/Spanish/images/install_node.png b/Spanish/images/install_node.png deleted file mode 100644 index e5aecf1..0000000 Binary files a/Spanish/images/install_node.png and /dev/null differ diff --git a/Spanish/images/js_code_on_chrome_console.png b/Spanish/images/js_code_on_chrome_console.png deleted file mode 100644 index 7d6002c..0000000 Binary files a/Spanish/images/js_code_on_chrome_console.png and /dev/null differ diff --git a/Spanish/images/js_code_vscode.png b/Spanish/images/js_code_vscode.png deleted file mode 100644 index 6e1a661..0000000 Binary files a/Spanish/images/js_code_vscode.png and /dev/null differ diff --git a/Spanish/images/launched_on_new_tab.png b/Spanish/images/launched_on_new_tab.png deleted file mode 100644 index ed377dc..0000000 Binary files a/Spanish/images/launched_on_new_tab.png and /dev/null differ diff --git a/Spanish/images/local_storage.png b/Spanish/images/local_storage.png deleted file mode 100644 index 0876852..0000000 Binary files a/Spanish/images/local_storage.png and /dev/null differ diff --git a/Spanish/images/multiple_script.png b/Spanish/images/multiple_script.png deleted file mode 100644 index caa067f..0000000 Binary files a/Spanish/images/multiple_script.png and /dev/null differ diff --git a/Spanish/images/opening_chrome_console_shortcut.png b/Spanish/images/opening_chrome_console_shortcut.png deleted file mode 100644 index eace03f..0000000 Binary files a/Spanish/images/opening_chrome_console_shortcut.png and /dev/null differ diff --git a/Spanish/images/opening_developer_tool.png b/Spanish/images/opening_developer_tool.png deleted file mode 100644 index 6eb33dd..0000000 Binary files a/Spanish/images/opening_developer_tool.png and /dev/null differ diff --git a/Spanish/images/opening_project_on_vscode.png b/Spanish/images/opening_project_on_vscode.png deleted file mode 100644 index 908c8fd..0000000 Binary files a/Spanish/images/opening_project_on_vscode.png and /dev/null differ diff --git a/Spanish/images/projects/congratulations.gif b/Spanish/images/projects/congratulations.gif deleted file mode 100644 index cddd6c4..0000000 Binary files a/Spanish/images/projects/congratulations.gif and /dev/null differ diff --git a/Spanish/images/projects/dom_min_project_30DaysOfJavaScript_color_changing_day_9.1.gif b/Spanish/images/projects/dom_min_project_30DaysOfJavaScript_color_changing_day_9.1.gif deleted file mode 100644 index c8d2f2b..0000000 Binary files a/Spanish/images/projects/dom_min_project_30DaysOfJavaScript_color_changing_day_9.1.gif and /dev/null differ diff --git a/Spanish/images/projects/dom_min_project_bar_graph_day_5.1.gif b/Spanish/images/projects/dom_min_project_bar_graph_day_5.1.gif deleted file mode 100644 index a7d7962..0000000 Binary files a/Spanish/images/projects/dom_min_project_bar_graph_day_5.1.gif and /dev/null differ diff --git a/Spanish/images/projects/dom_min_project_bar_graph_day_5.1.png b/Spanish/images/projects/dom_min_project_bar_graph_day_5.1.png deleted file mode 100644 index 0b6ccf7..0000000 Binary files a/Spanish/images/projects/dom_min_project_bar_graph_day_5.1.png and /dev/null differ diff --git a/Spanish/images/projects/dom_min_project_challenge_info_day_1.1.gif b/Spanish/images/projects/dom_min_project_challenge_info_day_1.1.gif deleted file mode 100644 index 0551771..0000000 Binary files a/Spanish/images/projects/dom_min_project_challenge_info_day_1.1.gif and /dev/null differ diff --git a/Spanish/images/projects/dom_min_project_challenge_info_day_1.1.png b/Spanish/images/projects/dom_min_project_challenge_info_day_1.1.png deleted file mode 100644 index 01a8d4f..0000000 Binary files a/Spanish/images/projects/dom_min_project_challenge_info_day_1.1.png and /dev/null differ diff --git a/Spanish/images/projects/dom_min_project_countries_aray_day_2.2.png b/Spanish/images/projects/dom_min_project_countries_aray_day_2.2.png deleted file mode 100644 index ca0e344..0000000 Binary files a/Spanish/images/projects/dom_min_project_countries_aray_day_2.2.png and /dev/null differ diff --git a/Spanish/images/projects/dom_min_project_day_7.1.gif b/Spanish/images/projects/dom_min_project_day_7.1.gif deleted file mode 100644 index 51bdadb..0000000 Binary files a/Spanish/images/projects/dom_min_project_day_7.1.gif and /dev/null differ diff --git a/Spanish/images/projects/dom_min_project_day_number_generators_2.1.png b/Spanish/images/projects/dom_min_project_day_number_generators_2.1.png deleted file mode 100644 index d69a6c2..0000000 Binary files a/Spanish/images/projects/dom_min_project_day_number_generators_2.1.png and /dev/null differ diff --git a/Spanish/images/projects/dom_min_project_keycode_day_3.2.gif b/Spanish/images/projects/dom_min_project_keycode_day_3.2.gif deleted file mode 100644 index 7c75c14..0000000 Binary files a/Spanish/images/projects/dom_min_project_keycode_day_3.2.gif and /dev/null differ diff --git a/Spanish/images/projects/dom_min_project_number_generator_day_3.1.gif b/Spanish/images/projects/dom_min_project_number_generator_day_3.1.gif deleted file mode 100644 index 59a8dd0..0000000 Binary files a/Spanish/images/projects/dom_min_project_number_generator_day_3.1.gif and /dev/null differ diff --git a/Spanish/images/projects/dom_min_project_solar_system_day_4.1.gif b/Spanish/images/projects/dom_min_project_solar_system_day_4.1.gif deleted file mode 100644 index d88b04b..0000000 Binary files a/Spanish/images/projects/dom_min_project_solar_system_day_4.1.gif and /dev/null differ diff --git a/Spanish/images/projects/dom_min_project_solar_system_day_4.1.mkv b/Spanish/images/projects/dom_min_project_solar_system_day_4.1.mkv deleted file mode 100644 index 1ed941c..0000000 Binary files a/Spanish/images/projects/dom_min_project_solar_system_day_4.1.mkv and /dev/null differ diff --git a/Spanish/images/projects/dom_min_project_solar_system_day_4.1.mp4 b/Spanish/images/projects/dom_min_project_solar_system_day_4.1.mp4 deleted file mode 100644 index 69ce936..0000000 Binary files a/Spanish/images/projects/dom_min_project_solar_system_day_4.1.mp4 and /dev/null differ diff --git a/Spanish/images/projects/dom_mini_project_challenge_info_day_2.3.gif b/Spanish/images/projects/dom_mini_project_challenge_info_day_2.3.gif deleted file mode 100644 index 571ea6f..0000000 Binary files a/Spanish/images/projects/dom_mini_project_challenge_info_day_2.3.gif and /dev/null differ diff --git a/Spanish/images/projects/dom_mini_project_challenge_info_day_2.3.png b/Spanish/images/projects/dom_mini_project_challenge_info_day_2.3.png deleted file mode 100644 index 3387bea..0000000 Binary files a/Spanish/images/projects/dom_mini_project_challenge_info_day_2.3.png and /dev/null differ diff --git a/Spanish/images/projects/dom_mini_project_countries_day_6.1.gif b/Spanish/images/projects/dom_mini_project_countries_day_6.1.gif deleted file mode 100644 index 8a8f09a..0000000 Binary files a/Spanish/images/projects/dom_mini_project_countries_day_6.1.gif and /dev/null differ diff --git a/Spanish/images/projects/dom_mini_project_countries_object_day_10.1.gif b/Spanish/images/projects/dom_mini_project_countries_object_day_10.1.gif deleted file mode 100644 index 03b1e35..0000000 Binary files a/Spanish/images/projects/dom_mini_project_countries_object_day_10.1.gif and /dev/null differ diff --git a/Spanish/images/projects/dom_mini_project_form_validation_day_10.2.1.png b/Spanish/images/projects/dom_mini_project_form_validation_day_10.2.1.png deleted file mode 100644 index 9d2c2b3..0000000 Binary files a/Spanish/images/projects/dom_mini_project_form_validation_day_10.2.1.png and /dev/null differ diff --git a/Spanish/images/projects/dom_mini_project_form_validation_day_10.2.png b/Spanish/images/projects/dom_mini_project_form_validation_day_10.2.png deleted file mode 100644 index ca7cdd5..0000000 Binary files a/Spanish/images/projects/dom_mini_project_form_validation_day_10.2.png and /dev/null differ diff --git a/Spanish/images/projects/dom_mini_project_leaderboard_day_8.1.gif b/Spanish/images/projects/dom_mini_project_leaderboard_day_8.1.gif deleted file mode 100644 index 789d0cb..0000000 Binary files a/Spanish/images/projects/dom_mini_project_leaderboard_day_8.1.gif and /dev/null differ diff --git a/Spanish/images/projects/dom_mini_project_leaderboard_day_8.1.png b/Spanish/images/projects/dom_mini_project_leaderboard_day_8.1.png deleted file mode 100644 index 2956fa0..0000000 Binary files a/Spanish/images/projects/dom_mini_project_leaderboard_day_8.1.png and /dev/null differ diff --git a/Spanish/images/projects/dom_mini_project_slider_day_7.1.gif b/Spanish/images/projects/dom_mini_project_slider_day_7.1.gif deleted file mode 100644 index 51bdadb..0000000 Binary files a/Spanish/images/projects/dom_mini_project_slider_day_7.1.gif and /dev/null differ diff --git a/Spanish/images/raising_syntax_error.png b/Spanish/images/raising_syntax_error.png deleted file mode 100644 index 81f6245..0000000 Binary files a/Spanish/images/raising_syntax_error.png and /dev/null differ diff --git a/Spanish/images/regex.png b/Spanish/images/regex.png deleted file mode 100644 index c7116b4..0000000 Binary files a/Spanish/images/regex.png and /dev/null differ diff --git a/Spanish/images/running_script.png b/Spanish/images/running_script.png deleted file mode 100644 index deac13d..0000000 Binary files a/Spanish/images/running_script.png and /dev/null differ diff --git a/Spanish/images/scripts_on_vscode.png b/Spanish/images/scripts_on_vscode.png deleted file mode 100644 index f6257be..0000000 Binary files a/Spanish/images/scripts_on_vscode.png and /dev/null differ diff --git a/Spanish/images/string_indexes.png b/Spanish/images/string_indexes.png deleted file mode 100644 index cc2f638..0000000 Binary files a/Spanish/images/string_indexes.png and /dev/null differ diff --git a/Spanish/images/vscode.png b/Spanish/images/vscode.png deleted file mode 100644 index 724fc10..0000000 Binary files a/Spanish/images/vscode.png and /dev/null differ diff --git a/Spanish/images/vscode_ui.png b/Spanish/images/vscode_ui.png deleted file mode 100644 index 7210a08..0000000 Binary files a/Spanish/images/vscode_ui.png and /dev/null differ diff --git a/Spanish/images/web_storage.png b/Spanish/images/web_storage.png deleted file mode 100644 index 46f9311..0000000 Binary files a/Spanish/images/web_storage.png and /dev/null differ diff --git a/Spanish/readme.md b/Spanish/readme.md deleted file mode 100644 index 6c06ece..0000000 --- a/Spanish/readme.md +++ /dev/null @@ -1,550 +0,0 @@ -
-

30 Días de JavaScript

- - - - - Twitter Follow - - -Autor: -Asabeneh Yetayeh
- Enero de 2020 -
- -
- -🇬🇧 [English](../readMe.md) -🇪🇸 [Spanish](./readme.md) -🇷🇺 [Russian](../RU/README.md) - -
-
- -![Thirty Days Of JavaScript](./images/day_1_1.png) - -[📔Día 1](#día-1) - -- [📔Día 1](#día-1) - - [Introducción](#introducción) - - [Requerimientos](#requerimientos) - - [Preparación](#preparación) - - [Instala Node.js](#instala-nodejs) - - [Navegador](#navegador) - - [Instalando Google Chrome](#instalando-google-chrome) - - [Abriendo la consola de Google Chrome](#abriendo-la-consola-de-google-chrome) - - [Escribiendo el código en la consola del navegador](#escribiendo-el-código-en-la-consola-del-navegador) - - [Console.log](#consolelog) - - [Console.log con múltiples argumentos](#consolelog-con-múltiples-argumentos) - - [Comentario](#comentario) - - [Sintaxis](#sintaxis) - - [Aritmética](#aritmética) - - [Editor de código](#editor-de-código) - - [Instalando Visual Studio](#instalando-visual-studio) - - [Cómo usar Visual Studio Code](#cómo-usar-visual-studio-code) - - [Añadiendo JavaScript a una página web](#añadiendo-javascript-a-una-página-web) - - [Script en línea](#script-en-línea) - - [Script interno](#script-interno) - - [Script externo](#script-externo) - - [Múltiples Scripts externos](#múltiples-scripts-externos) - - [Introducción a los tipos de datos](#introducción-a-los-tipos-de-datos) - - [Números](#números) - - [Cadenas de texto](#cadenas-de-texto) - - [Booleanos](#booleanos) - - [Undefined](#undefined) - - [Null](#null) - - [Comprobando los tipos de datos](#comprobando-los-tipos-de-datos) - - [Comentarios](#comentarios) - - [Variables](#variables) -- [💻 Día 1: Ejercicios](#-día-1-ejercicios) - -# 📔Día 1 - -## Introducción - -**Felicidades** por decidir participar en el desafío de 30 días de JavaScript. En este desafío aprenderás todo lo que necesitas para ser un programador de JavaScript y los conceptos generales de la programación. Al final obtendrás un certificado de 30 días de JavaScript. Únete al [grupo de telegram](https://t.me/ThirtyDaysOfJavaScript). - -**30 días de JavaScript** es una guía tanto para principiantes como para desarrolladores avanzados. Bienvenido a JavaScript. Disfruto de usarlo y enseñarlo y espero que tú también. JavaScript es el lenguaje del navegador. - -En este tutorial de paso a paso, aprenderás JavaScript, el lenguaje de programación más popular de la historia de la humanidad. Se usa para **agregar interactividad a las páginas web, para desarrollar aplicaciones móviles, aplicaciones de desktop, juegos** y ahora también puede ser usado para el **aprendizaje automático** (machine learning) e **inteligencia artificial** (AI). Su popularidad ha incrementado en años recientes, siendo el lenguaje predominante por cuatro años consecutivos y el más usado en GitHub. - -## Requerimientos - -Ningún conocimiento previo es requerido para el siguiente desafío. Solo necesitarás: - -1. Motivación -2. Una computadora -3. Internet -4. Un navegador -5. Un editor de texto - -## Preparación - -Asumo que tienes motivación, un fuerte deseo de convertirte en un desarrollador, una computadora e internet. Si tienes todo esto, entonces lo tienes todo. - -### Instala Node.js - -Tal vez no lo necesites ahora pero si más adelante. Asi que instala [node.js](https://nodejs.org/en/) - -![Node download](./images/download_node.png) - -Luego de que se descargue, haz doble click e instálalo - -![Install node](./images/install_node.png) - -Puedes comprobar si se ha instalado correctamente abriendo la terminal del ordenador - - asabeneh $ node -v - v12.14.0 - -Para el desafío estaremos utilizando la versión 12.14.0, la cual es la recomendada por Node. - -### Navegador - -Existen muchos navegadores disponibles. Sin embargo, recomiendo especialmente Google Chrome. - -#### Instalando Google Chrome - -Instala [Google Chrome](https://www.google.com/chrome/) si aún no lo tienes. Podemos escribir un pequeño código JavaScript en la consola del navegador, pero no utilizamos la consola para desarrollar aplicaciones. - -![Google Chrome](./images/google_chrome.png) - -#### Abriendo la consola de Google Chrome - -Puedes abrir la consola de Google Chrome haciendo click en los tres puntos de la esquina superior derecha del navegador Chrome o utilizando un acceso directo. Yo prefiero usar los atajos. - -![Opening chrome](./images/opening_developer_tool.png) - -Para abrir la consola Chrome usando un atajo. - - Mac - Command+Option+I - - Windows: - Ctl+Shift+I - -![Opening console](./images/opening_chrome_console_shortcut.png) - -Después de abrir la consola de Google Chrome, intenta explorar los botones marcados. Pasaremos la mayor parte del tiempo aquí. La consola es el lugar donde va el código de JavaScript. El motor de la Consola de Google V8 cambia tu código JavaScript a código de máquina. Escribamos un código JavaScript en la consola de Google Chrome: - -![write code on console](./images/js_code_on_chrome_console.png) - -#### Escribiendo el código en la consola del navegador - -Podemos escribir cualquier código de JavaScript en la consola de Google o en la de cualquier navegador. Sin embargo, para este desafío, sólo nos centramos en la consola de Google Chrome. Abre la consola usando: - - Mac - Comando+Opción+I - - Windows: - Ctl+Mayúsculas+I - -##### Console.log - -Para escribir nuestro primer código de JavaScript, usamos una función incorporada, **console.log()**. Pasamos un argumento como datos de entrada, y la función muestra la salida. Pasamos 'Hola, Mundo' como datos de entrada o argumento en la función console.log(). - - console.log('¡Hola, Mundo!') - -##### Console.log con múltiples argumentos - -El console.log(param1, param2, param3), puede tomar múltiples argumentos. - -![console log multiple arguments](./images/console_log_multipl_arguments.png) - - console.log('Hola', 'Mundo', '!') - console.log('FELIZ', 'AÑO', 'NUEVO', 2020) - console.log('Bienvenido', 'a', 30, 'Días', 'de', 'JavaScript') - -Como pueden ver, en el código del fragmento de arriba, console.log() puede tomar múltiples argumentos. - -¡Felicidades! Escribiste tu primer código JavaScript usando _console.log()_. - -##### Comentario - -Podemos añadir comentarios a nuestro código. Los comentarios son muy importantes para hacer el código más legible y para dejar recordatorios en nuestro código. JavaScript no ejecuta la parte de comentarios de nuestro código. Cualquier texto que empiece con // en JavaScript es un comentario o cualquier cosa que encierre como esta /\* \*/ es un comentario. - -**Ejemplo: Comentario en una sola línea** - - // Este es el primer comentario - // Este es el segundo comentario - // Soy un comentario de una sola línea - -**Ejemplo: Comentario multilínea** - - /* Este es un comentario de varias líneas. - - Los comentarios multilínea pueden tomar múltiples líneas. - - JavaScript es el lenguaje de la web - */ - -##### Sintaxis - -JavaScript es un lenguaje de programación. Como resultado, tiene su sintaxis como otros lenguajes. Si no escribimos una sintaxis que JavaScript entienda, se producirán diferentes tipos de errores. Exploraremos diferentes tipos de errores de JavaScript más adelante. Por ahora, veamos los errores de sintaxis. - -![Error](./images/raising_syntax_error.png) - -Cometí un error deliberado. Como resultado, la consola produce un error de sintaxis. En realidad, la sintaxis es muy informativa. Informa sobre el tipo de error que cometimos. Leyendo la guía de retroalimentación de errores, podemos corregir la sintaxis y arreglar el problema. El proceso de identificar y eliminar errores de un programa se llama 'debugging'. Corrijamos los errores: - - console.log("¡Hola, Mundo!") - console.log('¡Hola, Mundo!') - -Hasta ahora, hemos visto cómo mostrar el texto usando un console.log(). Si imprimimos texto o cadena usando console.log(), el texto tiene que estar entre comillas simples, dobles o 'backtick' (``). **Ejemplo:** - - console.log("¡Hola, Mundo!") - console.log('¡Hola, Mundo!') - console.log(`Hola, Mundo!`) - -#### Aritmética - -Ahora, practiquemos más la escritura de códigos JavaScript usando console.log() en la consola de Google Chrome para los tipos de datos numéricos. Además del texto, también podemos hacer cálculos matemáticos usando JavaScript. Hagamos los siguientes cálculos sencillos. - -![Arithmetic](./images/arithmetic.png) - - console.log(2 + 3) // Adición - console.log(3 - 2) // Sustracción - console.log(2 * 3) // Multiplicación - console.log(3 / 2) // División - console.log(3 % 2) // Módulo - encontrar el resto - console.log(3 ** 2) // Exponencial - -### Editor de código - -Podemos escribir nuestros códigos en la consola del navegador, pero no será para proyectos más grandes. En un entorno de trabajo real, los desarrolladores utilizan diferentes editores para escribir sus códigos. En este desafío de 30 días de JavaScript, usaremos Visual Studio Code. - -#### Instalando Visual Studio - -Visual Studio es un editor de texto de código abierto muy popular. Recomendaría descargarlo, pero si estás a favor de otros editores, siéntete libre de seguir con lo que tienes. - -![Vscode](./images/vscode.png) - -Si ya instalaste Visual Studio Code, empezaremos a usarlo. - -#### Cómo usar Visual Studio Code - -Abre Visual Studio Code haciendo doble clic en el ícono de Visual Studio. Cuando lo abras, obtendrás este tipo de interfaz. Intenta interactuar con los iconos etiquetados. - -![Vscode ui](./images/vscode_ui.png) - -![Vscode add project](./images/adding_project_to_vscode.png) - -![Vscode open project](./images/opening_project_on_vscode.png) - -![script file](./images/scripts_on_vscode.png) - -![running script](./images/running_script.png) - -![coding running](./images/launched_on_new_tab.png) - -## Añadiendo JavaScript a una página web - -JavaScript puede ser añadido a una página web de tres maneras diferentes: - -- **_Script en línea ('Inline script')_** -- **_Script interno_** -- **_Script externo_** -- **_Múltiples scripts_** - -Las siguientes secciones muestran diferentes formas de añadir código JavaScript a nuestra página web. - -### Script en línea - -Crea una carpeta en tu escritorio y llámala 30DíasDeJS o en cualquier lugar y crea un archivo **_index.html_** en la carpeta del proyecto. Luego pega el siguiente código y ábrelo en un navegador, ya sea en [Chrome](https://www.google.com/chrome/). - - - - - 30DíasDeJS:Inline Script - - - - - - - -Ahora, escribiste tu primer inline script. Podemos crear un mensaje de alerta emergente usando la función integrada _alert()_. - -### Script interno - -El Script interno puede ser escrito en la cabecera del código _('head')_ o en el cuerpo _('body')_, pero es preferible ponerlo en el cuerpo del documento HTML. Primero, escribamos en la parte de la cabeza de la página. - - - - - 30DíasDeJS:Scripts Internos - - - - - - -Así es como escribimos el guión interno la mayor parte del tiempo. Escribir el código de JavaScript en la sección del body es el lugar más recomendado. Abre la consola del navegador para ver la respuesta del console.log() - - - - - 30DíasDeJS:Scripts Internos - - - - - - - -Abre la consola del navegador para ver la respuesta del console.log() - -![js code from vscode](./images/js_code_vscode.png) - -### Script externo - -Al igual que el script interno, el enlace del script externo puede estar en la cabecera del código ('head') o en el cuerpo ('body'), pero igualmente es recomendado ponerlo en el 'body'. Primero, debemos crear un archivo JavaScript externo con extensión .js. Cualquier archivo JavaScript termina con .js. Crea un archivo introduccion.js dentro del directorio del proyecto y escribe el siguiente código y enlaza este archivo .js en la parte inferior del cuerpo. - - console.log('Bienvenido a 30DaysOfJavaScript') - -**Script externo en la cabecera** - - - - - 30DíasDeJS:Scripts Externos - - - - - - -**Script externo en el cuerpo** - - - - - 30DíasDeJS:Scripts Externos - - - //Podría estar en la cabecera o en el cuerpo... - // Aquí está el lugar recomendado para poner el script externo - - - - -Abre la consola del navegador para ver la respuesta del console.log() - -### Múltiples Scripts externos - -Podemos enlazar múltiples archivos externos de JavaScript a una página web. Crea un archivo holamundo.js dentro de la carpeta 30DiasDeJS y escribe el siguiente código. - - console.log('¡Hola, Mundo!') - - - - - - Múltiples guiones externos - - - - - - - - -Tu archivo main.js debería estar por debajo de todos los otros scripts. Ten cuidado con tu ejercicio para entender esta línea. - -![Multiple Script](./images/multiple_script.png) - -## Introducción a los tipos de datos - -En JavaScript y también en otros lenguajes de programación, hay diferentes tipos de datos. Los siguientes son los tipos de datos primitivos de JavaScript: _Cadenas de texto ('string'), Números, Booleanos, undefined, Null_ y _Symbol_. - -### Números - -- Enteros: Números enteros (negativos, cero y positivos) Ejemplo: ... -3, -2, -1, 0, 1, 2, 3 ... -- Float: Números decimales Ejemplo ... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ... - -### Cadenas de texto - -Una colección de uno o más carácteres entre comillas. **Ejemplo:** - - "Asabeneh" - "Finlandia" - 'JavaScript es un hermoso lenguaje de programación'. - "Me encanta enseñar" - "Espero que estés disfrutando del primer día" - `También podemos crear una cadena usando un backtick` - -### Booleanos - -Un valor booleano es verdadero o falso. Cualquier comparación devuelve un valor booleano, que es verdadero o falso. - -Un tipo de datos booleano es un valor Verdadero o Falso. - -**Ejemplo:** - - true // si la luz está encendida, el valor es true - falso // si la luz está apagada, el valor es Falso - -### Undefined - -En JavaScript, si no asignamos un valor a una variable, el valor es indefinido. Además, si una función no devuelve nada, devuelve undefined. - - let nombre; - console.log(nombre); //no está definida, porque no está asignada a un valor todavía - -### Null - -Null en JavaScript significa un valor vacío/nulo. - - let valorVacio = null - -## Comprobando los tipos de datos - -Para comprobar el tipo de datos de un determinado valor, utilizamos el operador **'typeof'**. Véase el siguiente ejemplo. - - console.log(typeof 'Asabeneh') // string - console.log(typeof 5) // número - console.log(typeof true ) // boolean - console.log(typeof null) // tipo de objeto - console.log(typeof undefined) // undefined - -## Comentarios - -Los comentarios en JavaScript son similares a los de otros lenguajes de programación. Los comentarios son importantes para hacer tu código más legible. Hay dos maneras de comentar: - -- _Comentario en una sola línea_ -- _Comentario multilineal_ - - // comentando el código mismo con un solo comentario - // let nombre = 'Asabeneh'; comentario de una sola línea - // let apellido = 'Yetayeh'; comentario de una sola línea - -Comentario multilineal: - - /* - let ubicación = 'Helsinki'; - let edad = 100; - let casado = verdadero; - Este es un comentario de varias líneas - */ - -### Variables - -Las variables son contenedores de datos. Las variables se utilizan para almacenar datos en una ubicación de memoria. Cuando se declara una variable, se reserva una ubicación de memoria. Cuando se asigna una variable a un valor (data), el espacio de memoria se llena con esos datos. Para declarar una variable, usamos palabras clave _var_, _let_ o _const_. Hablaremos más sobre var, let y const en detalle en otras secciones (ámbito). Por ahora, la explicación anterior es suficiente. - -Para una variable que cambia en un momento diferente, usamos _let_. Si los datos no cambian en absoluto, usamos _const_. Por ejemplo, PI, nombre del país, gravedad no cambian, y podemos usar _const._ - -- El nombre de una variable en JavaScript no debe comenzar con un número. -- Un nombre de variable JavaScript no permite caracteres especiales excepto el signo de dólar y el guión bajo. -- Los nombres de las variables en JavaScript siguen una convención 'CamelCase'. -- El nombre de una variable no debe tener espacio entre palabras. - -Los siguientes son ejemplos válidos de variables JavaScript. - -Variables válidas en JavaScript: - - primerNombre - apellido - país - ciudadCapital - capital - edad - estaCasado - - nombre_de_pila - apellido - esta_casado - ciudad_capital - - num1 - num_1 - _num_1 - $num1 - año2020 - año_2020 - -camelCase es convencional en JavaScript. En este material, usaremos variables de CamelCase. - -Variables inválidas: - - primer-nombre - 1_numero - num_#_1 - -Declaremos las variables con diferentes tipos de datos. Para declarar una variable, necesitamos usar la palabra clave let o const antes del nombre de la variable. Después del nombre de la variable, escribimos un signo igual (operador de asignación), y un valor. - - # Sintaxis - let nombreDeLaVariable = valor - -**Ejemplos: Variables** - - // Declarando diferentes variables de diferentes tipos de datos - let nombre = 'Asabeneh' // nombre de una persona - let apellido = 'Yetayeh' // apellido de una persona - let pais = 'Finland' // país - let ciudad = 'Helsinki' // ciudad capital - let edad = 100 // edad en años - let estaCasado = true - - console.log(nombre, apellido, país, ciudad, edad, estáCasado) - - - Asabeneh Yetayeh Finlandia Helsinki 100 True - - // Declarando variables con valores numéricos - let edad = 100 // edad en años - const constante = 9,81 // gravedad terrestre en m/s2 - const puntoDeEbullición = 100 // punto de ebullición del agua, temperatura en oC - const PI = 3.14 // constante geométrica - - console.log(gravedad, punto de ebullición, PI) - - - 9.81 100 3.14 - - - // Las variables también pueden ser declaradas en una línea separada por una coma - let nombre = 'Asabeneh', // nombre de una persona - trabajo = 'profesor', - viveEn = 'Finlandia'; - console.log(nombre, trabajo, viveEn); - - - Asabeneh profesor de Finlandia - -Cuando ejecutas los archivos en la carpeta Día_1 deberías obtener esto: - -![Day one](./images/day_1.png) - -🌕 Eres increíble. Acabas de completar el desafío del día 1 y estás en camino a la grandeza. Ahora haz algunos ejercicios para tu cerebro y para tus músculos. - -# 💻 Día 1: Ejercicios - -1. Escribe un comentario de una sola línea que diga _"los comentarios pueden hacer que el código sea legible"_ - -2. Escribe otro comentario que diga, _"Bienvenido a 30DaysOfJavaScript"_ - -3. Escribe un comentario multilínea que diga, _"Los comentarios pueden hacer el código legible, fácil de usar e informativo"_ - -4. Crea un archivo variable.js y declarar variables y asignar tipos de datos string, booleanos, indefinidos y nulos - -5. Crea el archivo datatypes.js y utilizar el operador **_"typeof"_** de JavaScript para comprobar los diferentes tipos de datos. Comprueba el tipo de datos de cada variable - -6. Declara cuatro variables sin asignar valores - -7. Declara cuatro variables con valores asignados - -8. Declara variables para almacenar su nombre, apellido, estado civil, país y edad en múltiples líneas - -9. Declara variables para almacenar su nombre, apellido, estado civil, país y edad en una sola línea - -10. Declara dos variables _miEdad_ y _tuEdad_ y asígneles valores iniciales y regístrese en la consola del navegador. - - Tengo 25 años. - Tú tienes 30 años. - - 🎉 ¡FELICIDADES! 🎉 - -[Day 2 >>](./dia_02_tipos_de_datos.md) diff --git a/Turkish/02_Day_Data_types/02_day_data_types.md b/Turkish/02_Day_Data_types/02_day_data_types.md deleted file mode 100644 index 694313f..0000000 --- a/Turkish/02_Day_Data_types/02_day_data_types.md +++ /dev/null @@ -1,999 +0,0 @@ -
-

30 Günde JavaScript: Veri Türleri

- - - - - Twitter Follow - - - Author: - Asabeneh Yetayeh
- January, 2020 -
-
- - -[<< Gün 1](../readMe.md) | [Gün 3 >>](../03_Day_Booleans_operators_date/03_booleans_operators_date.md) - -![JavaScript'in 30 Günü](../../images/banners/day_1_2.png) - -- [📔 Gün 2](#-gun-2) - - [Veri Türleri](#veri-turleri) - - [İlkel Veri Türleri](#ilkel-veri-türleri) - - [İlkel Olmayan Veri Türleri](#ilkel-olmayan-veri-türleri) - - [Sayılar](#sayilar) - - [Sayı Veri Türlerini Bildirme](#sayı-veri-türleri-bildirme) - - [Math Nesnesi](#math-nesnesi) - - [Rastgele Sayı Üretme](#rastgele-sayı-üretme) - - [Stringler](#stringler) - - [String Birleştirme](#string-birleştirme) - - [Toplama Operatörünü Kullanarak Birleştirme](#toplama-operatörü-kullanarak-birleştirme) - - [Uzun Değişmez String'ler](#uzun-değişmez-stringler) - - [String'lerdeki Kaçış Dizileri](#strringlerdeki-kaçış-dizileri) - - [Şablon Değişmezleri](#şablon-değişmezleri) - - [String Metotları](#string-metotları) - - [Veri Türlerini Kontrol Etme ve Döküm](#veri-türlerini-kontrol-etme-ve-döküm) - - [Veri Türlerini Kontrol Etme](#veri-türlerini-kontrol-etme) - - [Veri Türünü Değiştirme (Döküm)](#veri-türünü-değiştirme-döküm) - - [String to Int](#string-to-int) - - [String to Float](#string-to-float) - - [Float to Int](#float-to-int) - - [💻 Gün 2: Egzersizler](#-gün-2-egzersizler) - - [Egzersiz: Seviye 1](#egzersiz-seviye-1) - - [Egzersiz: Seviye 2](#egzersiz-seviye-2) - - [Egzersiz: Seviye 3](#egzersiz-seviye-3) - -# 📔 Gün 2 - -( type çeviri olarak "tür - tip " olarak kullanılabilir. ) -Bölüm çevirisini yaparken bazı kelimeleri çevirmedim zira bunları ingilizce halleriyle bilmenizde fayda var. -Örn: - String vb.. - -## Veri Türleri - -Bir Önceki bölümde, veri türlerinden biraz bahsettik. Veri veya değerlerin (veri) türleri vardır. -Veri türleri, verilerin özelliklerini tanımlar. Veri türleri ikiye ayrılabilir: - -1. İlkel veri türleri -2. İlkel olmayan veri türleri (Nesne Referansları) - -### İlkel Veri Türleri - -JavaScript'teki ilkel veri türleri şunları içerir: - - 1. Numbers - Tamsayılar - Ondalık sayılar - 2. Strings - Tek tırnak, çift tırnak veya ters tırnak içerisindeki tüm veriler.. - 3. Booleans - true yada false (true = 1 false = 0 bu iki terimi bu şekilde öğrenin. Çevirilerine çok girmeyin kısaca var yada yok ) - 4. Null - Boş değer yada değeri yok - 5. Undefined - Bir değer verilmeyen değişken. ( Örn: let variables; ) - 6. Symbol - Sembol yapıcısı tarafından oluşturulabilen benzersiz bir değer - -JavaScript'teki ilkel olmayan veri türleri şunları içerir: - -1. Objects ( Nesneler ) -2. Arrays ( Diziler ) - - -Şimdi ilkel ve ilkel olmayan veri türlerinin tam olarak ne anlama geldiğini görelim. -*İlkel* veri türleri değişmez (değiştirilemez) veri türleridir. İlkel bir veri türü oluşturulduktan sonra onu değiştiremeyiz. - -**Örnek:** - -```js -let word = 'JavaScript' -``` - -*word* değişkeninde saklanan dizeyi değiştirmeye çalışırsak JavaScript bir hata vermelidir. Tek, çift veya ters tırnak arasındaki herhangi bir veri türü, dize veri türüdür. - -```js -word[0] = 'Y' -``` - -Bu ifade *word* değişkeninde saklanan dizeyi değiştirmez. Yani, string'lerin değiştirilemez ya da başka bir deyişle değişmez olduğunu söyleyebiliriz. -İlkel veri türleri değerlerine göre karşılaştırılır. Farklı veri değerlerini karşılaştıralım. Aşağıdaki örneğe bakın: - -```js -let numOne = 3 -let numTwo = 3 - -console.log(numOne == numTwo) // true ( Burada iki değişkende 3 e eşit olduğu için birbirine eşit olduğu sonucu çıkıyor ) - -let js = 'JavaScript' -let py = 'Python' - -console.log(js == py) //false ( Burada iki değişkende farklı olduğu ve eşitlenemedikleri için false yani 0 değeri dönüyor ) - -let lightOn = true -let lightOff = false - -console.log(lightOn == lightOff) //false ( Yukarıdaki örnek gibi eeşit olmadıkları için false yani 0 değeri dönüyor ) -``` - -### İlkel Olmayan Veri Türleri - -*İlkel olmayan* veri türleri düzenlenebilir veya değiştirilebilir. İlkel olmayan veri türlerinin değerini, oluşturulduktan sonra değiştirebiliriz. -Bir dizi oluşturarak görelim. Dizi, köşeli parantez içindeki veri değerlerinin bir listesidir.Diziler aynı veya farklı veri türlerini içerebilir. Dizi değerleri dizin indekslerine ( dizinine ) göre referans alınır. JavaScript'te dizilerin indeksi sıfırdan başlar. Yani bir dizinin ilk elemanı sıfır indeksinde, ikinci elemanı bir indeksinde, üçüncü elemanı iki indeksinde bulunur. -( Orjinal anlatıma bağlı kalmak istiyorum lakin bazen anlamsız olabiliyor. Kısaca diziler okunurken 0-1-2-3 .... şeklinde indekslenir. Bir dizinin ilk elemanına erişmek istiyorsanız indeks numarasına 0 yazmalısınız. Aşağıdaki örneği incelerseniz bu karmaşıklığı çözmüş olacaksınız. ) - -```js -let nums = [1, 2, 3] -nums[0] = 10 - -console.log(nums) // [10, 2, 3] ( nums değişkeninin ilk elemanı yada 0. indeksinin değerini 10 yapmış oldu ) -``` - -Gördüğünüz gibi "DİZİ" ilkel olmayan bir veri türü değişkenidir. İlkel olmayan veri türleri değere göre karşılaştırılamaz. İlkel olmayan veri türleri aynı özelliklere ve değerlere sahip olsa bile, kesinlikle eşit değildirler. - -```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) // false -``` - -Temel kural, ilkel olmayan veri türlerini karşılaştıramıyoruz. Dizileri (arrays), fonksiyonları (functions) veya nesneleri (objects) karşılaştırmayın. -İlkel olmayan değerler, değer yerine referansla karşılaştırıldıkları için referans türleri olarak adlandırılır. İki nesne, yalnızca aynı temel nesneye atıfta bulunuyorlarsa kesinlikle eşittir. - -```js -let nums = [1, 2, 3] -let numbers = nums - -console.log(nums == numbers) // true ( değişken oluştururken numbers'ın değerini nums'a eşitlediği için bunun sonucu true dönmektedir.) - -let userOne = { -name:'Asabeneh', -role:'teaching', -country:'Finland' -} - -let userTwo = userOne - -console.log(userOne == userTwo) // true ( yukarıdaki ile aynı ) -``` - -İlkel veri türleri ile ilkel olmayan veri türleri arasındaki farkı anlamakta zorluk çekiyorsan, bunu yaşayan tek kişi değilsin. Sakin ol ve bir sonraki bölüme geç ve bir süre sonra geri gelip burayı tekrar incele. Şimdi sayı türlerine göre veri türlerine başlayalım. - -## Sayılar - -Sayılar, tüm aritmetik işlemleri yapabilen tam sayılar ve ondalık değerlerdir. -Hadi sayılar ile ilgili bazı örnekler görelim. - -### Sayı Veri Türlerini Bildirme - -```js -let age = 35 -const gravity = 9.81 // yer çekimi kuvvet değeri bu değer haliyle değişmeyeceği için const olarak tanımlanıyor. Değişmez değişkenleri const ile tanımlarsınız. Bunu unutmayın. -let mass = 72 // kilogram cinsinden kütle -const PI = 3.14 // pi sayısı matematikte sabit bir sayı olduğu için const ile oluşturulmuş. ( küsüratı almamış ) - -// daha fazla örnek -const boilingPoint = 100 // derece cinsinden sıcaklık, suyun sabit olan kaynama noktası ( derecesi ) -const bodyTemp = 37 // derece. İnsan vücudun sabit olan ortalama sıcaklığı - -console.log(age, gravity, mass, PI, boilingPoint, bodyTemp) -``` - -### Matematik Nesnesi - Objesi ( Math Object ) - -JavaScript'te Math Objesi, sayılar ile çalışmanız için birçok yöntem sağlar. - -```js -const PI = Math.PI // Buraya kısa bir açıklama getirelim. Math objesi sayesinde PI sayısının değerini otomatik alıyoruz. - -console.log(PI) // 3.141592653589793 - -// En yakın sayıya yuvarlama -// Eğer .5'in altındaysa aşağıya üstündeyse yukarıya yuvarlar. Örn: 3.14 ise 3 yapar 3.51 ise 4 yapar. - -console.log(Math.round(PI)) // 3.14 olduğu için 3 e yuvarlama yapıyor - -console.log(Math.round(9.81)) // Ondası 0.5 üstünde olduğu için 10 yapar - -console.log(Math.floor(PI)) // floor aşağı yuvarlar Bu 3 olur - -console.log(Math.ceil(PI)) // ceil yukarı yuvarlar Bu 4 olur - -console.log(Math.min(-5, 3, 20, 4, 5, 10)) // En küçük sayıyı bulmaya yaradığı için sonuç -5 döner - -console.log(Math.max(-5, 3, 20, 4, 5, 10)) // En büyük sayıyı bulmaya yaradığı için sonuç 20 döner - -const randNum = Math.random() // 0 ile 0.999999 arasında rastgele bir sayı üretir. -console.log(randNum) - -// 0 ile 10 arasında rastgele bir sayı oluşturalım. - -const num = Math.floor(Math.random () * 11) // 0 ile 10 arasında rastgele sayı oluşturur -console.log(num) - -//Mutlak değer -console.log(Math.abs(-10)) // 10 - -//Kare kök -console.log(Math.sqrt(100)) // 10 - -console.log(Math.sqrt(2)) // 1.4142135623730951 - -// Üs -console.log(Math.pow(3, 2)) // 9 - -console.log(Math.E) // 2.718 - -// Logaritma -// Returns the natural logarithm with base E of x, Math.log(x) -console.log(Math.log(2)) // 0.6931471805599453 -console.log(Math.log(10)) // 2.302585092994046 - -// Sırasıyla 2 ve 10'un doğal logaritmasını döndürür -console.log(Math.LN2) // 0.6931471805599453 -console.log(Math.LN10) // 2.302585092994046 - -// Trigonometri -Math.sin(0) -Math.sin(60) - -Math.cos(0) -Math.cos(60) -``` - -#### Rastgele Sayı Üretme - -JavaScript'te Math nesnesi random() methodu 0 ile 0,999999999 arasında bir sayı üretir - -```js -let randomNum = Math.random() // 0 ile 0.999999999 arasında bir sayı üretir -``` - -Şimdi 0 ile 10 arasında rastgele bir sayı üretmek için random() methodu'nu nasıl kullanabileceğimizi görelim: - -```js -let randomNum = Math.random() // 0 ile 0.999 arasında oluşturur -let numBtnZeroAndTen = randomNum * 11 - -console.log(numBtnZeroAndTen) // Sonuç : minimum 0 ve maksimum 10.99 - -let randomNumRoundToFloor = Math.floor(numBtnZeroAndTen) // yuvarlama yapıyor -console.log(randomNumRoundToFloor) // Sonuç 0 ile 10 arasında çıkar -``` - -## Strings - -Dizeler **_tek_**, **_çift_** ve **_ters tırnak_** arasındaki metinlerdir. -Bir dize bildirmek için değişken adına, atama operatörüne, tek tırnak, çift tırnak veya ters tırnak içerisinde bir değere ihtiyacımız var. -Bazı dize örnekleri görelim: - -```js -let space = ' ' // boş alan string tek tırnaklı -let firstName = 'Asabeneh' // tek tırnaklı string -let lastName = 'Yetayeh' // tek tırnaklı string -let country = 'Finland' // tek tırnaklı string -let city = 'Helsinki' // tek tırnaklı string -let language = 'JavaScript' // tk tırnaklı string -let job = 'teacher' // tek tırnaklı string -let quote = "The saying,'Seeing is Believing' is not correct in 2020." // çift tırnaklı string -let quotWithBackTick = `The saying,'Seeing is Believing' is not correct in 2020.` // ters tırnaklı string (bu karakteri genellikle klavyenizdeki noktalı virgülü kullanarak yaparsınız. Benim klavyemde alt gr + noktalı virgül ve iki kere tıklanınca çıkıyor) -``` - -### String Birleştirme - -İki veya daha fazla string'i birbirine bağlama işlemine birleştirme denir. -Yukarda bulunan string örneklerini kullanarak: - -```js -let fullName = firstName + space + lastName; // birleştirme, iki string'i bir araya getirme. -console.log(fullName); -``` - -```sh -Asabeneh Yetayeh -``` - -String'leri farklı şekildede birleştirebiliriz. - -#### Toplama Operatörünü Kullanarak Birleştirme - -Ekleme operatörü kullanarak birleştirme eski bir yöntemdir. Bu birleştirme yöntemi sıkıcı ve hataya açıktır. Bu şekilde nasıl birleştirileceğini bilmek iyidir, ancak ES6 şablon dizelerini kullanmanızı şiddetle tavsiye ederim (daha sonra açıklanacaktır). - -```js -// Farklı veri türlerini oluşturma -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 toplama operatörü ile değişkenleri birleştiriyor - -console.log(personInfoOne) -``` - -```sh -Asabeneh Yetayeh. I am 250. I live in Finland -``` - -#### Uzun Değişmez Stringler - -Stringler tek bir karakter, paragraf yada sayfa olabilir. String uzunluğu çok büyükse tek bir satıra sığmayabilir. String'in bir sonraki satırda devam edeceğini belirtmek için her satırın sonunda ters eğik çizgi karakterini (\\) kullanabiliriz. -**Örnek:** - -```js -// burada kendinden bahseden bir paragraf yazmış. Bunuda çevirmeyelim :D -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) -``` - -#### String'lerdeki Kaçış Dizileri -JavaScript ve diğer programlama dillerinde \ (ters eğik çizgi ) ardından bazı karakterler kaçış dizisidir. En yaygın kaçış karakterlerini görelim: - -- \n: yeni satır -- \t: Tab, 8 boşluk anlamına gelir ( klavyedeki tab tuşunu temsil eder ) -- \\\\: Ters eğik çizgi -- \\': Tek Tırnak (') -- \\": Çift Tırnak (") - -```js -// kodları console kısmına yazarak denerseniz daha iyi anlarsınız. -console.log('I hope everyone is enjoying the 30 Days Of JavaScript challenge.\nDo you ?') // Buradakı \n satır sonu anlamına gelir sonrası aşağı iner -console.log('Days\tTopics\tExercises') // Burada her kelimeden sonra bir tab (\t) tuşuna basılmış etkisi verir -console.log('Day 1\t3\t5') // \t bir başka örnek -console.log('Day 2\t3\t5') // \t bir başka örnek -console.log('Day 3\t3\t5') // \t bir başka örnek -console.log('Day 4\t3\t5') // \t bir başka örnek -console.log('This is a backslash symbol (\\)') // Ters eğik çizgi yazmak için \\ kullanılıyor -console.log('In every programming language it starts with \"Hello, World!\"') // Hello World'ü çift tırnak içine almak için \" Hello World \" kullanılıyor. -console.log("In every programming language it starts with \'Hello, World!\'") // Hello World'ü tek tırnak içine almak için \' Hello World \' kullanılıyor. -console.log('The saying \'Seeing is Believing\' isn\'t correct in 2020') // Bu kısımdada alıntıları kullanmak için \ kullanımı gösterilmiş. -``` - -Konsol çıktıları : - -```sh -I hope everyone is enjoying the 30 Days Of JavaScript challenge. -Do you ? -Days Topics Exercises -Day 1 3 5 -Day 2 3 5 -Day 3 3 5 -Day 4 3 5 -This is a backslash symbol (\) -In every programming language it starts with "Hello, World!" -In every programming language it starts with 'Hello, World!' -The saying 'Seeing is Believing' isn't correct in 2020 -``` - -#### Şablon Değişmezleri (Şablon String'ler) - -Şablon string'leri oluşturmak için iki ters tırnak kullanıyoruz. Verileri bir şablon string'i içine ifade olarak ekleme yapabiliriz. Verileri eklemek için, ifadeyi $ (dolar) işareti ile başlayan bir küme parantezinin "{}" içine alırız. Aşağıdaki sözdizimine bakın. - -```js -//Syntax -`String literal text` -`String literal text ${expression}` -``` - -**Örnek : 1** - -```js -console.log(`The sum of 2 and 3 is 5`) // statik bir veri -let a = 2 -let b = 3 -console.log(`The sum of ${a} and ${b} is ${a + b}`) // verileri dinamik olarak ekleme -``` - -**Örnek :2** - -```js - -// Bu kısımda yazar + kullanarak ekleme yapmanın diğer yöntemi olan ES6 ekleme yöntemini gösteriyor. Bu daha stabil çalışıyor. -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 - dize ekleme yöntemi ( ES5 yukarda gösterilmişti ) -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. -``` - -Bir string şablonu veya interpolasyon ( matematiksel bir terim ) yöntemi kullanarak, bir değer olabilecek ifadeler veya bazı işlemler ekleyebiliriz.(karşılaştırma, aritmetik işlemler, üçlü işlem) - -```js -let a = 2 -let b = 3 -console.log(`${a} is greater than ${b}: ${a > b}`) // a b den büyüktür yazıyor ve interpolasyon metodu bunun yanlış olduğunu söylecek -``` - -```sh -2 is greater than 3: false -``` - -### String Metotları - -JavaScript'teki her şey bir nesnedir. Bir string ilkel veri türüyse bunu değiştiremeyiz. String bir nesnenin, birçok string metodu vardır. Birçok string metodu bulunmaktadır, bunlar string'ler ile çalışmamıza yardımcı olurlar. ( stringlerin özelliklerini vb bulma metodları bunlar Örneğe bakın) - -1. *length*: String içerisindeki karakterlerin sayısını belirtir. Boşluklar dahildir. - -**Örnek :** - -```js -let js = 'JavaScript' -console.log(js.length) // 10 -let firstName = 'Asabeneh' -console.log(firstName.length) // 8 -``` - -2. *String'deki karakterlere erişim*: String içerisinde bulunan her karaktere indeks numarasıyla erişebiliriz. Programlamada sayma 0 dan başlar. String'in ilk dizini 0, son dizini ise toplam uzunluğun -1'dir. ( Kısaca 10 karakter varsa sıralama 0-9 arasında yapılıyor. Resme bakın daha iyi anlayacaksınız.) - - ![Dizine göre dizine erişme](../../images/string_indexes.png) - -'JavaScript' string'indeki farklı karakterlere erişelim. - -```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()*: bu metot string verisini büyük harflere dönüştürür. - -```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()*: bu metot string verisini küçük harflere dönüştürür. - -```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()*: İki arrgüman alır, başlangıç indeksi ve silenecek karakter sayısı. - -```js -let string = 'JavaScript' -console.log(string.substr(4,6)) // Script - -let country = 'Finland' -console.log(country.substr(3, 4)) // land -``` - -6. *substring()*: Başlangıç indeksi ve durma indeksi olmak üzere iki argüman almaktadır. - -```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()*: Bu metot bir stringi belirtilen yerden bölmeye yarar. ( array oluşturuyor ) - -```js -let string = '30 Days Of JavaScript' - -console.log(string.split()) // bu kısımda birşey belirtmediğin için 1 elementli array oluştu -> ["30 Days Of JavaScript"] -console.log(string.split(' ')) // bu kısımda boşluktan böl dediğimiz için 4 elementli array oluştu -> ["30", "Days", "Of", "JavaScript"] - -let firstName = 'Asabeneh' - -console.log(firstName.split()) // - > ["Asabeneh"] -console.log(firstName.split('')) // burada sadece tek tırnak kullandığımız için string'in içindeki tüm karakterleri array haline getirdi -> ["A", "s", "a", "b", "e", "n", "e", "h"] - -let countries = 'Finland, Sweden, Norway, Denmark, and Iceland' - -console.log(countries.split(',')) // Dikkat edin sadece virgül ile ayırıyor. İknci elementin solunda boşluk oluşuyor. ["Finland", " Sweden", " Norway", " Denmark", " and Iceland"] -console.log(countries.split(', ')) // Dikkat edin burayada. ', ' virgül ve boşluk bulunmakta bu yüzden elementleri virgülden ayırıp boşluklsuz arrray oluşturuyor.  ["Finland", "Sweden", "Norway", "Denmark", "and Iceland"] -``` - -8. *trim()*: String'in başında ve sonundaki boşlukları silmeye yarar. - -```js -let string = ' 30 Days Of JavaScript ' - -console.log(string) -console.log(string.trim(' ')) - -let firstName = ' Asabeneh ' - -console.log(firstName) -console.log(firstName.trim()) // içinde tırnak kullanmasanız dahi boşlukları siler -``` - -```sh - 30 Days Of JavasCript -30 Days Of JavasCript - Asabeneh -Asabeneh -``` - -9. *includes()*: Bu metot string içerisinde varlık kontrolü yapmaya yarar. Eğer bulursa true, bulamazsa false döner. ( birebir arama yapar ) - -```js -let string = '30 Days Of JavaScript' - -console.log(string.includes('Days')) // true -console.log(string.includes('days')) // false - birebir arama yapar! -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()*: Bu metot string içerisinde değiştirme yapmamızı sağlar. Eski ve Yeni olmak üzere iki argüman alır. - -```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()*: Stringdeki indeksi belirttiğinizde o indeksin değerini yazdırır. - -```js -string.charAt(index) -``` - -```js -let string = '30 Days Of JavaScript' -console.log(string.charAt(0)) // 3 (0. indeksin değerini döndürdü) - -let lastIndex = string.length - 1 // bu kısımda yukardaki değişkenin karakter sayısını alıyor (21) sonra bu sonucu 1 ile çıkartıyor sonuç 20. aşağı bak -console.log(string.charAt(lastIndex)) // pogramlamada sayma 0 dan başladığı için -1 yapıyor yukarıda console.log da çıkan sonuç "t" olacaktır. Buda 20. karakterdir. İnanmazsan say =) ama sıfırdan başlamayı unutma -``` - -12. *charCodeAt()*: String'teki vermiş olduğunuz index değerinin ASCII numarasını döndürür. - -```js -string.charCodeAt(index) -``` - -```js -let string = '30 Days Of JavaScript' -console.log(string.charCodeAt(3)) // D ASCII 68 - -let lastIndex = string.length - 1 -console.log(string.charCodeAt(lastIndex)) // t ASCII 116 - -``` - -13. *indexOf()*: Bu metot belirtilen değerin indeksini verir. Değer bulunamazsa -1 sonucunu döndürür. ( Birebir arama yapar örneğe bakın ) - -```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()*: Bu metot belirtilen değerin son değer indeksini verir. Değer bulunamazsa -1 sonucunu döndürür. ( Birebir arama yapar örneğe bakın ) - - -```js -//syntax -string.lastIndexOf(substring) -``` - -```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()*: Bu metot birleştirme işlemini sağlar, birden fazla değer alabilir - -```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*: String'in belirtilen değer ile başlayıp başlamadığını kontrol eder. true yada false döndürür. - -```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*: String'in belirtilen değer ile bitip bitmediğini kontrol eder. true yada false döndürür. - -```js -string.endsWith(substring) -``` - -```js -let string = 'Love is the most powerful feeling in the world' - -console.log(string.endsWith('world')) // true -console.log(string.endsWith('love')) // false -console.log(string.endsWith('in the 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*: Argüman olarak bir alt dize alır ve ilk eşleşmenin dizinini döndürür. Arama değeri bir dize veya normal ifade kalıbı olabilir. - -```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 -console.log(string.search(/javascript/gi)) // 7 buradaki gi açıklaması bir alt örnekte var -``` - -19. *match*: Argüman olarak bir alt dize veya normal ifade kalıbı alır ve eşleşme varsa bir dizi döndürür, değilse null döndürür. Normal bir ifade kalıbının nasıl göründüğünü görelim. / işareti ile başlar ve / işareti ile biter. - -```js -let string = 'love' -let patternOne = /love/ // koşulsuz -let patternTwo = /love/gi // g-bütün metinde ara, i - büyük küçük harf duyarsız -``` - -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"] -``` - -Normal bir ifade kullanarak metinden sayıları çıkaralım. Burası normal ifade bölümü değil, panik yapmayın! Düzenli ifadeleri daha sonra ele alacağız. - -```js -let txt = 'In 2019, I ran 30 Days of Python. Now, in 2020 I am super exited to start this challenge' -let regEx = /\d+/ - -// kaçış karakterli d, d'nin normal olmadığı anlamına gelir, d bunun yerine bir rakam gibi davranır -// + bir veya daha fazla basamaklı sayı anlamına gelir, -// ondan sonra g varsa global demektir, her yerde ara. - -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()*: bağımsız değişken olarak bir sayı alır ve stringi sayı kadar döndürür. - -```js -string.repeat(n) -``` - -```js -let string = 'love' -console.log(string.repeat(10)) // lovelovelovelovelovelovelovelovelovelove -``` - -## Veri Türlerini Kontrol Etme ve Döküm - -### Veri Türlerini Kontrol Etme - -Belirli bir değişkenin veri türünü kontrol etmek için _typeof_ yöntemini kullanırız. - -**Örnek:** - -```js -// Farklı javascript veri türleri -// Farklı veri tipleri tanımlayalım - -let firstName = 'Asabeneh' // string -let lastName = 'Yetayeh' // string -let country = 'Finland' // string -let city = 'Helsinki' // string -let age = 250 // number, benim gerçek yaşım değil merak etme -let job // undefined, çünkü bir değer atanmamış - -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 -``` - -### Veri Türünü Değiştirme (Döküm) - -- Döküm: Bir veri tipini başka bir veri tipine dönüştürme. Kullandıklarımız _parseInt()_, _parseFloat()_, _Number()_, _+ sign_, _str()_ - Aritmetik işlemler yapmadan önce string sayıları önce integer yada float türüne dönüştürmeliyiz yoksa hata alırız. - -#### String to Int - - -String bir numarayı sayıya dönüştürebiliriz. Alıntı içerisindeki herhangi bir sayı string numarasıdır. Bir string numarası örneği: '10', '5', vb. -Aşağıdaki metotları kullanarak string'i sayıya dönüştürebiliriz: - -- parseInt() -- Number() -- Plus sign(+) // artı işareti demek - -```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 - -String içindeki ondalık numarayı sayıya çevirebiliriz. Tırnak içerisindeki ondalık sayı string ondalık sayıdır. Bir string ondalık numarası örneği: '9.81', '3.14', '1.44' vb. -Aşağıdaki metotları kullanarak ondalık stringi sayıya dönüştürebiliriz: - -- 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(numFloat) // 9.81 -``` - -#### Float to Int - -Ondalık sayıları tam sayılara çevirebiliriz. (Int) ( bu aşağıya yuvarlıyor ) -Float'ı int'e dönüştürmek için aşağıdaki metodu kullanıyoruz: - -- parseInt() - -```js -let num = 9.81 -let numInt = parseInt(num) - -console.log(numInt) // 9 -``` - -🌕 Harikasın. 2. gün zorluklarını yeni tamamladınız ve mükemmelliğe giden yolda iki adım öndesiniz. Şimdi beyniniz ve kasınız için bazı egzersizler yapın. - -## 💻 Gün 2: Egzersizleri - -### Exercise: Seviye 1 - -1. Challenge adında bir değişken tanımlayın ve **'30 Days Of JavaScript'** başlangıç ​​değerine atayın. -2. __console.log()__ kullanarak tarayıcı konsolunda değişkeni yazdırın, -3. _console.log()_ kullanarak tarayıcı konsolunda dizenin __length__ değerini yazdırın, -4. __toUpperCase()__ yöntemini kullanarak tüm dize karakterlerini büyük harflerle değiştirin, -5. __toLowerCase()__ yöntemini kullanarak tüm dize karakterlerini küçük harflerle değiştirin, -6. __substr()__ veya __substring()__ yöntemini kullanarak string'in ilk kelimesini kesin-silin (dilimleyin) -7. *Days Of JavaScript* ifadesini *30 Days Of JavaScript*'ten ayırın. -8. __includes()__ yöntemini kullanarak string'in __Script__ kelimesini içerip içermediğini kontrol edin -9. __split()__ yöntemini kullanarak __string__ öğesini bir __array__'ye bölün -10. 30 Days Of JavaScript dizesini __split()__ yöntemini kullanarak boşlukta bölün -11. 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon' dizeyi virgülden __split__ ve bir dizi olarak değiştirin. -12. __replace()__ yöntemini kullanarak 30 Days of JavaScript'i 30 Days of Python olarak değiştirin. -13. 'JavaScript'in 30 Günü' dizesinde dizin 15'teki karakter nedir? __charAt()__ yöntemini kullanın. -14. __charCodeAt()__ kullanan 'JavaScript'in 30 Günü' dizesindeki J karakter kodu nedir? -15. 30 Days of JavaScript'te __a__ öğesinin ilk oluşumunun konumunu belirlemek için __indexOf__ kullanın -16. 30 Days of JavaScript'te __a__ öğesinin son oluşumunun konumunu belirlemek için __lastIndexOf__ kullanın. -17. Aşağıdaki cümlede __çünkü__ kelimesinin ilk geçtiği yeri bulmak için __indexOf__ kullanın: -__'Bir cümleyi çünkü ile bitiremezsiniz çünkü çünkü bir bağlaçtır'__ -18. Aşağıdaki cümlede __çünkü__ kelimesinin son geçtiği yeri bulmak için __lastIndexOf__ kullanın: -__'Bir cümleyi çünkü ile bitiremezsiniz çünkü çünkü bir bağlaçtır'__ -19. Aşağıdaki cümlede __çünkü__ kelimesinin ilk geçtiği yeri bulmak için __search__ kullanın: -__'Bir cümleyi çünkü ile bitiremezsiniz çünkü çünkü bir bağlaçtır'__ -20. Bir dizgenin başındaki ve sonundaki boşlukları kaldırmak için __trim()__ kullanın. Örneğin '30 Days Of JavaScript'. -21. *30 Days Of JavaScript* dizesiyle __startsWith()__ yöntemini kullanın ve sonucu doğru yapın -22. *30 Days Of JavaScript* dizesiyle __endsWith()__ yöntemini kullanın ve sonucu doğru yapın -23. JavaScript'in 30 Günü'ndeki tüm __a__'leri bulmak için __match()__ yöntemini kullanın -24. __concat()__ kullanın ve '30 Days of' ve 'JavaScript'i tek bir dize olan '30 Days of JavaScript' ile birleştirin -25. 30 Gün JavaScript'i 2 kez yazdırmak için __repeat()__ yöntemini kullanın - - -### Egzersiz: Seviye 2 - -1. console.log() kullanarak aşağıdaki ifadeyi yazdırın: - - ```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 one another. - ``` - -2. console.log()'u kullanarak Rahibe Teresa'nın aşağıdaki alıntısını yazdırın: - - ```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." - ``` - -3. '10' tipinin tam olarak 10'a eşit olup olmadığını kontrol edin. Değilse tam olarak eşit yapın. -4. parseFloat('9.8') 10'a tam olarak eşit değilse, 10'a eşit olup olmadığını kontrol edin. -5. Hem python hem de jargonda 'on' ifadesinin bulunup bulunmadığını kontrol edin -6. _Umarım bu kurs jargonla dolu değildir_. Cümlede _jargon_ olup olmadığını kontrol edin. -7. 0 ile 100 arasında rastgele bir sayı üretin. -8. 50 ile 100 arasında rastgele bir sayı üretin. -9. Dahil olmak üzere 0 ile 255 arasında rastgele bir sayı oluşturun. -10. Rastgele bir sayı kullanarak 'JavaScript' dize karakterlerine erişin. -11. Aşağıdaki kalıbı yazdırmak için console.log() ve kaçış karakterlerini kullanın. - - ```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 - ``` - -12. __substr__ kullanarak __çünkü çünkü__ ifadesini aşağıdaki cümleden ayırın:__'Bir cümleyi çünkü ile bitiremezsiniz çünkü çünkü bir bağlaçtır'__ - -### Egzersiz: Seviye 3 - -1. 'Aşk bu dünyadaki en iyi şeydir. Bazıları aşkını buldu ve bazıları hala aşkını arıyor.' Bu cümledeki __love__ kelimesini sayın. -2. Aşağıdaki cümledeki tüm __çünkü__ sayısını saymak için __match()__ kullanın:__'Bir cümleyi çünkü ile bitiremezsiniz çünkü çünkü bir bağlaçtır'__ -3. Aşağıdaki metni temizleyin ve en sık kullanılan kelimeyi bulun (ipucu, değiştirme ve normal ifadeleri kullanın). - - ```js - const sentence = '%I $am@% a %tea@cher%, &and& I lo%#ve %te@a@ching%;. The@re $is no@th@ing; &as& mo@re rewarding as educa@ting &and& @emp%o@weri@ng peo@ple. ;I found tea@ching m%o@re interesting tha@n any ot#her %jo@bs. %Do@es thi%s mo@tiv#ate yo@u to be a tea@cher!? %Th#is 30#Days&OfJavaScript &is al@so $the $resu@lt of &love& of tea&ching' - ``` - -4. Aşağıdaki metinden sayıları çıkararak kişinin yıllık toplam gelirini hesaplayın. - -'Aylık maaşından 5000 euro, yıllık 10000 euro ikramiye, ayda 15000 euro online kurstan kazanıyor.' - -🎉 TEBRİKLER ! 🎉 - -[<< Gün 1](../readMe.md) | [Gün 3 >>](../03_Day_Booleans_operators_date/03_booleans_operators_date.md) diff --git a/Turkish/03_Day_Booleans_operators_date/03_booleans_operators_date.md b/Turkish/03_Day_Booleans_operators_date/03_booleans_operators_date.md deleted file mode 100644 index 65b7271..0000000 --- a/Turkish/03_Day_Booleans_operators_date/03_booleans_operators_date.md +++ /dev/null @@ -1,637 +0,0 @@ -
-

30 Days Of JavaScript: Booleans (Boole Değerler), Operators (Operatörler), Date (Tarih Objesi)

- - - - - Twitter Follow - - - Author: - Asabeneh Yetayeh
- January, 2020 -
-
- -[<< Gün 2](../02_Day_Data_types/02_day_data_types.md) | [Gün 4 >>](../04_Day_Conditionals/04_day_conditionals.md) - -![30 Günde JavaScript](../../images/banners/day_1_3.png) - -- [📔 Gün 3](#-gün-3) - - [Boolean Değerleri](#boolean-degerleri) - - [Doğru Değerleri](#doğru-değerleri) - - [Yanlış Değerleri](#yanlış-değerleri) - - [Tanımsız](#tanımsız) - - [Boş](#boş) - - [Operatörler](#operatörler) - - [Atama Operatörleri](#atama-operatörleri) - - [Aritmetik Operatörleri](#aritmetik-operatörleri) - - [Karşılaştırma Operatörleri](#karşılaştırma-operatörleri) - - [Mantıksal Operatörler](#mantıksal-operatörler) - - [Arttırma Operatörü](#arttırma-operatörü) - - [Azaltma Operatörü](#azaltma-operatörü) - - [Koşul Operatörü](#koşul-operatörü) - - [Operatör Önceliği](#operatör-önceliği) - - [Window Metotları](#window-metotları) - - [Window alert() metot](#window-alert-metot) - - [Window prompt() metot](#window-prompt-metot) - - [Window confirm() metot](#window-confirm-metot) - - [Date Objesi](#date-objesi) - - [Bir Zaman Objesi Oluşturma](#bir-zaman-objesi-oluşturma) - - [Tam Yılı Almak](#tam-yılı-almak) - - [Ayı Almak](#ayı-almak) - - [Tarihi Almak](#tarihi-almak) - - [Günü Almak](#günü-almak) - - [Saati Almak](#saati-almak) - - [Dakikayı Almak](#dakikayı-almak) - - [Saniyeyi Almak](#saniyeyi-almak) - - [Zamanı Almak](#zamanı-almak) - - [💻 Gün 3: Egzersizleri](#-gün-3-egzersizleri) - - [Egzersiz: Seviye 1](#egzersiz-seviye-1) - - [Egzersiz: Seviye 2](#egzersiz-seviye-2) - - [Egzersiz: Seviye 3](#egzersiz-seviye-3) - -# 📔 Gün 3 - -## Boolean Değerleri - -Boolean ver türü iki değerden birini temsil eder :_true_ yada _false_. Boolean değeri doğru veya yanlıştır. Karşılaştırma operatörlerini kullandığınızda sonuc netleşecektir. Herhangi bir karşılaştırma sonucu doğru veya yanlış olan bir boolean değeri döndürür. - -**Örnek: Boolean Deperleri** - -```js -let isLightOn = true // ışık açık doğru -let isRaining = false // yağıyor yanlış -let isHungry = false // aç yanlış -let isMarried = true // evli doğru -let truValue = 4 > 3 // true -- doğru -let falseValue = 4 < 3 // false -- yanlış -``` - -Boolean değerlerinin doğru yada yanlış olduğunu kabul etmiştik. - -### Doğru Değerleri (true) - -- Sıfır hariç tüm sayılar (pozitif ve negatif) doğrudur -- Boş bir dize ('') dışında tüm dizeler doğrudur -- Boole değeri doğru - -### Yanlış Değerleri (false) - -- 0 -- 0n -- null -- undefined -- NaN -- the boolean false -- '', "", ``, empty string - -Bu doğru ve yanlış değerleri hatırlamakta fayda var. Daha sonraki bölümde, onları karar vermek için koşullarla kullanacağız. - -## Tanımsız (Undefined) - -Bir değişken bildirirsek ve bir değer atamazsak, değer tanımsız olacaktır. Buna ek olarak, eğer bir fonksiyon değer döndürmüyorsa tanımsız olacaktır. - - -```js -let firstName -console.log(firstName) //tanımlanmamış, çünkü henüz bir değer atanmamış. -``` - -## Boş (Null) - -```js -let empty = null -console.log(empty) // -> null(boş) , değer yok anlamına gelir -``` - -## Operatörler - -### Atama Operatörleri - -JavaScript'te eşittir işareti bir atama operatörüdür. Değişken atamak için kullanılır. - -```js -let firstName = 'Asabeneh' -let country = 'Finland' -``` - -Atama Operatörleri - -![Atama Operatörleri](../../images/assignment_operators.png) - -### Aritmetik Operatörleri - -Aritmetik operatörler matematiksel operatörlerdir. - -- Toplama(+): a + b -- Çıkarma(-): a - b -- Çarpma(*): a * b -- Bölme(/): a / b -- Kalan(Bölmedeki kalan)(%): a % b -- (Örneğe Bak) Üstel Sayı (**): a ** b - -```js -let numOne = 4 -let numTwo = 3 -let sum = numOne + numTwo // toplama -let diff = numOne - numTwo // çıkarma -let mult = numOne * numTwo // çarpma -let div = numOne / numTwo // bölme -let remainder = numOne % numTwo // kalanı bulma (bölmedeki kalan oluyor bu Biraz matematik :D ) -let powerOf = numOne ** numTwo // buda üstel sayı anlamına geliyor Örnek: 4 Üssü 3 Kaçtır? Biraz matematik 2 :D - -console.log(sum, diff, mult, div, remainder, powerOf) // 7,1,12,1.33,1, 64 ---- Sonuçları console.log'a tek tek yazıp deneyin - -``` - -```js -const PI = 3.14 -let radius = 100 // metre cinsinden uzunluk - -// Bir dairenin alanını hesaplayalım -const areaOfCircle = PI * radius * radius -console.log(areaOfCircle) // 314 m - - -const gravity = 9.81 // m/s2 cinsinden ( metre saniye cinsi ) -let mass = 72 // kilogram cinsinden - -// Bir cismin ağırlığını hesaplayalım -const weight = mass * gravity -console.log(weight) // 706.32 N(Newton) - -const boilingPoint = 100 // oC cinsinden sıcaklık, suyun kaynama noktası -const bodyTemp = 37 // oC cinsinden vücut ısısı - - -// Dize enterpolasyonu kullanarak dizeyi sayılarla birleştirme -/* - The boiling point of water is 100 oC. // Suyun kaynama noktası 100 oC'dir. - Human body temperature is 37 oC. // İnsan vücut sıcaklığı 37 oC'dir. - The gravity of earth is 9.81 m/s2. // Dünyanın yerçekimi 9.81 m/s2'dir. - */ -console.log( - `The boiling point of water is ${boilingPoint} oC.\nHuman body temperature is ${bodyTemp} oC.\nThe gravity of earth is ${gravity} m / s2.` -) -``` - -### Karşılaştırma Operatörleri - -Programlamada değerleri karşılaştırırız, iki değeri karşılaştırmak için karşılaştırma operatörlerini kullanırız. Bir değerin diğer değere eşit veya büyük olup olmadığını kontrol ederiz. - -![Karşılaştırma Operatörleri](../../images/comparison_operators.png) -**Örnek: Karşılaştırma Operatörleri** - -```js -console.log(3 > 2) // true, çünkü 3 2 den büyüktür -console.log(3 >= 2) // true, çünkü 3 2 den büyüktür -console.log(3 < 2) // false, çünkü 3 2 den büyüktür -console.log(2 < 3) // true, çünkü 2 3 den küçüktür -console.log(2 <= 3) // true, çünkü 2 3 den küçüktür -console.log(3 == 2) // false, çünkü 3 2 ye eşit değildir -console.log(3 != 2) // true, çünkü 3 2 ye eşit değildir -console.log(3 == '3') // true, sadece değeri karşılaştırıyor -console.log(3 === '3') // false, hem değeri hemde veri türünü karşılaştırıyor o yüzden yanlış. Birisi int değeri birisi string değerinden ( Bu denklik operatörü ) -console.log(3 !== '3') // true, hem değeri hemde veri türünü karşılaştırıyor o yüzden doğru. (Bu denk değil operatörü) -console.log(3 != 3) // false, değeri karşılaştırıyor -console.log(3 !== 3) // false, hem değeri hem de veri türünü karşılaştırıyor -console.log(0 == false) // true, eşdeğer -console.log(0 === false) // false, tam olarak aynı değil -console.log(0 == '') // true, eşdeğer -console.log(0 == ' ') // true, eşdeğer -console.log(0 === '') // false, tam olarak aynı değil -console.log(1 == true) // true, eşdeğer -console.log(1 === true) // false, tam olarak aynı değil -console.log(undefined == null) // true -console.log(undefined === null) // false -console.log(NaN == NaN) // false, eşit değil -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) // true -console.log('milk'.length != 'meat'.length) // false -console.log('tomato'.length == 'potato'.length) // true -console.log('python'.length > 'dragon'.length) // false -``` - -Yukarıdaki karşılaştırmaları biraz mantıkla anlamaya çalışın. Herhangi bir mantık olmadan hatırlamak zor olabilir. -JavaScript bir şekilde kablolu bir programlama dilidir. JavaScript kodu çalışır ve size bir sonuç verir, ancak bunda iyi değilseniz, istenen sonuç olmayabilir. - -Temel kural olarak, eğer bir değer == ile doğru değilse, === ile eşit olmayacaktır. === kullanmak, == kullanmaktan daha güvenlidir. Aşağıdaki [bağlantı](https://dorey.github.io/JavaScript-Equality-Table/) veri türlerinin kapsamlı bir karşılaştırma listesine sahiptir. - -### Mantıksal Operatörler - -Aşağıdaki semboller ortak mantıksal operatörlerdir: -&&(ve işareti) , || (boru -veya-) ve !(olumsuzlama). -&& operatörü, yalnızca iki işlenen doğruysa doğru olur. -|| operatör, işlenenlerden herhangi birinin doğru olması durumunda gerçekleşir. -! operatör true - false ve false - true değerini olumsuzlar. - -```js -// && ve işareti operatörü örneği ( ampersand olarak anlandırılıyor) - -const check = 4 > 3 && 10 > 5 // true && true -> true -const check = 4 > 3 && 10 < 5 // true && false -> false -const check = 4 < 3 && 10 < 5 // false && false -> false - -// || boru veya operatör, örnek - -const check = 4 > 3 || 10 > 5 // true || true -> true -const check = 4 > 3 || 10 < 5 // true || false -> true -const check = 4 < 3 || 10 < 5 // false || false -> false - -//! olumsuzlama örnekleri - -let check = 4 > 3 // true -let check = !(4 > 3) // false -let isLightOn = true -let isLightOff = !isLightOn // false -let isMarried = !false // true -``` - -### Arttırma Operatörü - -JavaScript'te, bir değişkende saklanan bir değeri artırmak için artırma operatörünü kullanırız. Artış, artış öncesi veya sonrası olabilir. Her birini görelim: - -1. Öncesi Artış - -```js -let count = 0 -console.log(++count) // 1 -console.log(count) // 1 -``` - -1. Sonrası Artış - -```js -let count = 0 -console.log(count++) // 0 -console.log(count) // 1 -``` - -Artış sonrası zamanın çoğunu kullanırız. En azından artım sonrası operatörünü nasıl kullanacağınızı hatırlamalısınız. - - -### Azaltma Operatörü - -JavaScript'te, bir değişkende saklanan bir değeri azaltmak için azaltma operatörünü kullanırız. Azaltma, eksiltme öncesi veya sonrası olabilir. Her birini görelim: - -1. Öncesi Azaltma - -```js -let count = 0 -console.log(--count) // -1 -console.log(count) // -1 -``` - -2. Sonrası Azaltma - -```js -let count = 0 -console.log(count--) // 0 -console.log(count) // -1 -``` - -### Koşul Operatörü (Ternary - Üçlü ) - -Üçlü operatör bir koşul yazmaya izin verir. -Koşullar yazmanın başka bir yolu da üçlü operatörleri kullanmaktır. Aşağıdaki örneklere bakın: - -```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 negative number`) -number = -5 - -number > 0 - ? console.log(`${number} is a positive number`) - : console.log(`${number} is a negative number`) -``` - -```sh -5 is a positive number --5 is a negative number -``` - -### Operatör Önceliği - -Bu [bağlantıdan](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence) operatör önceliği hakkında okumanızı tavsiye ederim. - -## Window Metotları - -### Window alert() metot - -En başta gördüğünüz gibi alert() metodu, belirtilen bir mesaj ve bir Tamam butonu ile bir uyarı kutusu görüntüler. Yerleşik bir yöntemdir ve argüman alır. - -```js -alert(message) -``` - -```js -alert('Welcome to 30DaysOfJavaScript') -``` - -Yıkıcı ve sinir bozucu olduğu için çok fazla uyarı kullanmayın, sadece test etmek için kullanın. - -### Window prompt() metot - -Pencere yöntemleri, tarayıcınızda giriş değerlerini almak için bir giriş içeren bir bilgi istemi kutusu görüntüler ve giriş verileri bir değişkende saklanabilir. prompt() yöntemi iki argüman alır. İkinci argüman isteğe bağlıdır. - -```js -prompt('required text', 'optional text') -``` - -```js -let number = prompt('Enter number', 'number goes here') -console.log(number) -``` - -### Window confirm() metot - -confirm() yöntemi, bir Tamam ve İptal düğmesiyle birlikte belirli bir mesaj içeren bir iletişim kutusu görüntüler. -Bir onay kutusu genellikle bir kullanıcıdan bir şeyi yürütmek için izin istemek için kullanılır. Pencere confirm() argüman olarak bir dize alır. -Tamam'a tıklamak doğru değeri verir, İptal düğmesine tıklamak yanlış değeri verir. - -```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 -``` - -Bunların hepsi window yöntemleri değil, window yöntemlerine derinlemesine girmek için ayrı bir bölümümüz olacak. - -## Date Objesi - -Zaman önemli bir şeydir. Belirli bir faaliyetin veya olayın zamanını bilmek isteriz. JavaScript'te geçerli saat ve tarih, JavaScript Date Objesi kullanılarak oluşturulur. Date objesini kullanarak oluşturduğumuz nesne, tarih ve saat ile çalışmak için birçok yöntem sunar. Bir tarih nesnesi değerlerinden tarih ve saat bilgisi almak için kullandığımız yöntemler, bilgiyi sağladığı için _get_ kelimesi ile başlamaktadır. -_getFullYear(), getMonth(), getDate(), getDay(), getHours(), getMinutes, getSeconds(), getMilliseconds(), getTime(), getDay()_ - - - -![Date time objesi](../../images/date_time_object.png) - -### Bir Zaman Objesi Oluşturma - -Bir kez zaman objesi oluşturduğumuzda zaman objesi, zaman hakkında bilgi sağlayacaktır. Bir zaman objesi oluşturalım. - -```js -const now = new Date() -console.log(now) // Sat Jan 04 2020 00:56:41 GMT+0200 (Eastern European Standard Time) -``` - -Bir time objesi oluşturduk ve tablo üzerinde bahsettiğimiz get yöntemlerini kullanarak objeden herhangi bir tarih saat bilgisine ulaşabiliyoruz. - -### Tam Yılı Almak - -Bir zaman objesinden tam yılı çıkaralım veya alalım. - -```js -const now = new Date() -console.log(now.getFullYear()) // 2020 -``` - -### Ayı Almak - -Bir zaman objesinden ayı çıkaralım veya alalım. - -```js -const now = new Date() -console.log(now.getMonth()) // Bunu yazdığınızda muhtemelen bulunduğunuz aydan bir önceki ayın sayısını alıcaktır çünkü aylar 0-11 arasında oluşuyor. Ocak 1 değil 0. ay oluyor aralıkta 11. ay oluyor. -``` - -### Tarihi Almak - -Bir zaman objesinden ayın tarihini çıkaralım veya alalım. - -```js -const now = new Date() -console.log(now.getDate()) // yukardaki örnekte bulunan açıklamaya ek olarak geçen ayın gün sayısını verecektir. -``` - -### Günü Almak - -Bir zaman objesinden haftanın gününü çıkaralım veya alalım. - -```js -const now = new Date() -console.log(now.getDay()) // 6, because the day is Saturday which is the 7th day -// Sunday is 0, Monday is 1 and Saturday is 6 -// Getting the weekday as a number (0-6) -``` - -### Saati Almak - -Bir zaman objesinden saatleri çıkaralım veya alalım. - -```js -const now = new Date() -console.log(now.getHours()) -``` - -### Dakikayı Almak - -Bir zaman objesinden dakikaları çıkaralım veya alalım. - -```js -const now = new Date() -console.log(now.getMinutes()) -``` - -### Saniyeyi Almak - -Bir zaman objesinden saniyeleri çıkaralım veya alalım. - -```js -const now = new Date() -console.log(now.getSeconds()) -``` - -### Zamanı Almak - -Bu metot 1 Ocak 1970'den itibaren milisaniye cinsinden süre verir. Unix zamanı olarak da bilinir. Unix zamanını iki şekilde alabiliriz: - -1. _getTime()_ Kullanımı - -```js -const now = new Date() // -console.log(now.getTime()) // çıktı farklı olacaktır , 1 Ocak 1970 den kullandığınız zaman arasındaki süreyi milisaniye cinsinden verecektir. -``` - -1. _Date.now()_ Kullanımı - -```js -const allSeconds = Date.now() // -console.log(allSeconds) // çıktı farklı olacaktır , 1 Ocak 1970 den kullandığınız zaman arasındaki süreyi milisaniye cinsinden verecektir. - -const timeInSeconds = new Date().getTime() -console.log(allSeconds == timeInSeconds) // true -``` - -Bu değerleri insan tarafından okunabilir bir zaman biçimine biçimlendirelim. - -**Örnek:** - -```js -const now = new Date() -const year = now.getFullYear() // yılı döndürür -const month = now.getMonth() + 1 // ayı döndürür (0 - 11) olduğu için +1 ekliyor -const date = now.getDate() // günü döndürür (1 - 31) -const hours = now.getHours() // sayıyı döndürür (0 - 23) -const minutes = now.getMinutes() // sayıyı döndürür (0 -59) - -console.log(`${date}/${month}/${year} ${hours}:${minutes}`) // çıktı farklı olacaktır -``` - -🌕 Sınırsız bir enerjiniz var. 3. gün zorluklarını yeni tamamladınız ve mükemmelliğe giden yolda üç adım öndesiniz. Şimdi beyniniz ve kasınız için bazı egzersizler yapın. - -## 💻 Gün 3: Egzersizleri - -### Egzersiz: Seviye 1 - -1. firstName, lastName, country, city, age, isMarried, year değişkenlerini oluşturun ve bunlara değer atayın. Farklı veri türlerini kontrol etmek için typeof operatörünü kullanın. -2. '10' türünün 10'a eşit olup olmadığını kontrol edin -3. parseInt('9.8') 10'a eşit olup olmadığını kontrol edin -4. Boolean değeri, doğru veya yanlıştır. - 1. Doğruluk değeri sağlayan üç JavaScript ifadesi yazın. - 2. Yanlış değer sağlayan üç JavaScript ifadesi yazın. - -5. console.log() kullanmadan önce aşağıdaki karşılaştırma ifadesinin sonucunu bulun. Sonuca karar verdikten sonra console.log() kullanarak onaylayın. - 1. 4 > 3 - 2. 4 >= 3 - 3. 4 < 3 - 4. 4 <= 3 - 5. 4 == 4 - 6. 4 === 4 - 7. 4 != 4 - 8. 4 !== 4 - 9. 4 != '4' - 10. 4 == '4' - 11. 4 === '4' - 12. Python ve jargonun uzunluğunu bulun ve yanlış bir karşılaştırma ifadesi yapın. - -6. console.log() kullanmadan önce aşağıdaki ifadelerin sonucunu bulun. Sonuca karar verdikten sonra console.log() kullanarak onaylayın. - 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') - 11. Hem dragon hem de python'da 'on' yoktur. - -7. Aşağıdaki etkinlikleri yapmak için Date nesnesini kullanın. - 1. Bugün yıl nedir? - 2. Bugünün ayı rakam olarak nedir? - 3. Bugünün tarihi nedir? - 4. Bugün sayı olarak gün nedir? - 5. Şimdi saat kaç? - 6. Dakika kaç şimdi? - 7. 1 Ocak 1970'den bugüne kadar geçen saniye sayısını bulun. - -### Egzersiz: Seviye 2 - -1. Kullanıcıdan üçgenin tabanını ve yüksekliğini girmesini ve bir üçgenin alanını hesaplamasını isteyen bir komut dosyası yazın (alan = 0,5 x b x h). - - ```sh - Enter base: 20 - Enter height: 10 - The area of the triangle is 100 - ``` - -1. Kullanıcıdan üçgenin a kenarını, b kenarını ve c kenarını girmesini ve üçgenin çevresini hesaplamasını isteyen bir komut dosyası yazın (çevre = a + b + c) - - ```sh - Enter side a: 5 - Enter side b: 4 - Enter side c: 3 - The perimeter of the triangle is 12 - ``` - -1. Komut istemini kullanarak uzunluk ve genişliği alın ve bir dikdörtgenin alanını hesaplayın (alan = uzunluk x genişlik ve dikdörtgenin çevresi (çevre = 2 x (uzunluk + genişlik)) -1. Komut istemini kullanarak yarıçapı alın ve bir dairenin alanını (alan = pi x r x r) ve bir dairenin çevresini (c = 2 x pi x r) hesaplayın, burada pi = 3.14. -1. y = 2x -2'nin eğimini, x kesme noktasını ve y kesme noktasını hesaplayın -1. Eğim m = (y2-y1)/(x2-x1). (2, 2) noktası ile (6,10) noktası arasındaki eğimi bulun -1. Yukarıdaki iki sorunun eğimini karşılaştırın. -1. y'nin değerini hesaplayın (y = x2 + 6x + 9). Farklı x değerleri kullanmayı deneyin ve y'nin hangi x değerinin 0 olduğunu bulun. -1. Kullanıcıdan saat ve saat başına oran girmesini isteyen bir komut dosyası yazın. Kişinin ücretini hesapla? - - ```sh - Enter hours: 40 - Enter rate per hour: 28 - Your weekly earning is 1120 - ``` - -1. Adınızın uzunluğu 7'den büyükse, adınız uzun, yoksa adınızın kısa olduğunu söyleyin. -1. Adınızın uzunluğunu ve soyadınızın uzunluğunu karşılaştırın ve bu çıktıyı almalısınız. - - ```js - let firstName = 'Asabeneh' - let lastName = 'Yetayeh' - ``` - - ```sh - Your first name, Asabeneh is longer than your family name, Yetayeh - ``` - -1. İki değişken _myAge_ ve _yourAge_ bildirin ve bunlara başlangıç değerleri ile myAge ve yourAge atayın. - - ```js - let myAge = 250 - let yourAge = 25 - ``` - - ```sh - I am 225 years older than you. - ``` - -1. İstemi kullanarak, kullanıcının doğduğu yılı alır ve kullanıcı 18 veya daha büyükse, kullanıcıya belirli bir süre beklemesini söylemediği takdirde, kullanıcının araba kullanmasına izin verir. - ```sh - - Enter birth year: 1995 - You are 25. You are old enough to drive - - Enter birth year: 2005 - You are 15. You will be allowed to drive after 3 years. - ``` - -1. Kullanıcıdan yıl sayısını girmesini isteyen bir komut dosyası yazın. Bir kişinin yaşayabileceği saniye sayısını hesaplayın. Birinin sadece yüz yıl yaşadığını varsayalım - - ```sh - Enter number of years you live: 100 - You lived 3153600000 seconds. - ``` - -1. Tarih saat nesnesini kullanarak insan tarafından okunabilir bir saat biçimi oluşturun - 1. YYYY-MM-DD HH:mm - 2. DD-MM-YYYY HH:mm - 3. DD/MM/YYYY HH:mm - -### Egzersiz: Seviye 3 - -1. Tarih saat nesnesini kullanarak insan tarafından okunabilir bir saat biçimi oluşturun. Saat ve dakika her zaman iki basamaklı olmalıdır (7 saat 07 ve 5 dakika 05 olmalıdır) - 1. YYY-MM-DD HH:mm eg. 20120-01-02 07:05 - -[<< Gün 2](../02_Day_Data_types/02_day_data_types.md) | [Gün 4 >>](../04_Day_Conditionals/04_day_conditionals.md) diff --git a/Turkish/04_Day_Conditionals/04_day_conditionals.md b/Turkish/04_Day_Conditionals/04_day_conditionals.md deleted file mode 100644 index 18c4d1a..0000000 --- a/Turkish/04_Day_Conditionals/04_day_conditionals.md +++ /dev/null @@ -1,386 +0,0 @@ -
-

30 Days Of JavaScript: Conditionals [ Koşullar ]

- - - - - Twitter Follow - - - Author: - Asabeneh Yetayeh
- January, 2020 -
-
- -[<< Gün 3](../03_Day_Booleans_operators_date/03_booleans_operators_date.md) | [Gün 5 >>](../05_Day_Arrays/05_day_arrays.md) - -![Thirty Days Of JavaScript](../../images/banners/day_1_4.png) - -- [📔 Gün 4](#-gün-4) - - [Conditionals - Koşullar](#conditionals-koşullar) - - [If](#if) - - [If Else](#if-else) - - [If Else if Else](#if--else-if-else) - - [Switch](#switch) - - [Ternary Operatörü](#ternary-operatörü) - - [💻 Egzersizler](#-exercises) - - [Egzersiz: Seviye 1](#egzersiz-seviye-1) - - [Egzersiz: Seviye 2](#egzersiz-seviye-2) - - [Egzersiz: Seviye 3](#egzersiz-seviye-3) - -# 📔 Gün 4 - -## Conditionals - Koşullar - -Koşullu ifadeler, farklı koşullara dayalı kararlar vermek için kullanılır. -Varsayılan olarak, JavaScript komut dosyasındaki ifadeler yukarıdan aşağıya doğru uygulanır. İşleme mantığı bunu gerektiriyorsa, ardışık yürütme akışı iki şekilde değiştirilebilir: - -- Koşullu yürütme: Belirli bir ifade doğruysa, bir veya daha fazla ifadeden oluşan bir blok yürütülür. -- Tekrarlayan yürütme : Belirli bir ifade doğru olduğu sürece, bir veya daha fazla ifadeden oluşan bir blok tekrar tekrar yürütülecektir. Bu bölümde _if_, _else_ , _else if_ deyimlerini ele alacağız. Önceki bölümlerde öğrendiğimiz karşılaştırma ve mantıksal operatörler burada faydalı olacaktır. - -Koşullar aşağıdaki yollarla uygulanabilir: - -- if -- if else -- if else if else -- switch -- ternary operator - -### If - -JavaScript ve diğer programlama dillerinde _if_ anahtar kelimesi, bir koşulun doğru olup olmadığını kontrol etmek ve blok kodunu yürütmek için kullanılır. Bir if koşulu kullanmak oluşturmak için normal parantez ve küme parantezlerine ihtiyaç duyurulur. ({}) - -```js -// syntax -if (condition) { - //kodun bu kısmı doğru koşul için çalışır -} -``` - -**Örnek:** - -```js -let num = 3 -if (num > 0) { - console.log(`${num} is a positive number`) -} -// 3 pozitif bir sayıdır -``` - -Yukarıdaki koşul örneğinde görebileceğiniz gibi 3, 0'dan büyüktür, yani pozitif bir sayıdır. Koşul doğruydu ve kod bloğu yürütüldü. Ancak koşul yanlışsa herhangi bir sonuç göremeyiz. - -```js -let isRaining = true -if (isRaining) { - console.log('Remember to take your rain coat.') -} -``` -Aynısı ikinci koşul için de geçerlidir, isRaining false ise if bloğu yürütülmez ve herhangi bir çıktı görmeyiz. Yanlış bir koşulun sonucunu görmek için, _else_ ile başka bir bloğumuz olmalıdır. - -### If Else - -Koşul doğruysa, ilk blok yürütülür, doğru değilse, __else__ koşul yürütülür. - -```js -// syntax -if (condition) { - // kodun bu kısmı doğru koşul için çalışır -} else { - // kodun bu kısmı yanlış koşul için çalışır -} -``` - -```js -let num = 3 -if (num > 0) { - console.log(`${num} is a positive number`) -} else { - console.log(`${num} is a negative number`) -} -// 3 pozitif bir sayıdır - -num = -3 -if (num > 0) { - console.log(`${num} is a positive number`) -} else { - console.log(`${num} is a negative number`) -} -// -3 negatif bir sayıdır -``` - -```js -let isRaining = true -if (isRaining) { - console.log('You need a rain coat.') -} else { - console.log('No need for a rain coat.') -} -// Bir yağmurluğa ihtiyacın var. - -isRaining = false -if (isRaining) { - console.log('You need a rain coat.') -} else { - console.log('No need for a rain coat.') -} -// Yağmurluğa gerek yok. -``` - -Son koşul yanlıştır, bu nedenle else bloğu yürütülmüştür. Ya ikiden fazla koşulumuz varsa? Bu durumda *else if* koşullarını kullanırdık. - - -### If Else if Else - -Hayatımızda günlük kararlar veririz. Kararları bir veya iki koşulu kontrol ederek değil, birden çok koşula göre veririz. Günlük hayatımızda olduğu gibi programlama da şartlarla doludur. Birden fazla koşulumuz olduğunda *else if* kullanırız. - -```js -// syntax -if (condition) { - // code -} else if (condition) { - // code -} else { - // code - -} -``` - -**Örnek:** - -```js -let a = 0 -if (a > 0) { - console.log(`${a} is a positive number`) -} else if (a < 0) { - console.log(`${a} is a negative number`) -} else if (a == 0) { - console.log(`${a} is zero`) -} else { - console.log(`${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.') -} -``` - -#### Çevirmen Açıklaması - -Arkadaşlar anlatıcı belirtmemiş lakin ben araya bunu şıkıştırayım. if doğruluğu kontrol eder bir kere kullanılır, else ise if çalışmadığında devreye girer buda bir kere kullanılır. -Birden fazla if yada else kullanamazsınız. Zaten birden fazla koşulu sorgulamak için else if blogu bulunmaktadır. Normalde else if açıklamasında bunu anlamanız gerekir. -Lakin ekstra bir açıklama yapalım kafanızda tam oturmuş olsun konu. Mutlu kalın. - - -### Switch - -Switch, **if else if else** için bir alternatiftir. -Switch ifadesi bir *switch* anahtar sözcüğüyle başlar, ardından bir parantez ve kod bloğu gelir. Kod bloğunun içinde farklı durumlarımız olacak. Case bloğu, switch parantezindeki değer vaka değeriyle eşleşirse çalışır. Break ifadesi, koşul yerine getirildikten sonra kod yürütmesini sonlandırmak içindir. Default blok, tüm durumlar koşulu karşılamıyorsa çalışır. - - -```js -switch(caseValue){ - case 1: - // code - break - case 2: - // code - break - case 3: - // code - break - default: - // code -} -``` - -```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 Diğer Örnekler -let dayUserInput = prompt('What day is today ?') -let 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.') -} - -``` - -// Durumlarda koşulları kullanmak için örnekler - -```js -let num = prompt('Enter number'); -switch (true) { - case num > 0: - console.log('Number is positive'); - break; - case num == 0: - console.log('Numbers is zero'); - break; - case num < 0: - console.log('Number is negative'); - break; - default: - console.log('Entered value was not a number'); -} -``` - -### Ternary Operatörü - -Koşullar yazmanın başka bir yolu da üçlü operatörleri kullanmaktır. Bunu diğer bölümlerde ele aldık, ancak burada da belirtmek gerekir. - -```js -let isRaining = true -isRaining - ? console.log('You need a rain coat.') - : console.log('No need for a rain coat.') -``` - -🌕 Olağanüstü birisin ve olağanüstü bir potansiyelin var. 4. gün zorluklarını yeni tamamladınız ve mükemmelliğe giden yolda dört adım öndesiniz. Şimdi beyniniz ve kasınız için bazı egzersizler yapın. - -## 💻 Egzersizler - -### Egzersiz: Seviye 1 - -1. prompt(“Enter your age:”) ile kullanıcı girdisi alın. Kullanıcı 18 veya daha büyükse, geri bildirimde bulunun:'Sürecek kadar yaşlısınız', ancak 18 değilse, 18 yaşına girmesi gereken yıl sayısını beklemeye başlayarak başka bir geri bildirim verin. - - ```sh - Enter your age: 30 - You are old enough to drive. - - Enter your age:15 - You are left with 3 years to drive. - ``` - -1. if… else kullanarak myAge ve yourAge değerlerini karşılaştırın. Karşılaştırmaya dayanarak ve sonucu kimin daha yaşlı olduğunu (ben veya siz) belirterek konsola kaydedin. Yaşı girdi olarak almak için komut prompt(“Enter your age:”) kullanın. - - ```sh - Enter your age: 30 - You are 5 years older than me. - ``` - -1. a, b'den büyükse, 'a b'den büyüktür', aksi takdirde 'a, b'den küçüktür' döndürür. şekilde uygulamaya çalışın - - - using if else - - ternary operator. - - ```js - let a = 4 - let b = 3 - ``` - - ```sh - 4 is greater than 3 - ``` - -1. Çift sayılar 2'ye tam bölünür kalan sıfırdır. Bir sayının çift olup olmadığını veya JavaScript kullanıp kullanmadığını nasıl kontrol edersiniz? - - ```sh - Enter a number: 2 - 2 is an even number - - Enter a number: 9 - 9 is is an odd number. - ``` - -### Egzersiz: Seviye 2 - -1. Öğrencilere puanlarına göre not verebilecek bir kod yazın: - - 80-100, A - - 70-89, B - - 60-69, C - - 50-59, D - - 0-49, F -1. Mevsimin Sonbahar, Kış, İlkbahar veya Yaz olup olmadığını kontrol edin. - Değerler : - - Eylül, Ekim veya Kasım, mevsim sonbahardır. - - Aralık, Ocak veya Şubat, mevsim kıştır. - - Mart, Nisan veya Mayıs mevsimi bahardır - - Haziran, Temmuz veya Ağustos, mevsim yazdır - -1. Bir günün hafta sonu mu yoksa iş günü mü olduğunu kontrol edin. Komut dosyanız girdi olarak gün alacaktır. - -```sh - What is the day today? Saturday - Saturday is a weekend. - - What is the day today? saturDaY - Saturday is a weekend. - - What is the day today? Friday - Friday is a working day. - - What is the day today? FrIDAy - Friday is a working day. - ``` - -### Egzersiz: Seviye 3 - -1. Bir aydaki gün sayısını söyleyen bir program yazın. - - ```sh - Enter a month: January - January has 31 days. - - Enter a month: JANUARY - January has 31 day - - Enter a month: February - February has 28 days. - - Enter a month: FEbruary - February has 28 days. - ``` - -1. Bir aydaki gün sayısını söyleyen bir program yazın, şimdi artık yılı düşünün. - - -🎉 TEBRİKLER ! 🎉 - -[<< Gün 3](../03_Day_Booleans_operators_date/03_booleans_operators_date.md) | [Gün 5 >>](../05_Day_Arrays/05_day_arrays.md) diff --git a/Turkish/05_Day_Arrays/05_day_arrays.md b/Turkish/05_Day_Arrays/05_day_arrays.md deleted file mode 100644 index f17f614..0000000 --- a/Turkish/05_Day_Arrays/05_day_arrays.md +++ /dev/null @@ -1,1536 +0,0 @@ - - - - -
- -

30 Days Of JavaScript: Arrays

- - - - - - - - - -Twitter Follow - - - - - -Author: - -Asabeneh Yetayeh
- - January, 2020 - -
- -
- - - -[<< Gün 4](../04_Day_Conditionals/04_day_conditionals.md) | [Gün 6 >>](../06_Day_Loops/06_day_loops.md) - - - -![Day 5](../../images/banners/day_1_5.png) - - - -- [📔 Gün 5](#-day-5) - - - [Diziler ( Array )](#arrays) - - - [Boş bir dizi nasıl oluşturulur](#boş-bir-dizi-nasıl-oluşturulur) - - - [Değerlere sahip bir dizi nasıl oluşturulur](#değerlere-sahip-bir-dizi-nasıl-oluşturulur) - - - [split kullanarak dizi oluşturmak](#split-kullanarak-dizi-oluşturmak) - - - [index kullanarak dizi elemanlarına ulaşmak](#index-kullanarak-dizi-elemanlarına-ulaşmak) - - - [Dizi elemanlarını düzenlemek](#dizi-elemanlarını-düzenlemek) - - - [Dizileri manüple edebilecek metotlar](#dizileri-manüple-edebilecek-metotlar) - - - [Dizi Constructor'ı ( yapıcı metot )](#dizi-constructor) - - - [fill ile statik değerler yaratmak](#fill-ile-statik-değerler-yaratmak) - - - [concat kullanarak dizileri birleştirmek](#concat-kullanarak-dizileri-birleştirmek) - - - [Dizi uzunluğuna ulaşmak ( length )](#dizi-uzunluğuna-ulaşmak) - - - [arr dizisinin içindeki index'e ulaşmak](#arr-dizisinin-içindeki-indexe-ulaşmak) - - - [Dizinin içindeki son index'e ulaşmak](#dizinin-içindeki-son-indexe-ulaşmak) - - - [Diziyi kontrol etmek](#diziyi-kontrol-etmek) - - - [Diziyi string'e çevirmek](#diziyi-stringe-çevirmek) - - - [Dizi elemanlarını Joinlemek](#dizi-elemanlarını-joinlemek) - - - [Dizi elemanlarını Slice etmek ( kesmek )](#dizi-elemanlarını-slice-etmek) - - - [Dizlerde Splice metodu](#dizilerde-splice-metodu) - - - [push kullanarak diziye eleman eklemek](#push-kullanarak-diziye-eleman-eklemek) - - - [pop kıllanarak diziden eleman çıkarmak](#pop-kullanarak-diziden-eleman-çıkarmak) - - - [Dizinin en başından eleman kaldırmak](#dizinin-en-başından-eleman-kaldırmak) - - - [Dizinin en başına eleman ekleme](#dizinin-en-başına-eleman-eklemek) - - - [Dizi sırasını ters'e çevirmek](#dizi-sırasını-terse-çevirmek) - - - [Dizi elemanlarını sıralamak](#dizi-elemanlarını-sıralamak) - - - [Dizi içinde Diziler](#dizi-içinde-diziler) - - - [💻 Egzersizler](#-Egzersizler) - - - [Egzersiz: Seviye 1](#egzersiz-seviye-1) - - - [Egzersiz: Seviye 2](#egzersiz-seviye-2) - - - [Egzersiz: Seviye 3](#egzersiz-seviye-3) - - - -# 📔 Gün 5 - - - -## Diziler - - - -Değişkenlerin aksine, diziler _Çoklu değerleri_ depolayabilirler. Dizi'deki her bir değer _index_'e sahiptir, ve her index _bellek adresindeki bir referans_'ı işaret eder. Bu _index'ler_ kullanılarak her bir değere ulaşım sağlanabilir. Bir dizinin index'i _sıfır_'dan başlar ve dizinin son elemanının index'i, dizinin uzunluğundan bir eksiktir. - - - -Bir dizi, sıralı ve değiştirilebilirdir. Farklı veri türlerinin bir koleksiyonudur. Bir dizi, tekrar edilen elemanların ve farklı veri türlerinin depolanmasına izin verir. Bir dizi boş olabilir veya farklı veri türü değerlerine sahip olabilir. - - - -### Boş bir dizi nasıl oluşturulur - - - -JavaScript'te birçok farklı yol ile dizi oluşturabiliriz. Bir dizi oluşturmanın farklı yollarını görelim. - -Bir dizi değişkeni tanımlamak için _let_ yerine _const_ kullanmak çok yaygındır. Const kullanıyorsanız, bu değişken adını bir daha kullanmayacağınız anlamına gelir. - - - -- Array constructor'ı ( yapıcı metot ) kullanmak - - - -```js - -// syntax - -const arr = Array() - -// ya da - -// let arr = new Array() - -console.log(arr) // [] - -``` - - - -- Köşeli parantez kullanmak([]) - - - -```js - -// syntax - -// Bu boş bir dizi oluşturmak için en çok tavsiye edilen yöntemdir - -const arr = [] - -console.log(arr) - -``` - - - -### Değerlere sahip bir dizi nasıl oluşturulur - - - -Başlangıç değerine sahip bir dizi. _length_ özelliğini kullanarak dizinin uzuluğunu bulabiliriz. - - - -```js - -const numbers = [0, 3.14, 9.81, 37, 98.6, 100] // sayı dizisi - -const fruits = ['banana', 'orange', 'mango', 'lemon'] // string dizisi, meyveler - -const vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] // string dizisi, sebzeler - -const animalProducts = ['milk', 'meat', 'butter', 'yoghurt'] // string dizisi, ürünler - -const webTechs = ['HTML', 'CSS', 'JS', 'React', 'Redux', 'Node', 'MongDB'] // string dizisi, web teknolojileri - -const countries = ['Finland', 'Denmark', 'Sweden', 'Norway', 'Iceland'] // string dizisi, ülkeler - - - -// Diziyi ve dizinin uzunluğunu yazdırmak - - - -console.log('Numbers:', numbers) - -console.log('Number of numbers:', numbers.length) - - - -console.log('Fruits:', fruits) - -console.log('Number of fruits:', fruits.length) - - - -console.log('Vegetables:', vegetables) - -console.log('Number of vegetables:', vegetables.length) - - - -console.log('Animal products:', animalProducts) - -console.log('Number of animal products:', animalProducts.length) - - - -console.log('Web technologies:', webTechs) - -console.log('Number of web technologies:', webTechs.length) - - - -console.log('Countries:', countries) - -console.log('Number of countries:', countries.length) - -``` - - - -```sh - -Numbers: [0, 3.14, 9.81, 37, 98.6, 100] - -Number of numbers: 6 - -Fruits: ['banana', 'orange', 'mango', 'lemon'] - -Number of fruits: 4 - -Vegetables: ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] - -Number of vegetables: 5 - -Animal products: ['milk', 'meat', 'butter', 'yoghurt'] - -Number of animal products: 4 - -Web technologies: ['HTML', 'CSS', 'JS', 'React', 'Redux', 'Node', 'MongDB'] - -Number of web technologies: 7 - -Countries: ['Finland', 'Estonia', 'Denmark', 'Sweden', 'Norway'] - -Number of countries: 5 - -``` - - - -- Dizinin farklı veri tiplerinde elemanları olabilir. - - - -```js - -const arr = [ - -'Asabeneh', - -250, - -true, - -{ country: 'Finland', city: 'Helsinki' }, - -{ skills: ['HTML', 'CSS', 'JS', 'React', 'Python'] } - -] // arr farklı veri tipleri içerir. - -console.log(arr) - -``` - - - -### Split kullanarak dizi oluşturmak - - -Önceki bölümde gördüğümüz gibi, bir diziyi farklı şekillerde bölebilir ve diziyi değiştirebiliriz. Aşağıdaki örneklere bir göz atalım. - - - -```js - -let js = 'JavaScript' - -const charsInJavaScript = js.split('') - - - -console.log(charsInJavaScript) // ["J", "a", "v", "a", "S", "c", "r", "i", "p", "t"] - - - -let companiesString = 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon' - -const companies = companiesString.split(',') - - - -console.log(companies) // ["Facebook", " Google", " Microsoft", " Apple", " IBM", " Oracle", " Amazon"] - -let txt = - -'I love teaching and empowering people. I teach HTML, CSS, JS, React, Python.' - -const words = txt.split(' ') - - - -console.log(words) - -// metnin özel karakterleri var, sadece kelimeleri nasıl alabileceğinizi düşünün - -// ["I", "love", "teaching", "and", "empowering", "people.", "I", "teach", "HTML,", "CSS,", "JS,", "React,", "Python"] - -``` - - - -### index kullanarak dizi elemanlarına ulaşmak - - - -Dizide elemanların indexlerini kullanarak o elemana ulaşabiliriz. Dizinin index'i 0'dan başlar. Aşşağıdaki resm her elemanın indexini açıkça göstermektedir. - - - -![arr index](../images/array_index.png) - - - -```js - -const fruits = ['banana', 'orange', 'mango', 'lemon'] - -let firstFruit = fruits[0] // 1. eleman'a o elemanın indexini kullanarak erişiyoruz. - - -console.log(firstFruit) // banana - - - -secondFruit = fruits[1] - -console.log(secondFruit) // orange - - - -let lastFruit = fruits[3] - -console.log(lastFruit) // lemon - -// Son eleman devam eden örnekteki gibi hesaplanabilir - - - -let lastIndex = fruits.length - 1 - -lastFruit = fruits[lastIndex] - - - -console.log(lastFruit) // lemon - -``` - - - -```js - -const numbers = [0, 3.14, 9.81, 37, 98.6, 100] // sayı dizisi - - - -console.log(numbers.length) // => dizinin uzunluğunu bilebiliriz. O da 6'dır - -console.log(numbers) // -> [0, 3.14, 9.81, 37, 98.6, 100] - -console.log(numbers[0]) // -> 0 - -console.log(numbers[5]) // -> 100 - - - -let lastIndex = numbers.length - 1; - -console.log(numbers[lastIndex]) // -> 100 - -``` - - - -```js - -const webTechs = [ - -'HTML', - -'CSS', - -'JavaScript', - -'React', - -'Redux', - -'Node', - -'MongoDB' - -] // Web teknolojilerinin Listesi - - - -console.log(webTechs) // Dizi elemanlarının hepsi - -console.log(webTechs.length) // => dizinin uzunluğunu bilebiliriz. O da 7'dir - -console.log(webTechs[0]) // -> HTML - -console.log(webTechs[6]) // -> MongoDB - - - -let lastIndex = webTechs.length - 1 - -console.log(webTechs[lastIndex]) // -> MongoDB - -``` - - - -```js - -const countries = [ - -'Albania', - -'Bolivia', - -'Canada', - -'Denmark', - -'Ethiopia', - -'Finland', - -'Germany', - -'Hungary', - -'Ireland', - -'Japan', - -'Kenya' - -] // List of countries - - - -console.log(countries) // -> Dizideki tüm ülkeler - -console.log(countries[0]) // -> Albania - -console.log(countries[10]) // -> Kenya - - - -let lastIndex = countries.length - 1; - -console.log(countries[lastIndex]) // -> Kenya - -``` - - - -```js - -const shoppingCart = [ - -'Milk', - -'Mango', - -'Tomato', - -'Potato', - -'Avocado', - -'Meat', - -'Eggs', - -'Sugar' - -] // Ürünler listesi - - - -console.log(shoppingCart) // -> shoppingCart Dizisi elemanlarının hepsi - -console.log(shoppingCart[0]) // -> Milk - -console.log(shoppingCart[7]) // -> Sugar - - - -let lastIndex = shoppingCart.length - 1; - -console.log(shoppingCart[lastIndex]) // -> Sugar - -``` - - - -### Dizi elemanlarını düzenlemek - - - -Bir dizi değiştirilebilir. Dizi yaratıldıktan sonra, elemanların içeriklerini değiştirebilir, modifiye edebiliriz. - - - -```js - -const numbers = [1, 2, 3, 4, 5] - -numbers[0] = 10 // index 0'daki 1 elemanını 10 elemanı olarak değiştirdik - -numbers[1] = 20 // index 2'deki 2 elemanını 20 elemanı olarak değiştirdik - - - -console.log(numbers) // [10, 20, 3, 4, 5] - - - -const countries = [ - -'Albania', - -'Bolivia', - -'Canada', - -'Denmark', - -'Ethiopia', - -'Finland', - -'Germany', - -'Hungary', - -'Ireland', - -'Japan', - -'Kenya' - -] - - - -countries[0] = 'Afghanistan' // Albania yerini Afghanistan aldı - -let lastIndex = countries.length - 1 - -countries[lastIndex] = 'Korea' // Kenya yerini Korea aldı - - - -console.log(countries) - -``` - - - -```sh - -["Afghanistan", "Bolivia", "Canada", "Denmark", "Ethiopia", "Finland", "Germany", "Hungary", "Ireland", "Japan", "Korea"] - -``` - - - -### Dizileri manüple edebilecek metotlar - - - -Diziyi manüple edebilmek için farklı metotlar vardır. Bunlar dizilerle uğraşmak için kullanışlı yöntemlerden bazılarıdır. Bu yöntemler: _Array, length, concat, indexOf, slice, splice, join, toString, includes, lastIndexOf, isArray, fill, push, pop, shift, unshift_ - - - -#### Dizi Constructor - - - - -Array:Bir dizi yaratmak için kullanılır. - - - -```js - -const arr = Array() // boş bir dizi yaratır - -console.log(arr) - - - -const eightEmptyValues = Array(8) // sekiz tane boş değer yaratır - -console.log(eightEmptyValues) // [empty x 8] - -``` - - - -#### fill ile statik değerler yaratmak - - - -fill: Bütün dizi elemanlarını statik değerle doldurur. - - - -```js - -const arr = Array() // Boş bir dizi yaratır - -console.log(arr) - - - -const eightXvalues = Array(8).fill('X') // 'X'değerine sahip 8 tane eleman oluşuturur. - -console.log(eightXvalues) // ['X', 'X','X','X','X','X','X','X'] - - - -const eight0values = Array(8).fill(0) // '0' değerine sahip 8 tane eleman oluşturur. - -console.log(eight0values) // [0, 0, 0, 0, 0, 0, 0, 0] - - - -const four4values = Array(4).fill(4) //'4' değerine sahip 8 tane eleman oluşturur. - -console.log(four4values) // [4, 4, 4, 4] - -``` - - - -#### Concat kullanarak dizileri birleştirmek - - - -concat: İki diziyi birbiri ile birleştirir. - -// Çevirmen notu : concat sadece iki diziyi birleştirmez. ikiden fazla sayıda diziyi birleştirmenize izin verir. - - - -```js - -const firstList = [1, 2, 3] - -const secondList = [4, 5, 6] - -const thirdList = firstList.concat(secondList) - - - -console.log(thirdList) // [1, 2, 3, 4, 5, 6] - -``` - - - -```js - -const fruits = ['banana', 'orange', 'mango', 'lemon'] // meyveler dizisi - -const vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] // sebzeler dizisi - -const fruitsAndVegetables = fruits.concat(vegetables) // iki diziyi birleştirdik - - - -console.log(fruitsAndVegetables) - -``` - - - -```sh - -["banana", "orange", "mango", "lemon", "Tomato", "Potato", "Cabbage", "Onion", "Carrot"] - -``` - - - -#### Dizi uzunluğuna ulaşmak - - - -Length:Dizi uzunluğunu bildirir. - - - -```js - -const numbers = [1, 2, 3, 4, 5] - -console.log(numbers.length) // -> Dizinin uzunluğu 5'tir - -``` - - - -#### Arr dizisinin içindeki indexe ulaşmak - - - -indexOf: O elemanın dizide olup olmadığını kontrol eder.Eğer o eleman dizide mevcutsa index numarasını, mevcut değilse -1 döner. - - -```js - -const numbers = [1, 2, 3, 4, 5] - - - -console.log(numbers.indexOf(5)) // -> 4 - -console.log(numbers.indexOf(0)) // -> -1 - -console.log(numbers.indexOf(1)) // -> 0 - -console.log(numbers.indexOf(6)) // -> -1 - -``` - - - -Bir dizide mevcut olup olmadığını kontrol edin. - - - -- Listedeki elemanları kontrol edin. - -```js - -// dizide bir banana olup olmadığını kontrol edelim - - - -const fruits = ['banana', 'orange', 'mango', 'lemon'] - -let index = fruits.indexOf('banana') // 0 - - - -if(index === -1){ - -console.log('This fruit does not exist in the array') - -} else { - -console.log('This fruit does exist in the array') - -} - -// This fruit does exist in the array - - - -// Burada ayrıca kısa if kullanabilirz. - -index === -1 ? console.log('This fruit does not exist in the array'): console.log('This fruit does exist in the array') - - - -// dizide bir avocado olup olmadığını kontrol edelim - -let indexOfAvocado = fruits.indexOf('avocado') // -1, eğer eleman dizide yoksa -1 döner - -if(indexOfAvocado === -1){ - -console.log('This fruit does not exist in the array') - -} else { - -console.log('This fruit does exist in the array') - -} - -// This fruit does not exist in the array - -``` - - - -#### Dizinin içindeki son indexe ulaşmak - - - -lastIndexOf: Dizideki son elemanın pozisyonunu verir. Eğer mevcutsa o elemanın index numarasını döner, mevcut değilse -1 döner. - - - -```js - -const numbers = [1, 2, 3, 4, 5, 3, 1, 2] - - - -console.log(numbers.lastIndexOf(2)) // 7 - -console.log(numbers.lastIndexOf(0)) // -1 - -console.log(numbers.lastIndexOf(1)) // 6 - -console.log(numbers.lastIndexOf(4)) // 3 - -console.log(numbers.lastIndexOf(6)) // -1 - -``` - - - -includes:Bir dizide bir öğenin olup olmadığını kontrol etmek için kullanılır.Mevcut ise, true değerini döndürür, aksi takdirde false değerini döndürür. - - - -```js - -const numbers = [1, 2, 3, 4, 5] - - - -console.log(numbers.includes(5)) // true - -console.log(numbers.includes(0)) // false - -console.log(numbers.includes(1)) // true - -console.log(numbers.includes(6)) // false - - - -const webTechs = [ - -'HTML', - -'CSS', - -'JavaScript', - -'React', - -'Redux', - -'Node', - -'MongoDB' - -] // Web teknolojileri dizisi - - - -console.log(webTechs.includes('Node')) // true - -console.log(webTechs.includes('C')) // false - -``` - - - -#### Diziyi kontrol etmek - - - -Array.isArray: Veri tipinin bir dizi olup olmadığını kontrol etmek için kullanılır. - - -```js - -const numbers = [1, 2, 3, 4, 5] - -console.log(Array.isArray(numbers)) // true - - - -const number = 100 - -console.log(Array.isArray(number)) // false - -``` - - - -#### Diziyi stringe çevirmek - - - -toString:Diziyi string bir ifadeye çevirir. - - - -```js - -const numbers = [1, 2, 3, 4, 5] - -console.log(numbers.toString()) // 1,2,3,4,5 - - - -const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook'] - -console.log(names.toString()) // Asabeneh,Mathias,Elias,Brook - -``` - - - -#### Dizi elemanlarını Joinlemek - - -join: Dizinin elemanlarını birleştirmek için kullanılır, join yönteminde ilettiğimiz argüman dizide birleştirilir ve bir dizi olarak döndürülür. Varsayılan olarak bir virgül ile birleşir, ancak elemanlar arasında birleştirilebilecek farklı dizi parametreleri iletebiliriz. - - - -```js - -const numbers = [1, 2, 3, 4, 5] - -console.log(numbers.join()) // 1,2,3,4,5 - - - -const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook'] - - - -console.log(names.join()) // Asabeneh,Mathias,Elias,Brook - -console.log(names.join('')) //AsabenehMathiasEliasBrook - -console.log(names.join(' ')) //Asabeneh Mathias Elias Brook - -console.log(names.join(', ')) //Asabeneh, Mathias, Elias, Brook - -console.log(names.join(' # ')) //Asabeneh # Mathias # Elias # Brook - - - -const webTechs = [ - -'HTML', - -'CSS', - -'JavaScript', - -'React', - -'Redux', - -'Node', - -'MongoDB' - -] // List of web technologies - - - -console.log(webTechs.join()) // "HTML,CSS,JavaScript,React,Redux,Node,MongoDB" - -console.log(webTechs.join(' # ')) // "HTML # CSS # JavaScript # React # Redux # Node # MongoDB" - -``` - - - -#### Dizi elemanlarını slice etmek - - - -Slice: Bir aralıktaki çoklu elemanları dilimler İki parametre alır. Bu parametreler, başlangıç ve bitiş konumlarıdır. Bitiş konumunu dahil etmez. - - -```js - -const numbers = [1,2,3,4,5] - - - -console.log(numbers.slice()) // -> Bütün öğeyi kopyalar - -console.log(numbers.slice(0)) // -> Bütün öğeyi kopyalar - -console.log(numbers.slice(0, numbers.length)) // Bütün öğeyi kopyalar - -console.log(numbers.slice(1,4)) // -> [2,3,4] // son elemanı dahil etmez - -``` - - - -#### Dizilerde splice metodu - - - -Splice: üç parametre alır :başlangıç konumu, kaldırılması gereken eleman sayısı ve eklenmesi gereken eleman sayısı. - - - -```js - -const numbers = [1, 2, 3, 4, 5] - -numbers.splice() - -console.log(numbers) // -> Bütün elemanları kaldırır - - - -``` - - - -```js - -const numbers = [1, 2, 3, 4, 5] - -numbers.splice(0,1) - -console.log(numbers) // ilk elemanı kaldırır - -``` - - - -```js - -const numbers = [1, 2, 3, 4, 5, 6] - -numbers.splice(3, 3, 7, 8, 9) - -console.log(numbers.splice(3, 3, 7, 8, 9)) // -> [1, 2, 3, 7, 8, 9] //2 eleman kaldırdı ve yerine 3 eleman ekledi - -``` - - - -#### Push kullanarak diziye eleman eklemek - - - -Push: Dizinin sonuna eleman ekler.Varolan bir diziye eleman eklemek için push metodunu kullanırız. - - -```js - -// syntax - -const arr = ['item1', 'item2','item3'] - -arr.push('new item') - -console.log(arr) - -// ['item1', 'item2','item3','new item'] - -``` - - - -```js - -const numbers = [1, 2, 3, 4, 5] - -numbers.push(6) - -console.log(numbers) // -> [1,2,3,4,5,6] - - - -numbers.pop() // -> Dizinin sonundan bir eleman çıkarır. - -console.log(numbers) // -> [1,2,3,4,5] - -``` - - - -```js - -let fruits = ['banana', 'orange', 'mango', 'lemon'] - -fruits.push('apple') - -console.log(fruits) // ['banana', 'orange', 'mango', 'lemon', 'apple'] - - - -fruits.push('lime') - -console.log(fruits) // ['banana', 'orange', 'mango', 'lemon', 'apple', 'lime'] - -``` - - - -#### pop kıllanarak diziden eleman çıkarmak - - - -pop: Dizinin sonundaki elemanı siler. - - - -```js - -const numbers = [1, 2, 3, 4, 5] - -numbers.pop() // -> Sondaki elemanı siler - -console.log(numbers) // -> [1,2,3,4] - -``` - - - -#### Dizinin en başından eleman kaldırmak - - - -shift: Dizinin en başındaki elemanı siler. - - - -```js - -const numbers = [1, 2, 3, 4, 5] - -numbers.shift() // -> baştan bir elemanı kaldırır. - -console.log(numbers) // -> [2,3,4,5] - -``` - - - -#### Dizinin en başına eleman eklemek - - - -unshift: Dizinin başına dizi elemanı ekler. - - - -```js - -const numbers = [1, 2, 3, 4, 5] - -numbers.unshift(0) // -> en başa eleman ekler - -console.log(numbers) // -> [0,1,2,3,4,5] - -``` - - - -#### Dizi sırasını terse çevirmek - - - -reverse: Dizi sıralamasını terse çevirir. - - - -```js - -const numbers = [1, 2, 3, 4, 5] - -numbers.reverse() // -> ters dizi sırası - -console.log(numbers) // [5, 4, 3, 2, 1] - - - -numbers.reverse() - -console.log(numbers) // [1, 2, 3, 4, 5] - -``` - - - -#### Dizi elemanlarını sıralamak - - -sort: Dizi elemanlarını alfabetik sırada düzenleyin.Sort call back fonksyonu alır, sort'un call back fonksiyonu ile nasıl kullandığımızı ilerleyen bölümlerde göreceğiz. - - - -```js - -const webTechs = [ - -'HTML', - -'CSS', - -'JavaScript', - -'React', - -'Redux', - -'Node', - -'MongoDB' - -] - - - -webTechs.sort() - -console.log(webTechs) // ["CSS", "HTML", "JavaScript", "MongoDB", "Node", "React", "Redux"] - - - -webTechs.reverse() // sortladıktan sonra reverse edebiliriz. - -console.log(webTechs) // ["Redux", "React", "Node", "MongoDB", "JavaScript", "HTML", "CSS"] - -``` - - - -### Dizi içinde diziler - - - -Diziler farklı veri tiplerinde elemanları ve yeni bir dizi de depolayabilirler Şimdi dizi içinde bir dizi tanımlayalım. - - -```js - -const firstNums = [1, 2, 3] - -const secondNums = [1, 4, 9] - - - -const arrayOfArray = [[1, 2, 3], [1, 2, 3]] - -console.log(arrayOfArray[0]) // [1, 2, 3] - - - -const frontEnd = ['HTML', 'CSS', 'JS', 'React', 'Redux'] - -const backEnd = ['Node','Express', 'MongoDB'] - -const fullStack = [frontEnd, backEnd] - -console.log(fullStack) // [["HTML", "CSS", "JS", "React", "Redux"], ["Node", "Express", "MongoDB"]] - -console.log(fullStack.length) // 2 - -console.log(fullStack[0]) // ["HTML", "CSS", "JS", "React", "Redux"] - -console.log(fullStack[1]) // ["Node", "Express", "MongoDB"] - -``` - - - -🌕 Çalışkansınız ve zaten çok şey başardınız. 5. gün zorluklarını yeni tamamladınız ve mükemmelliğe giden yolda 5 adım öndesiniz. Şimdi beyniniz ve kasınız için bazı egzersizler yapın. - - - -## 💻 Egzersizler - - - -### Egzersiz: Seviye 1 - - - -```js - -const countries = [ - -'Albania', - -'Bolivia', - -'Canada', - -'Denmark', - -'Ethiopia', - -'Finland', - -'Germany', - -'Hungary', - -'Ireland', - -'Japan', - -'Kenya' - -] - - - -const webTechs = [ - -'HTML', - -'CSS', - -'JavaScript', - -'React', - -'Redux', - -'Node', - -'MongoDB' - -] - -``` - - - -1. _boş_ bir dizi yaratın; - -2. Eleman sayısı 5'ten fazla olan bir dizi yaratın. - -3. Yarattığınız dizinin uzunluğunu bulun ( length ). - -4. Dizinizdeki ilk elemanı, ortadaki elemanı ve sondaki elemanı bulun. - -5. _mixedDataTypes_ adında bir dizi yaratın,dizinin içine farklı veri tiplerinde elemanlar koyun ve bu dizinin uzunluğunu bulun. Dizinin uzunluğu 5'ten büyük olmalıdır. - -6. ItCompanies adlı bir dizi değişkeni oluşturun ve Facebook, Google, Microsoft, Apple, IBM, Oracle ve Amazon'a başlangıç değerleri atayın. - -7. _console.log()_ kullanarak dizinizi yazdırın. - -8. Dizinin içindeki şirketlerin sayısın yazdırın. - -9. Dizinin içindeki ilk, ortadaki ve son elemanı yazdırın. - -10. Dizideki her şirketi yazdırın. - -11. Her bir şirketin adını tek tek büyük harfleri ile değişterin ( ör: facebook -> FACEBOOK) ve her birini yazdırın. - -12. Diziyi bir cümle gibi yazdırın: Facebook, Google, Microsoft, Apple, IBM,Oracle and Amazon are big IT companies. - -13. itCompanies dizisinde belirli bir şirketin olup olmadığını kontrol edin. Varsa şirketi geri döndürün, aksi takdirde _not found_ geri döndürün. - -14. Birden fazla 'o' harfi içeren şirketleri filter metodunu kullanmadan filtreleyin. - -15. _sort()_ metodunu kullanarak diziyi sıralayın. - -16. _reverse()_ metodunu kullanarak diziyi tersine çevirin. - -17. Diziden ilk 3 şirketi dilimleyin ( Slice edin ). - -18. Diziden son 3 şirketi dilimleyin ( Slice edin ). - -19. Ortadaki IT şirketini ya da şirketlerini diziden dilimleyin ( Slice edin ). - -20. İlk IT şirketini diziden kaldırın. - -21. Ortadaki IT şirketini ya da şirketlerini diziden kaldırın. - -22. Sondaki IT şirketini diziden kaldırın. - -23. Bütün IT şirketlerini kaldırın. - - - -### Egzersiz: Seviye 2 - - - -1.Ayrı bir country.js dosyası oluşturun ve country dizisini bu dosyaya kaydedin, ayrı bir web_techs.js dosyası oluşturun ve webTechs dizisini bu dosyaya kaydedin. Daha sonra Main.js dosyasından her iki dosyaya da erişim sağlayın. - -1. Önce bütün noktalama işaretlerini kaldırın ve ve string ifadeyi dizi olarak değiştirin ve dizideki kelime sayısını sayın. - - -```js - -let text = - -'I love teaching and empowering people. I teach HTML, CSS, JS, React, Python.' - -console.log(words) - -console.log(words.length) - -``` - - - -```sh - -["I", "love", "teaching", "and", "empowering", "people", "I", "teach", "HTML", "CSS", "JS", "React", "Python"] - -13 - -``` - - - -1. Aşşağıdaki alışveriş sepetindeki elemanları ekleyin, silin , düzenleyin. - - - -```js - -const shoppingCart = ['Milk', 'Coffee', 'Tea', 'Honey'] - -``` - - - -- Eğer alışveriş sepetine zaten 'Meat' eklenmemişse en başa ekleyin. - -- Eğer alışveriş sepetine zaten 'Sugar' eklenmemişse en sona ekleyin. - -- Eğer bala alerjiniz varsa 'Honey' elemanını diziden silin. - -- 'Tea' elemanını 'Green Tea' olarak güncelleyin. - -1. countries dizisinde 'Ethiopia' olup olmadığını kontrol edin. Eğer varsa 'ETHIOPIA' yazdırın. eğer yoksa bunu countries dizisine ekleyin. - -2. webTechs dizisinde Sass olup olmadığını kontrol edin eğer varsa 'Sass is a CSS preprocess' yazdırın. Eğer yoksa diziye Sass elemanını ekleyip diziyi yazdırın - -4. Aşağıdaki iki değişkeni birleştirin ve bir fullStack değişkeninde atayın. - - - -```js - -const frontEnd = ['HTML', 'CSS', 'JS', 'React', 'Redux'] - -const backEnd = ['Node','Express', 'MongoDB'] - -console.log(fullStack) - -``` - - - -```sh - -["HTML", "CSS", "JS", "React", "Redux", "Node", "Express", "MongoDB"] - -``` - - - -### Egzersiz: Seviye 3 - - - -1. Aşağıdaki dizide 10 öğrencinin yaşı vardır: - - - -```js - -const ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24] - -``` - - - -- Diziyi sıralayın ve en küçük ve en büyük yaşı bulun - -- Medyan yaşı bulun(dizinin ortasındaki eleman ama ortada iki eleman varsa elemanlar ikiye bölünür) - -- Ortalama yaşı bulun(tüm elemanlar eleman sayısına bölünür) - -- Yaş aralığını bulun (maks - min) - -- _abs()_ metodunu kullanarak (min - ortalama) ve (maks - ortalama) değerlerini karşılaştırın, - -1. [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) dizisinden ilk 10 ülkeyi dilimleyin ( Slice edin ) - -1. [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) dizisinden ortadaki ülkeleri bulun. - -2. countries dizisini çift ise iki eşit diziye bölün. countries dizisi çift değilse, ilk yarı için bir ülke fazla olarak bölün - -🎉 TEBRİKLER ! 🎉 - - - -[<< Gün 4](../04_Day_Conditionals/04_day_Conditionals.md) | [Gün 6 >>](../06_Day_Loops/06_day_loops.md) \ No newline at end of file diff --git a/Turkish/06_Day_Loops_Donguler/06_day_loops.md b/Turkish/06_Day_Loops_Donguler/06_day_loops.md deleted file mode 100644 index 76cf969..0000000 --- a/Turkish/06_Day_Loops_Donguler/06_day_loops.md +++ /dev/null @@ -1,451 +0,0 @@ -
-

30 Günde JavaScript: Loops - Döngüler

- - - - - Twitter Follow - - - Author: - Asabeneh Yetayeh
- Çevirmen: - Hasan Hüseyin Alav
- Temmuz 2022 -
-
- -[<< 5. Gün](../05_Day_Arrays/05_day_arrays.md) | [7. Gün >>](../07_Day_Functions/07_day_functions.md) - -![Day 6](/images/banners/day_1_6.png) - -- [📔 6. gün](#-day-6) - - [Loops - Döngüler](#loops) - - [For Döngüsü](#for-loop---for-döngüsü) - - [while Döngüsü](#while-loop---while-döngüsü) - - [do while Döngüsü](#do-while-loop-do-while-döngüsü) - - [for of Döngüsü](#for-of-loop---for-of-döngüsü) - - [break](#break) - - [continue](#continue) - - [💻 Alıştırmalar - Pratik: 6. Gün](#💻-alıştırma---prtik-6-gün) - - [Alıştırmalar - Pratik: 1. Seviye](#pratik-1-seviye) - - [Alıştırmalar - Pratik: 2. Seviye](#pratik-2-seviye) - - [Alıştırmalar - Pratik: 3. Seviye](#pratik-3-seviye) - -# 📔 6. Gün - -## Loops - Döngüler - -Yazılım kariyerimizde bir çok defa aynı işi tekrar tekrar yapmamız gerekebilir. Basit olarak Console.log() kullanarak 0'den 100'e kadar çıktı yazdırmayı deneyelim. Bu basit uygulamayı gerçekleştirmek bile 2 ila 5 dakika arasında zamanımızı alabilir; bu tür yorucu ve tekrarlayan görevler döngü kullanılarak gerçekleştirilebilir. Videoları izlemeyi tercih ediyorsanız. [video örnekleri](https://www.youtube.com/channel/UCM4xOopkYiPwJqyKsSqL9mw) - -Tekrar eden görevleri gerçekleştirmek için programlama dillerinde farklı döngü türleri kullanırız. Aşağıdaki örnekler, JavaScript ve diğer programlama dillerinde yaygın olarak kullanılan döngülerdir. - -### for Loop - for Döngüsü - -```js -// For Döngüsünün yapısı -for(başlangıç_değeri, şart, arttırma/azaltma){ - // uygulamak istediğimiz kod -} -``` - -```js -for(let i = 0; i <= 5; i++){ - console.log(i) -} - -// 0 1 2 3 4 5 -``` - -```js -for(let i = 5; i >= 0; i--){ - console.log(i) -} - -// 5 4 3 2 1 0 -``` - -```js -for(let i = 0; i <= 5; i++){ - console.log(`${i} * ${i} = ${i * i}`) -} -``` - -```sh -0 * 0 = 0 -1 * 1 = 1 -2 * 2 = 4 -3 * 3 = 9 -4 * 4 = 16 -5 * 5 = 25 -``` - -```js -const countries = ['Finland', 'Sweden', 'Denmark', 'Norway', 'Iceland'] -const newArr = [] -for(let i = 0; i < countries.length; i++){ - newArr.push(countries[i].toUpperCase()) -} - -// ["FINLAND", "SWEDEN", "DENMARK", "NORWAY", "ICELAND"] -``` - -Dizideki tüm elemanları toplama - -```js -const numbers = [1, 2, 3, 4, 5] -let sum = 0 -for(let i = 0; i < numbers.length; i++){ - sum = sum + numbers[i] - // daha pratik kullanım için, sum += numbers[i] - -} - -console.log(sum) // 15 -``` - -Mevcut diziyi temel alan yeni bir dizi oluşturma - -```js -const numbers = [1, 2, 3, 4, 5] -const newArr = [] -let sum = 0 -for(let i = 0; i < numbers.length; i++){ - newArr.push( numbers[i] ** 2) - -} - -console.log(newArr) // [1, 4, 9, 16, 25] -``` - -```js -const countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland'] -const newArr = [] -for(let i = 0; i < countries.length; i++){ - newArr.push(countries[i].toUpperCase()) -} - -console.log(newArr) // ["FINLAND", "SWEDEN", "NORWAY", "DENMARK", "ICELAND"] -``` - -### while loop - while Döngüsü - -while anahtar kelimesinin yanında belirtilen şarta doğru olduğu sürece çalışan bir döngü türüdür. Eğer koşul sürekli doğru çıkacak şekilde ayarlanırsa while döngüsü uygulama kasten kesilmediği sürece sonsuza kadar devam edebilir. Bu yüzden buraya dikkat etmek gerekebilir. - -```js -let i = 0 -while (i <= 5) { - console.log(i) - i++ -} - -// 0 1 2 3 4 5 -``` - -### do while loop do while döngüsü - - -do while döngüsü Koşul ile belirtilen alanın doğru olup olmadığına bakmadan kod bloğunu bir kez çalıştırır ve daha sonra Koşul ile belirtilen alan doğru (true) olduğu sürece kod bloğunun çalışması için kullanılır. - -```js -let i = 0 -do { - console.log(i) - i++ -} while (i <= 5) - -// 0 1 2 3 4 5 -``` - -### for of loop - for of döngüsü - -ES6, geleneksel bir döngüden daha basit olan bir döngü olan yeni bir döngü yöntemi sunar ve her tür için ve giriş döngülerinin eksikliklerini telafi eder. - -`for..of `Deyimi, yinelenen nesneler üzerinde yinelemek için bir döngü oluşturur. ES6'da tanıtılan `for..of` döngü , yeni yinelemeli protokollerin yerini alır. `for..in` ve `forEach()` destekler. `for..of` Array (Diziler), String (Metinler), Map (Haritalar), Set (Kümeler), Array benzeri nesneler (örneğin arguments veya NodeList), ve diğer yinelenen veri yapıları arasında yineleme yapmanızı sağlar. - -```js -for (const element of arr) { - // uygulamak istediğimiz kod -} -``` - -```js - -const numbers = [1, 2, 3, 4, 5] - -for (const num of numbers) { - console.log(num) -} - -// 1 2 3 4 5 - -for (const num of numbers) { - console.log(num * num) -} - -// 1 4 9 16 25 - -// array içindeki tüm nsayıları toplama -let sum = 0 -for (const num of numbers) { - sum = sum + num - // daha pratik kullanım için, sum += num - // bundan sonra pratik olan bu syntax türünün kullanacağız(+=, -=, *=, /= etc) -} -console.log(sum) // 15 - -const webTechs = [ - 'HTML', - 'CSS', - 'JavaScript', - 'React', - 'Redux', - 'Node', - 'MongoDB' -] - -for (const tech of webTechs) { - console.log(tech.toUpperCase()) -} - -// HTML CSS JAVASCRIPT REACT NODE MONGODB - -for (const tech of webTechs) { - console.log(tech[0]) // her öğenin yalnızca ilk harfini alın, H C J R N M -} - -``` - -```js -const countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland'] -const newArr = [] -for(const country of countries){ - newArr.push(country.toUpperCase()) -} - -console.log(newArr) // ["FINLAND", "SWEDEN", "NORWAY", "DENMARK", "ICELAND"] -``` - -### break - -Break, bir döngüyü kesmek için kullanılır. - -```js -for(let i = 0; i <= 5; i++){ - if(i == 3){ - break; - } - console.log(i) -} - -// 0 1 2 -``` - - i değeri 3 sayısına eşit olduğunda döngüyü durdurur -### continue - -Belirli bir döngü aşamasını atlamak için `continue` anahtar kelimesi kullanılır. - -```js -for(let i = 0; i <= 5; i++){ - if(i == 3){ - continue - } - console.log(i) -} - -// 0 1 2 4 5 -``` - -🌕 Adım adım öğrenmeye devam. 6. günü başarıyla bitirdiğmize göre şimdi sıra alıştırma ve pratik yapmada. - -## 💻 Alıştırma - Prtik: 6. Gün - -### Pratik: 1. seviye - - ```js - const countries = [ - 'Albania', - 'Bolivia', - 'Canada', - 'Denmark', - 'Ethiopia', - 'Finland', - 'Germany', - 'Hungary', - 'Ireland', - 'Japan', - 'Kenya' - ] - - const webTechs = [ - 'HTML', - 'CSS', - 'JavaScript', - 'React', - 'Redux', - 'Node', - 'MongoDB' - ] - - const mernStack = ['MongoDB', 'Express', 'React', 'Node'] - ``` - -1. while ve do while kullanarak 0 dan 10'a kadar giden bir döngü kurun. -2. while ve do while kullanarak 10 dan 0'a kadar giden bir döngü kurun. -3. 0'dan n' e kadar giden bir for döngüsü kurun. -4. Console.log() kullanarak aşağıdaki çıktıyı almayı deneyin. - - ```js - # - ## - ### - #### - ##### - ###### - ####### - ``` - -5. Aşağıdaki çıktıyı almak için bir döngü kurun: - - ```sh - 0 x 0 = 0 - 1 x 1 = 1 - 2 x 2 = 4 - 3 x 3 = 9 - 4 x 4 = 16 - 5 x 5 = 25 - 6 x 6 = 36 - 7 x 7 = 49 - 8 x 8 = 64 - 9 x 9 = 81 - 10 x 10 = 100 - ``` - -6. Aşağıdaki çıktıyı almak için bir döngü kurun: - - ```sh - i i^2 i^3 - 0 0 0 - 1 1 1 - 2 4 8 - 3 9 27 - 4 16 64 - 5 25 125 - 6 36 216 - 7 49 343 - 8 64 512 - 9 81 729 - 10 100 1000 - ``` - -7. 0'dan 100'e kadar olan çift sayıları bir döngü yardımı ile ekrana yazdırın. -8. 0'dan 100'e kadar olan tek sayıları bir döngü yardımı ile ekrana yazdırın -9. 0'dan 100'e kadar olan asal sayıları bir döngü yardımı ile ekrana yazdırın -10. 0 ile 100 arasındaki tüm sayıların toplamını ekrana yazıdırn - - ```sh - 0 ile 100 arasındaki sayıların toplamı: 5050. - ``` - -11. 0 ile 100 arasındaki tek ve çift sayıların toplamını bulun - - ```sh - Çift sayıların toplamı 2550 - Tek sayıların toplamı 2500 - ``` - -### Pratik: 2. seviye - -1. Herhangi bir sayıda rastgele id numarası atayan bir fonksiyon yazın - - ```sh - fe3jo1gl124g - ``` - - ```sh - xkqci4utda1lmbelpkm03rba - ``` - -2. Rastgele hexadecimal sayı üreten bir fonksiyon yazın. - - ```sh - '#ee33df' - ``` - -3. Rastgele bir rgb renk numarası oluşturan fonksiyon yazın. - - ```sh - rgb(240,180,80) - ``` - - ```sh - ["ALBANIA", "BOLIVIA", "CANADA", "DENMARK", "ETHIOPIA", "FINLAND", "GERMANY", "HUNGARY", "IRELAND", "JAPAN", "KENYA"] - ``` - -4. Yukarıdaki array'i kullanarak rastgele yeni bir dizi oluşturun. - -5. Yukarıdaki array'i kullanarak ülkelerin harf uzunluklarını içeren bir dizi olşturun'. - - ```sh - [7, 7, 6, 7, 8, 7, 7, 7, 7, 5, 5] - ``` - -6. Yukarıdaki diziyi kullanarak aşağıdaki diziyi oluşturun: - - ```sh - [ - ['Albania', 'ALB', 7], - ['Bolivia', 'BOL', 7], - ['Canada', 'CAN', 6], - ['Denmark', 'DEN', 7], - ['Ethiopia', 'ETH', 8], - ['Finland', 'FIN', 7], - ['Germany', 'GER', 7], - ['Hungary', 'HUN', 7], - ['Ireland', 'IRE', 7], - ['Iceland', 'ICE', 7], - ['Japan', 'JAP', 5], - ['Kenya', 'KEN', 5] - ] - ``` - -7. Yukarıdaki ülkeler dizisinde "land" sözcüğünü içeren bir ülke veya ülke olup olmadığını kontrol edin. "land" içeren ülkeler varsa bunu dizi halinde yazdırın. - - ```sh - ['Finland','Ireland', 'Iceland'] - ``` - -8. Yukarıdaki ülkeler dizisinde "ia" sözcüğünü içeren bir ülke veya ülke olup olmadığını kontrol edin. "ia" içeren ülkeler varsa bunu dizi halinde yazdırın.. - - ```sh - ['Albania', 'Bolivia','Ethiopia'] - ``` - -9. Yukarıdaki ülkeler dizisini kullanarak en fazla karakter içeren ülkeyi bulun. - - ```sh - Ethiopia - ``` - -10. Yukarıdaki ülkeler dizisini kullanarak, yalnızca 5 karakter içeren ülkeyi bulun. - - ```sh - ['Japan', 'Kenya'] - ``` - - -### Pratik: 3. seviye - -1. Countries dizisini kopyalayın(Avoid mutation) -2. Diziler değişebilir. Dizinin orjinalini değişirmeden bir kopyasını oluşturun. Oluşturduğunuz diziyi alfabetik olarak sıralayın ve sortedCountries dizisine atayın -3. webTechs dzisini ve mernStack dizisini sıralayın -4. [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js)inden "land" sözüğü ile biten ülkeleri farklı bir diziye atayın -5. [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) inden en uzun karakterli ülkeyi bulun -6. [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) inde 4 karakterli ülkeleri yazdırın -7. [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) inde iki veya daha fazla kelime içieren ülkeleri farklı bir diziye atayın -8. [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) i ters çevirin ve ülkelerin tüm harflerini büyük hale gertirin - -🎉 Tebrikler ! 🎉 - -[<< 6. Gün](../05_Day_Arrays/05_day_arrays.md) | [7. Gün >>](../07_Day_Functions/07_day_functions.md) diff --git a/Turkish/06_Day_Loops_Donguler/06_day_starter/data/countries.js b/Turkish/06_Day_Loops_Donguler/06_day_starter/data/countries.js deleted file mode 100644 index d0c4ec4..0000000 --- a/Turkish/06_Day_Loops_Donguler/06_day_starter/data/countries.js +++ /dev/null @@ -1,195 +0,0 @@ -const countries = [ - 'Afghanistan', - 'Albania', - 'Algeria', - 'Andorra', - 'Angola', - 'Antigua and Barbuda', - 'Argentina', - 'Armenia', - 'Australia', - 'Austria', - 'Azerbaijan', - 'Bahamas', - 'Bahrain', - 'Bangladesh', - 'Barbados', - 'Belarus', - 'Belgium', - 'Belize', - 'Benin', - 'Bhutan', - 'Bolivia', - 'Bosnia and Herzegovina', - 'Botswana', - 'Brazil', - 'Brunei', - 'Bulgaria', - 'Burkina Faso', - 'Burundi', - 'Cambodia', - 'Cameroon', - 'Canada', - 'Cape Verde', - 'Central African Republic', - 'Chad', - 'Chile', - 'China', - 'Colombi', - 'Comoros', - 'Congo (Brazzaville)', - 'Congo', - 'Costa Rica', - "Cote d'Ivoire", - 'Croatia', - 'Cuba', - 'Cyprus', - 'Czech Republic', - 'Denmark', - 'Djibouti', - 'Dominica', - 'Dominican Republic', - 'East Timor (Timor Timur)', - 'Ecuador', - 'Egypt', - 'El Salvador', - 'Equatorial Guinea', - 'Eritrea', - 'Estonia', - 'Ethiopia', - 'Fiji', - 'Finland', - 'France', - 'Gabon', - 'Gambia, The', - 'Georgia', - 'Germany', - 'Ghana', - 'Greece', - 'Grenada', - 'Guatemala', - 'Guinea', - 'Guinea-Bissau', - 'Guyana', - 'Haiti', - 'Honduras', - 'Hungary', - 'Iceland', - 'India', - 'Indonesia', - 'Iran', - 'Iraq', - 'Ireland', - 'Israel', - 'Italy', - 'Jamaica', - 'Japan', - 'Jordan', - 'Kazakhstan', - 'Kenya', - 'Kiribati', - 'Korea, North', - 'Korea, South', - 'Kuwait', - 'Kyrgyzstan', - 'Laos', - 'Latvia', - 'Lebanon', - 'Lesotho', - 'Liberia', - 'Libya', - 'Liechtenstein', - 'Lithuania', - 'Luxembourg', - 'Macedonia', - 'Madagascar', - 'Malawi', - 'Malaysia', - 'Maldives', - 'Mali', - 'Malta', - 'Marshall Islands', - 'Mauritania', - 'Mauritius', - 'Mexico', - 'Micronesia', - 'Moldova', - 'Monaco', - 'Mongolia', - 'Morocco', - 'Mozambique', - 'Myanmar', - 'Namibia', - 'Nauru', - 'Nepal', - 'Netherlands', - 'New Zealand', - 'Nicaragua', - 'Niger', - 'Nigeria', - 'Norway', - 'Oman', - 'Pakistan', - 'Palau', - 'Panama', - 'Papua New Guinea', - 'Paraguay', - 'Peru', - 'Philippines', - 'Poland', - 'Portugal', - 'Qatar', - 'Romania', - 'Russia', - 'Rwanda', - 'Saint Kitts and Nevis', - 'Saint Lucia', - 'Saint Vincent', - 'Samoa', - 'San Marino', - 'Sao Tome and Principe', - 'Saudi Arabia', - 'Senegal', - 'Serbia and Montenegro', - 'Seychelles', - 'Sierra Leone', - 'Singapore', - 'Slovakia', - 'Slovenia', - 'Solomon Islands', - 'Somalia', - 'South Africa', - 'Spain', - 'Sri Lanka', - 'Sudan', - 'Suriname', - 'Swaziland', - 'Sweden', - 'Switzerland', - 'Syria', - 'Taiwan', - 'Tajikistan', - 'Tanzania', - 'Thailand', - 'Togo', - 'Tonga', - 'Trinidad and Tobago', - 'Tunisia', - 'Turkey', - 'Turkmenistan', - 'Tuvalu', - 'Uganda', - 'Ukraine', - 'United Arab Emirates', - 'United Kingdom', - 'United States', - 'Uruguay', - 'Uzbekistan', - 'Vanuatu', - 'Vatican City', - 'Venezuela', - 'Vietnam', - 'Yemen', - 'Zambia', - 'Zimbabwe' -] diff --git a/Turkish/06_Day_Loops_Donguler/06_day_starter/index.html b/Turkish/06_Day_Loops_Donguler/06_day_starter/index.html deleted file mode 100644 index 2b6cbab..0000000 --- a/Turkish/06_Day_Loops_Donguler/06_day_starter/index.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - 30DaysOfJavaScript:06 Day - - - -

30DaysOfJavaScript:06 Day

-

Loops

- - - - - - - \ No newline at end of file diff --git a/Turkish/06_Day_Loops_Donguler/06_day_starter/scripts/main.js b/Turkish/06_Day_Loops_Donguler/06_day_starter/scripts/main.js deleted file mode 100644 index 421fb87..0000000 --- a/Turkish/06_Day_Loops_Donguler/06_day_starter/scripts/main.js +++ /dev/null @@ -1,2 +0,0 @@ -console.log(countries) -alert('Open the console and check if the countries has been loaded') \ No newline at end of file diff --git a/Turkish/07_Day_Functions/07_day_functions.md b/Turkish/07_Day_Functions/07_day_functions.md deleted file mode 100644 index 74e1858..0000000 --- a/Turkish/07_Day_Functions/07_day_functions.md +++ /dev/null @@ -1,717 +0,0 @@ -
-

30 günde JavaScript: Fonksiyonlar

- - - - - Twitter Follow - - - Author: - Asabeneh Yetayeh
- Çevirmen: - Hasan Hüseyin Alav
- Temmuz 2022 -
-
- -[<< 6. Gün](../06_Day_Loops_Donguler/06_day_loops.md) | [8. Gün >>](../08_Day_Objects/08_day_objects.md) - -![Thirty Days Of JavaScript](/images/banners/day_1_7.png) - -- [📔 7. Gün](#-day-7) - - [Functions - Fonksiyonlar](#functions---fonksiyonlar) - - [Klasik fonksiyon Tanımlama](#klasik-fonksiyon-tanımlama) - - [Anonymous Function - İsimsiz fonksiyon](#anonymous-function---i̇simsiz-fonksiyon) - - [Expression Function](#expression-function) - - [Parametresiz ve dönüş değeri olmayan fonksiyon](#parametresiz-ve-dönüş-değeri-olamayan-fonksiyon) - - [Fonksiyonlarda return kullanımı](#bir-değer-döndüren-fonksiyon) - - [Bir parametreli fonksiyon](#parametreli-fonksiyon) - - [İki parametreli fonksiyon](#i̇ki-parametreli-fonksiyon) - - [Çok parametreli fonksiyon](#çok-parametreli-fonksiyon) - - [Sınırsız sayıda parametreyle çalışan fonksiyon](#sınırsız-sayıda-parametreyle-çalışan-fonksiyon) - - [Klasik fonksiyonda sınırsız sayıda parametre](#klasik-fonksiyonda-sınırsız-sayıda-parametre) - - [Kendi kendine çağırılan fonksiyon - Self Invokinf function](#kendi-kendine-çağırılan-fonksiyon) - - [Arrow Function](#arrow-function) - - [Arrow function'da sınırsız sayıda parametre](#arrow-functionda-sınırsız-sayıda-parametre) - - [Default parametre ile fonksiyon kullanımı](#default-parametre-ile-fonksiyon-kullanımı) - - [Function declaration versus Arrow function](#function-declaration-versus-arrow-function) - - [💻 Exercises](#-exercises) - - [Exercises: Level 1](#exercises-level-1) - - [Exercises: Level 2](#exercises-level-2) - - [Exercises: Level 3](#exercises-level-3) - -# 📔 7. Gün - -## Functions - Fonksiyonlar - - -Şimdiye kadar birçok JavaScript fonksiyonu yazdık. Bu bölümde, custom fonksiyonlara odaklanacağız. Fonksiyon yazmaya başlamadan önce, fonksiyonun ne olduğunu ve neden fonksiyona ihtiyacımız olduğunu bakalım. - -Bir fonksiyon, belirli bir görevi gerçekleştirmek üzere tasarlanmış ve yeniden kullanılabilir bir kod bloğu veya programlama tanımıdır. - -Bir fonksiyon, `function` anahtar kelimesi ardından gelen o fonksiyona ait fonksiyon ismi ve parantezler ile tanımlanır. Bu paranteler fonksiyona parametre atayabilmemizi sağlar. Şayet fonksiyon parametre alırsa bu parametre fonksiyon scope'u içerisinde geçerli olan bir değişkendir. Farklı bir kullanım olarak da bu parametreye default değerler atayabiliriz. Eğer bir fonksiyon yardımı ile veri taşımak istiyorsak söz konusu fonksiyonun belirli bir veri türünü geriye değişken olarak döndürmesi gerekir. Daha sonra dönen bu değişkeni bir başka değişkene atayarak kullanabilir. - -Fonksiyon kullanmanın avantajları: - -- temiz ve okunması kolay -- yeniden kullanılabilir -- kolay test edilir - -Bir fonksiyon birkaç şekilde tanımlanabilir: - -- _Klasik Declaration function_ -- _Expression function_ -- _Anonymous function_ -- _Arrow function_ - -### Klasik Fonksiyon Tanımlama - -Bir fonksiyonun nasıl tanımlanacağını ve çağırılacağını görelim. - -```js -//parametresiz fonksiyon tanımıı -function functionName() { - // istenilen kod parçası -} -functionName() // fonksiyon, fonksiyon adı ve parantezler ile çağırılır -``` - -### Anonymous Function - İsimsiz Fonksiyon - - -```js -const anonymousFun = function() { - console.log( - 'İsimsiz bir fonksiyonum ve değerim anonim olarak saklanıyor' - ) -} -``` - -### Expression Function - - -Expression function, isimsiz fonksiyonlardır. İsimsiz bir fonksiyon oluşturduktan sonra bir değişkene atayarak kullanırız. Fonksiyondan bir değer geri döndürmek için değişkeni çağırmalıyız. Örnek vemrek gerekirse. - -```js - -// Function expression -const square = function() { - console.log("Bu bir expression function türünde fonksiyondur") -} - -``` - -### Parametresiz ve dönüş değeri olamayan fonksiyon - -Fonksiyon, parametre olmadan tanımlanabilir. (Şu ana kadar tanımladıklarımız zaten parametresizdi) - -**Example:** - -```js -function square() { - let num = 2 - let square = num * num - console.log(square) -} - -square() // 4 - -// parametresiz fonksiyon örnek 2: -function addTwoNumbers() { - let numOne = 10 - let numTwo = 20 - let sum = numOne + numTwo - - console.log(sum) -} - -addTwoNumbers() // fonksiyon, kendisine verilen isim ile çağırılmalı -``` - -```js - function printFullName (){ - let firstName = 'Asabeneh' - let lastName = 'Yetayeh' - let space = ' ' - let fullName = firstName + space + lastName - console.log(fullName) -} - -printFullName() // fonksiyon çağırımına bir örnek -``` - -### Bir değer döndüren fonksiyon - -Fonksiyonlar geriye bir değer döndürebilir. bu işlemi `return` anahtar kelimesini kullanarak sağlarız. Normal fonksiyondan farklı olarak bir field'a atanabilir veya bir metot içerisinde parametre olarak kullanılabilir. - -```js -function printFullName (){ - let firstName = 'Asabeneh' - let lastName = 'Yetayeh' - let space = ' ' - let fullName = firstName + space + lastName - return fullName -} -console.log(printFullName()) -``` - -```js - - function addTwoNumbers() { - let numOne = 2 - let numTwo = 3 - let total = numOne + numTwo - return total - - } - -console.log(addTwoNumbers()) -``` - -### Parametreli fonksiyon - -Bir fonksiyonda farklı veri türlerini (number, string, boolean, object, function) parametre olarak geçebiliriz. - -```js -// bir parametreli fonksiyon -function functionName(parm1) { - // istenilen kod parçası -} -functionName(parm1) // fonksiyonu çağırma sırasında parantezler arasına bir parametreye ihtiyaç duyar - -function areaOfCircle(r) { - let area = Math.PI * r * r - return area -} - -console.log(areaOfCircle(10)) // bağımsız bir değişkenle çağırılmalı - -function square(number) { - return number * number -} - -console.log(square(10)) -``` - -### İki parametreli fonksiyon - -```js -// iki parametreli fonksiyon -function functionName(parm1, parm2) { - //istenilen kod parçası -} -functionName(parm1, parm2) //fonksiyonu çağırma sırasında parantezler arasında iki tane parametreye ihtiyaç duyar - -// Parametresiz fonksiyon giriş yapmaz, bu nedenle parametrelerle bir fonksiyon yapalım -function sumTwoNumbers(numOne, numTwo) { - let sum = numOne + numTwo - console.log(sum) -} -sumTwoNumbers(10, 20) // fonksiyon çağırımı -// Bir fonksiyon değer döndürmezse veri depolayamaz, bu nedenle değer döndürmelidir. - -function sumTwoNumbers(numOne, numTwo) { - let sum = numOne + numTwo - return sum -} - -console.log(sumTwoNumbers(10, 20)) -function printFullName(firstName, lastName) { - return `${firstName} ${lastName}` -} -console.log(printFullName('Asabeneh', 'Yetayeh')) -``` - -### Çok parametreli fonksiyon - -```js -// çok parametreli fonksiyon -function functionName(parm1, parm2, parm3,...){ - //istenilen kod parçası -} -functionName(parm1,parm2,parm3,...) // fonksiyon çağırımı sırasında birden çok parametreye ihtiyaç duyar - - -// bu fonksiyon, bir diziyi parametre olarak alır ve dizideki sayıları toplar -function sumArrayValues(arr) { - let sum = 0; - for (let i = 0; i < arr.length; i++) { - sum = sum + arr[i]; - } - return sum; -} -const numbers = [1, 2, 3, 4, 5]; - //fonksiyon çağırımı -console.log(sumArrayValues(numbers)); - - - const areaOfCircle = (radius) => { - let area = Math.PI * radius * radius; - return area; - } -console.log(areaOfCircle(10)) - -``` - -### Sınırsız sayıda parametreyle çalışan fonksiyon - -Fonksiyonlarla çalışırken kaç tane parametre gerekebileceğini bilemeyebiliriz. Javascript'te bu durumda bize sınırsız sayıda parametre alan fonksiyon yazabilme imkanı tanır. Bu şekilde bir fonksiyon tanımlamanın iki yolu vardır. - -#### Klasik fonksiyonda sınırsız sayıda parametre - - A function declaration provides a function scoped arguments array like object. Any thing we passed as argument in the function can be accessed from arguments object inside the functions. Let us see an example - - Bu fonksiyonun tanımlanmasını fonksiyon scope'nda object temelli arguments anahtar kelimesi ile erişilir. Parametre olarak atanan her öğeye arguments üzerinden ulaşabiliriz. Bir örneğine bakmak gerekirse; - - ```js -// arguments nesnesine erişelim -​ -function sumAllNums() { - console.log(arguments) -} - -sumAllNums(1, 2, 3, 4) -// Arguments(4) [1, 2, 3, 4, callee: ƒ, Symbol(Symbol.iterator): ƒ] - -``` - -```js -// fonksiyon tanımı -​ -function sumAllNums() { - let sum = 0 - for (let i = 0; i < arguments.length; i++) { - sum += arguments[i] - } - return sum -} - -console.log(sumAllNums(1, 2, 3, 4)) // 10 -console.log(sumAllNums(10, 20, 13, 40, 10)) // 93 -console.log(sumAllNums(15, 20, 30, 25, 10, 33, 40)) // 173 -``` - -> Arrow function'da sınırsız sayıda parametre konusunu Arraw fonksiyonu gördükten sonra görebilirsiniz. - - -### Kendi kendine çağırılan fonksiyon - -JavaScript sözdiziminde birçok ilginç şey vardır, bunlardan biri kendi kendine çalışan (kendi kendini çağıran) fonksiyonların tanımıdır. Böyle bir fonksiyonu şu şekilde tanımlayabiliriz: - -```js -(function(n) { - console.log(n * n) -})(2) // 4, but instead of just printing if we want to return and store the data, we do as shown below - -let squaredNum = (function(n) { - return n * n -})(10) - -console.log(squaredNum) -``` - -Yukarıdaki fonksiyon, tanımlandıktan hemen sonra çağrılır. Kendi kendini çağıran işlevlerin yararı, global ad alanını karıştırmadan (herhangi bir global bildirmeden) kodu bir kez yürütmemize olanak vermeleridir. - -### Arrow Function - -Klasik fonksiyona alternatif olarak kullanılan arrow function sözdiziminde ufak bir farklılık vardır. `function` anahtar kelimesi yerine `=>` işareti kullanılır. - -Sırasıyla aynı fonksiyonun klasik ve arrow function halini yazalım - -```js -function square(n) { - return n * n -} - -console.log(square(2)) // 4 - -const square = n => { - return n * n -} - -console.log(square(2)) // -> 4 - -// kod bloğumuzda sadece bir satır kod varsa bu fonksiyon şu şekilde yazılabilir. -const square = n => n * n // -> 4 -``` - -```js -const changeToUpperCase = arr => { - const newArr = [] - for (const element of arr) { - newArr.push(element.toUpperCase()) - } - return newArr -} - -const countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland'] -console.log(changeToUpperCase(countries)) - -// ["FINLAND", "SWEDEN", "NORWAY", "DENMARK", "ICELAND"] -``` - -```js -const printFullName = (firstName, lastName) => { - return `${firstName} ${lastName}` -} - -console.log(printFullName('Asabeneh', 'Yetayeh')) -``` - -Yukarıdaki fonksiyon yalnızca geri dönüş ifadesine sahiptir, bu nedenle bunu aşağıdaki şekilde açıkça iade edebiliriz. -```js -const printFullName = (firstName, lastName) => `${firstName} ${lastName}` - -console.log(printFullName('Asabeneh', 'Yetayeh')) -``` - -#### Arrow function'da sınırsız sayıda parametre - - Arrow function, klasik fonksiyon gibi arguments nesnesine sahip değildir. Arrow function'da sınırsız sayıda parametre kullanmak istersek spread operatör (...) ve hemen ardından parametre adı kullanılır. Fonksiyonda bağımsız değişken olarak geçtiğimiz her şeye arrow functionda dizi olarak erişilebilir. Bir örnek görelim - - ```js -// arguments nesnesine erişmemize bir örnek -​ -const sumAllNums = (...args) => { - // console.log(arguments), arguments nesnesi bulunamadı - // bunun yerine spread operator (...) ve parametre adı kullanalım - console.log(args) -} - -sumAllNums(1, 2, 3, 4) -// [1, 2, 3, 4] - -``` - -```js -// function declaration -​ -const sumAllNums = (...args) => { - let sum = 0 - for (const element of args) { - sum += element - } - return sum -} - -console.log(sumAllNums(1, 2, 3, 4)) // 10 -console.log(sumAllNums(10, 20, 13, 40, 10)) // 93 -console.log(sumAllNums(15, 20, 30, 25, 10, 33, 40)) // 173 -``` - -### Default parametre ile fonksiyon kullanımı - - -Bazen parametrelere default değerler geçmek isteyebiliriz. Bu durumda fonksiyon çağırımı sırasında söz konusu parametreyi vermek zorunda olmadan kullanabiliriz. Eğer bu parametreyi vermezsek fonksiyon işlevinin parametrenin default değerini kullanarak tamamlayacaktır. - -```js -// syntax - söz dizimi -// fonksiyon tanımı -function functionName(param = value) { - //codes -} - -// fonksiyon çağırımı -functionName() -functionName(arg) -``` - -**Example:** - -```js -function greetings(name = 'Peter') { - let message = `${name}, welcome to 30 Days Of JavaScript!` - return message -} - -console.log(greetings()) -console.log(greetings('Asabeneh')) -``` - -```js -function generateFullName(firstName = 'Asabeneh', lastName = 'Yetayeh') { - let space = ' ' - let fullName = firstName + space + lastName - return fullName -} - -console.log(generateFullName()) -console.log(generateFullName('David', 'Smith')) -``` - -```js -function calculateAge(birthYear, currentYear = 2019) { - let age = currentYear - birthYear - return age -} - -console.log('Age: ', calculateAge(1819)) -``` - -```js -function weightOfObject(mass, gravity = 9.81) { - let weight = mass * gravity + ' N' // değer önce dize olarak değiştirilmelidir - return weight -} - -console.log('Weight of an object in Newton: ', weightOfObject(100)) // 9.81 Dünya yüzeyinde yerçekimi -console.log('Weight of an object in Newton: ', weightOfObject(100, 1.62)) // Ay yüzeyinde yerçekimi -``` - -Yukarıdaki fonksiyonları bir de arrow function kullanarak tanımlayalım - -```js -// syntax - söz dizimi -// fonksiyonu tanımlama -const functionName = (param = value) => { - //codes -} - -// fonksiyonu çağırma -functionName() -functionName(arg) -``` - -**Example:** - -```js -const greetings = (name = 'Peter') => { - let message = name + ', welcome to 30 Days Of JavaScript!' - return message -} - -console.log(greetings()) -console.log(greetings('Asabeneh')) -``` - -```js -const generateFullName = (firstName = 'Asabeneh', lastName = 'Yetayeh') => { - let space = ' ' - let fullName = firstName + space + lastName - return fullName -} - -console.log(generateFullName()) -console.log(generateFullName('David', 'Smith')) -``` - -```js - -const calculateAge = (birthYear, currentYear = 2019) => currentYear - birthYear -console.log('Age: ', calculateAge(1819)) -``` - -```js -const weightOfObject = (mass, gravity = 9.81) => mass * gravity + ' N' - -console.log('Weight of an object in Newton: ', weightOfObject(100)) // 9.81 Dünya yüzeyinde yerçekimi -console.log('Weight of an object in Newton: ', weightOfObject(100, 1.62)) // Ay yüzeyinde yerçekimi -``` - -### Function declaration versus Arrow function - -Diğer bölümde ele alınacaktır. - -🌕 Serinin 7. gününü de başarıyla tamamladın. Durmak yok yola devam - - - -## 💻 Exercises - -### Exercises: Level 1 - -1. Declare a function _fullName_ and it print out your full name. -2. Declare a function _fullName_ and now it takes firstName, lastName as a parameter and it returns your full - name. -3. Declare a function _addNumbers_ and it takes two two parameters and it returns sum. -4. An area of a rectangle is calculated as follows: _area = length x width_. Write a function which calculates _areaOfRectangle_. -5. A perimeter of a rectangle is calculated as follows: _perimeter= 2x(length + width)_. Write a function which calculates _perimeterOfRectangle_. -6. A volume of a rectangular prism is calculated as follows: _volume = length x width x height_. Write a function which calculates _volumeOfRectPrism_. -7. Area of a circle is calculated as follows: _area = π x r x r_. Write a function which calculates _areaOfCircle_ -8. Circumference of a circle is calculated as follows: _circumference = 2πr_. Write a function which calculates _circumOfCircle_ -9. Density of a substance is calculated as follows:_density= mass/volume_. Write a function which calculates _density_. -10. Speed is calculated by dividing the total distance covered by a moving object divided by the total amount of time taken. Write a function which calculates a speed of a moving object, _speed_. -11. Weight of a substance is calculated as follows: _weight = mass x gravity_. Write a function which calculates _weight_. -12. Temperature in oC can be converted to oF using this formula: _oF = (oC x 9/5) + 32_. Write a function which convert oC to oF _convertCelsiusToFahrenheit_. -13. Body mass index(BMI) is calculated as follows: _bmi = weight in Kg / (height x height) in m2_. Write a function which calculates _bmi_. BMI is used to broadly define different weight groups in adults 20 years old or older.Check if a person is _underweight, normal, overweight_ or _obese_ based the information given below. - - - The same groups apply to both men and women. - - _Underweight_: BMI is less than 18.5 - - _Normal weight_: BMI is 18.5 to 24.9 - - _Overweight_: BMI is 25 to 29.9 - - _Obese_: BMI is 30 or more - -14. Write a function called _checkSeason_, it takes a month parameter and returns the season:Autumn, Winter, Spring or Summer. -15. Math.max returns its largest argument. Write a function findMax that takes three arguments and returns their maximum with out using Math.max method. - - ```js - console.log(findMax(0, 10, 5)) - 10 - console.log(findMax(0, -10, -2)) - 0 - ``` - -### Exercises: Level 2 - -1. Linear equation is calculated as follows: _ax + by + c = 0_. Write a function which calculates value of a linear equation, _solveLinEquation_. -1. Quadratic equation is calculated as follows: _ax2 + bx + c = 0_. Write a function which calculates value or values of a quadratic equation, _solveQuadEquation_. - - ```js - console.log(solveQuadratic()) // {0} - console.log(solveQuadratic(1, 4, 4)) // {-2} - console.log(solveQuadratic(1, -1, -2)) // {2, -1} - console.log(solveQuadratic(1, 7, 12)) // {-3, -4} - console.log(solveQuadratic(1, 0, -4)) //{2, -2} - console.log(solveQuadratic(1, -1, 0)) //{1, 0} - ``` - -1. Declare a function name _printArray_. It takes array as a parameter and it prints out each value of the array. -1. Write a function name _showDateTime_ which shows time in this format: 08/01/2020 04:08 using the Date object. - - ```sh - showDateTime() - 08/01/2020 04:08 - ``` - -1. Declare a function name _swapValues_. This function swaps value of x to y. - - ```js - swapValues(3, 4) // x => 4, y=>3 - swapValues(4, 5) // x = 5, y = 4 - ``` - -1. Declare a function name _reverseArray_. It takes array as a parameter and it returns the reverse of the array (don't use method). - - ```js - console.log(reverseArray([1, 2, 3, 4, 5])) - //[5, 4, 3, 2, 1] - console.log(reverseArray(['A', 'B', 'C'])) - //['C', 'B', 'A'] - ``` - -1. Declare a function name _capitalizeArray_. It takes array as a parameter and it returns the - capitalizedarray. -1. Declare a function name _addItem_. It takes an item parameter and it returns an array after adding the item -1. Declare a function name _removeItem_. It takes an index parameter and it returns an array after removing an item -1. Declare a function name _sumOfNumbers_. It takes a number parameter and it adds all the numbers in that range. -1. Declare a function name _sumOfOdds_. It takes a number parameter and it adds all the odd numbers in that - range. -1. Declare a function name _sumOfEven_. It takes a number parameter and it adds all the even numbers in that - range. -1. Declare a function name evensAndOdds . It takes a positive integer as parameter and it counts number of evens and odds in the number. - - ```sh - evensAndOdds(100); - The number of odds are 50. - The number of evens are 51. - ``` - -1. Write a function which takes any number of arguments and return the sum of the arguments - - ```js - sum(1, 2, 3) // -> 6 - sum(1, 2, 3, 4) // -> 10 - ``` - -1. Writ a function which generates a _randomUserIp_. -1. Write a function which generates a _randomMacAddress_ -1. Declare a function name _randomHexaNumberGenerator_. When this function is called it generates a random hexadecimal number. The function return the hexadecimal number. - - ```sh - console.log(randomHexaNumberGenerator()); - '#ee33df' - ``` - -1. Declare a function name _userIdGenerator_. When this function is called it generates seven character id. The function return the id. - - ```sh - console.log(userIdGenerator()); - 41XTDbE - ``` - -### Exercises: Level 3 - -1. Modify the _userIdGenerator_ function. Declare a function name _userIdGeneratedByUser_. It doesn’t take any parameter but it takes two inputs using prompt(). One of the input is the number of characters and the second input is the number of ids which are supposed to be generated. - - ```sh - userIdGeneratedByUser() - 'kcsy2 - SMFYb - bWmeq - ZXOYh - 2Rgxf - ' - userIdGeneratedByUser() - '1GCSgPLMaBAVQZ26 - YD7eFwNQKNs7qXaT - ycArC5yrRupyG00S - UbGxOFI7UXSWAyKN - dIV0SSUTgAdKwStr - ' - ``` - -1. Write a function name _rgbColorGenerator_ and it generates rgb colors. - - ```sh - rgbColorGenerator() - rgb(125,244,255) - ``` - -1. Write a function **_arrayOfHexaColors_** which return any number of hexadecimal colors in an array. -1. Write a function **_arrayOfRgbColors_** which return any number of RGB colors in an array. -1. Write a function **_convertHexaToRgb_** which converts hexa color to rgb and it returns an rgb color. -1. Write a function **_convertRgbToHexa_** which converts rgb to hexa color and it returns an hexa color. -1. Write a function **_generateColors_** which can generate any number of hexa or rgb colors. - - ```js - console.log(generateColors('hexa', 3)) // ['#a3e12f', '#03ed55', '#eb3d2b'] - console.log(generateColors('hexa', 1)) // '#b334ef' - console.log(generateColors('rgb', 3)) // ['rgb(5, 55, 175)', 'rgb(50, 105, 100)', 'rgb(15, 26, 80)'] - console.log(generateColors('rgb', 1)) // 'rgb(33,79, 176)' - ``` - -1. Call your function _shuffleArray_, it takes an array as a parameter and it returns a shuffled array -1. Call your function _factorial_, it takes a whole number as a parameter and it return a factorial of the number -1. Call your function _isEmpty_, it takes a parameter and it checks if it is empty or not -1. Call your function _sum_, it takes any number of arguments and it returns the sum. -1. Write a function called _sumOfArrayItems_, it takes an array parameter and return the sum of all the items. Check if all the array items are number types. If not give return reasonable feedback. -1. Write a function called _average_, it takes an array parameter and returns the average of the items. Check if all the array items are number types. If not give return reasonable feedback. -1. Write a function called _modifyArray_ takes array as parameter and modifies the fifth item of the array and return the array. If the array length is less than five it return 'item not found'. - - ```js - console.log(modifyArray(['Avocado', 'Tomato', 'Potato','Mango', 'Lemon','Carrot']); - ``` - - ```sh - ['Avocado', 'Tomato', 'Potato','Mango', 'LEMON', 'Carrot'] - ``` - - ```js - console.log(modifyArray(['Google', 'Facebook','Apple', 'Amazon','Microsoft', 'IBM']); - ``` - - ```sh - ['Google', 'Facebook','Apple', 'Amazon','MICROSOFT', 'IBM'] - ``` - - ```js - console.log(modifyArray(['Google', 'Facebook','Apple', 'Amazon']); - ``` - - ```sh - 'Not Found' - ``` - -1. Write a function called _isPrime_, which checks if a number is prime number. -1. Write a functions which checks if all items are unique in the array. -1. Write a function which checks if all the items of the array are the same data type. -1. JavaScript variable name does not support special characters or symbols except \$ or \_. Write a function **isValidVariable** which check if a variable is valid or invalid variable. -1. Write a function which returns array of seven random numbers in a range of 0-9. All the numbers must be unique. - - ```js - sevenRandomNumbers() - [(1, 4, 5, 7, 9, 8, 0)] - ``` - -1. Write a function called reverseCountries, it takes countries array and first it copy the array and returns the reverse of the original array - -🎉 CONGRATULATIONS ! 🎉 - -[<< Day 6](../06_Day_Loops/06_day_loops.md) | [Day 8 >>](../08_Day_Objects/08_day_objects.md) diff --git a/Turkish/07_Day_Functions/07_day_starter/data/countries.js b/Turkish/07_Day_Functions/07_day_starter/data/countries.js deleted file mode 100644 index d0c4ec4..0000000 --- a/Turkish/07_Day_Functions/07_day_starter/data/countries.js +++ /dev/null @@ -1,195 +0,0 @@ -const countries = [ - 'Afghanistan', - 'Albania', - 'Algeria', - 'Andorra', - 'Angola', - 'Antigua and Barbuda', - 'Argentina', - 'Armenia', - 'Australia', - 'Austria', - 'Azerbaijan', - 'Bahamas', - 'Bahrain', - 'Bangladesh', - 'Barbados', - 'Belarus', - 'Belgium', - 'Belize', - 'Benin', - 'Bhutan', - 'Bolivia', - 'Bosnia and Herzegovina', - 'Botswana', - 'Brazil', - 'Brunei', - 'Bulgaria', - 'Burkina Faso', - 'Burundi', - 'Cambodia', - 'Cameroon', - 'Canada', - 'Cape Verde', - 'Central African Republic', - 'Chad', - 'Chile', - 'China', - 'Colombi', - 'Comoros', - 'Congo (Brazzaville)', - 'Congo', - 'Costa Rica', - "Cote d'Ivoire", - 'Croatia', - 'Cuba', - 'Cyprus', - 'Czech Republic', - 'Denmark', - 'Djibouti', - 'Dominica', - 'Dominican Republic', - 'East Timor (Timor Timur)', - 'Ecuador', - 'Egypt', - 'El Salvador', - 'Equatorial Guinea', - 'Eritrea', - 'Estonia', - 'Ethiopia', - 'Fiji', - 'Finland', - 'France', - 'Gabon', - 'Gambia, The', - 'Georgia', - 'Germany', - 'Ghana', - 'Greece', - 'Grenada', - 'Guatemala', - 'Guinea', - 'Guinea-Bissau', - 'Guyana', - 'Haiti', - 'Honduras', - 'Hungary', - 'Iceland', - 'India', - 'Indonesia', - 'Iran', - 'Iraq', - 'Ireland', - 'Israel', - 'Italy', - 'Jamaica', - 'Japan', - 'Jordan', - 'Kazakhstan', - 'Kenya', - 'Kiribati', - 'Korea, North', - 'Korea, South', - 'Kuwait', - 'Kyrgyzstan', - 'Laos', - 'Latvia', - 'Lebanon', - 'Lesotho', - 'Liberia', - 'Libya', - 'Liechtenstein', - 'Lithuania', - 'Luxembourg', - 'Macedonia', - 'Madagascar', - 'Malawi', - 'Malaysia', - 'Maldives', - 'Mali', - 'Malta', - 'Marshall Islands', - 'Mauritania', - 'Mauritius', - 'Mexico', - 'Micronesia', - 'Moldova', - 'Monaco', - 'Mongolia', - 'Morocco', - 'Mozambique', - 'Myanmar', - 'Namibia', - 'Nauru', - 'Nepal', - 'Netherlands', - 'New Zealand', - 'Nicaragua', - 'Niger', - 'Nigeria', - 'Norway', - 'Oman', - 'Pakistan', - 'Palau', - 'Panama', - 'Papua New Guinea', - 'Paraguay', - 'Peru', - 'Philippines', - 'Poland', - 'Portugal', - 'Qatar', - 'Romania', - 'Russia', - 'Rwanda', - 'Saint Kitts and Nevis', - 'Saint Lucia', - 'Saint Vincent', - 'Samoa', - 'San Marino', - 'Sao Tome and Principe', - 'Saudi Arabia', - 'Senegal', - 'Serbia and Montenegro', - 'Seychelles', - 'Sierra Leone', - 'Singapore', - 'Slovakia', - 'Slovenia', - 'Solomon Islands', - 'Somalia', - 'South Africa', - 'Spain', - 'Sri Lanka', - 'Sudan', - 'Suriname', - 'Swaziland', - 'Sweden', - 'Switzerland', - 'Syria', - 'Taiwan', - 'Tajikistan', - 'Tanzania', - 'Thailand', - 'Togo', - 'Tonga', - 'Trinidad and Tobago', - 'Tunisia', - 'Turkey', - 'Turkmenistan', - 'Tuvalu', - 'Uganda', - 'Ukraine', - 'United Arab Emirates', - 'United Kingdom', - 'United States', - 'Uruguay', - 'Uzbekistan', - 'Vanuatu', - 'Vatican City', - 'Venezuela', - 'Vietnam', - 'Yemen', - 'Zambia', - 'Zimbabwe' -] diff --git a/Turkish/07_Day_Functions/07_day_starter/index.html b/Turkish/07_Day_Functions/07_day_starter/index.html deleted file mode 100644 index 8a97e13..0000000 --- a/Turkish/07_Day_Functions/07_day_starter/index.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - 30DaysOfJavaScript:07 Day - - - -

30DaysOfJavaScript:07 Day

-

Functions

- - - - - - - \ No newline at end of file diff --git a/Turkish/07_Day_Functions/07_day_starter/scripts/main.js b/Turkish/07_Day_Functions/07_day_starter/scripts/main.js deleted file mode 100644 index 421fb87..0000000 --- a/Turkish/07_Day_Functions/07_day_starter/scripts/main.js +++ /dev/null @@ -1,2 +0,0 @@ -console.log(countries) -alert('Open the console and check if the countries has been loaded') \ No newline at end of file diff --git a/Turkish/08_Day_Objects/08_day_objects.md b/Turkish/08_Day_Objects/08_day_objects.md deleted file mode 100644 index ea0605a..0000000 --- a/Turkish/08_Day_Objects/08_day_objects.md +++ /dev/null @@ -1,598 +0,0 @@ -
-

30 Günde Javascript: Objects - Nesneler

- - - - - Twitter Follow - - - Author: - Asabeneh Yetayeh
-Çevirmen: - Hasan Hüseyin Alav
- Temmuz 2022 -
-
- -[<< 7. Gün](../07_Day_Functions/07_day_functions.md) | [9. Gün >>](../09_Day_Higher_order_functions/09_day_higher_order_functions.md) - -![Thirty Days Of JavaScript](/images/banners/day_1_8.png) - -- [📔 8. Gün](#-day-8) - - [Scope - Kapsam Alanları](#scope---kapsam-alanları) - - [Window Global Object](#window-global-object) - - [Global Scope](#global-scope) - - [Local Scope](#local-scope) - - [📔 Object - Nesne](#📔-object---nesne) - - [Boş Nesne Oluşturmak](#boş-nesne-oluşturmak) - - [Değerlerle Birlikte Bir Nesne Oluşturmak](#değerle-birlikte-nesne-oluşturmak) - - [Nesneden Değerleri Alabilmek](#nesneden-değerleri-alabilmek) - - [Object - Nesne Methodu Oluşturma](#object-methodları-oluşturma) - - [Object İçin Yeni Bir key Oluşturma](#object-için-yeni-bir-anahtar-değer-key-oluşturma) - - [Object Methodları](#object-methodları) - - [Object.keys() Metodu](#objectkeys-methodu) - - [Object.values() Methodu](#objectvalues-methodu) - - [Object.entries() Methodu](#objectentries-methodus) - - [hasOwnProperty() Methodu](#hasownproperty-methodu) - - [💻 Exercises](#-exercises) - - [Exercises: Level 1](#exercises-level-1) - - [Exercises: Level 2](#exercises-level-2) - - [Exercises: Level 3](#exercises-level-3) - -# 📔 8. Gün - -## Scope - Kapsam Alanları - -Bu konu değişken tanımlamanın temel kısmını oluşturur. Farklı veri türlerini depolamak için değişken tanımlarız. Bir değişkeni tanımlamak için `var`, `let` veya `const` anahtar sözcüklerini kullanırız. Bir değişken farklı kapsam alanlarında tanımlanabilir. Bu bölümde, `var` veya `let` kullandığımızda kapsam değişkenlerinin kodumuzu nasıl etkilediğini göreceğiz. - -Değişken scope'ları şu şekilde olabilir. - -- Global -- Local - -> `var`, `let` veya `const` olmadan tanımlanan her değişken global scope olarak geçerlidir. - -Scope.js adında bir dosyanızın olduğunu düşünelim. - -### Window Global Object - -Geçerli dosya içerisinde global scope da diyebiliriz bu duruma - -Console.log() metodunu kullanmadan tarayıcınızı açın ve kontrol edin; tarayıcıya a veya b yazarsanız a ve b değerlerini görebilirsiniz. Bu durum a ve b değişkenlerinin zaten hali hazırda mevcut olduğu anlamına gelir. - -```js -//scope.js dosyası içerisi - -a = 'JavaScript' // bir değişkeni let veya const anahtar kelimeleri olamadan tanımlamako değişkeni global hale getirir ve geçerli dosya içerisinde her yerden erişilebilir. - -b = 10 // bu gloabl scope olarak tanımlanmıştır ve dosya içerisinde her yerden erişilebilir. -function letsLearnScope() { - console.log(a, b) - if (true) { - console.log(a, b) - } -} -console.log(a, b) // erişilebilir -``` - -### Global scope - -Aynı dosyanın her yerinde global olarak tanımlanan bir değişkene erişilebilir. Global olma durumu iki şekilde olabilir Dosyanın direkt kendisinde global olabilir veya bazı kod bloklarına göre global olabilir. - -```js -//scope.js -let a = 'JavaScript' // bu dosyanın herhangi bir yerinde erişilebilecek global bir kapsamdır -let b = 10 // bu da dosyanın herhangi bir yerinde erişilebilecek global bir kapsamdır -function letsLearnScope() { - console.log(a, b) // JavaScript 10, erişilebilir - if (true) { - let a = 'Python' - let b = 100 - console.log(a, b) // Python 100 - } - console.log(a, b) -} -letsLearnScope() -console.log(a, b) // JavaScript 10, erişilebilir -``` - -### Local scope - -Yerel olarak tanımlanan bir değişkene yalnızca belirli kod bloğunda erişilebilir. - -- Block Scope -- Function Scope - -```js -//scope.js dosyasının içerisi - -let a = 'JavaScript' // bu dosyanın herhangi bir yerinde erişilebilecek global bir kapsamdır. -let b = 10 // bu dosyanın herhangi bir yerinde erişilebilecek global bir kapsamdır. - -// Function scope -function letsLearnScope() { - console.log(a, b) // JavaScript 10, erişilebilir - let value = false -// block scope - if (true) { - let a = 'Python' - let b = 20 - let c = 30 - let d = 40 - value = !value - console.log(a, b, c, value) // Python 20 30 true - } - //c değişkenine erişemiyoruz çünkü c değişkeni sadec if bloğunda geçerli bir değişkendir - console.log(a, b, c, value) // JavaScript 10 undefined true -} -letsLearnScope() -console.log(a, b) // JavaScript 10, erişilebilir -``` - -Artık scope'lar hakkında bir şeyler öğrendik. `var` anahtar kelimesi ile tanımlanan bir değişken fonksiyon scope'u içerisinde geçerlidir. Ancak `let` veya `const` anahtar kelimeleri ile tanımlanan değişkenler block scope'unda geçerlidir. (fonksiyon, if veya diğer dönggü blokları). Block kapsamını biraz daha netleştirmek gerekirse Javascript ve diğer çoğu yazılım dili için süslü parantezler arası demek olur. `{ }` - - -```js -//scope.js -function letsLearnScope() { - var gravity = 9.81 - console.log(gravity) - -} -// console.log(gravity), Uncaught ReferenceError: gravity is not defined -// yukarıdaki çıktı konsol ekranında alacağımız hatanın çıktısıdır. - -if (true){ - var gravity = 9.81 - console.log(gravity) // 9.81 -} -console.log(gravity) // 9.81 - -for(var i = 0; i < 3; i++){ - console.log(i) // 0, 1, 2 -} -console.log(i) // 3 - -``` - - - -```js -//scope.js -function letsLearnScope() { - // you can use let or const, but gravity is constant I prefer to use const - const gravity = 9.81 - console.log(gravity) - -} -// console.log(gravity), Uncaught ReferenceError: gravity is not defined - -if (true){ - const gravity = 9.81 - console.log(gravity) // 9.81 -} -// console.log(gravity), Uncaught ReferenceError: gravity is not defined - -for(let i = 0; i < 3; i++){ - console.log(i) // 0, 1, 2 -} -// console.log(i), Uncaught ReferenceError: i is not defined - -``` - -`let` ve `const` anahtar kelimeleri ile tanımlanan değişkenlerin kapsam alanlarının aynı olduğunu ifade ettik. Peki aralarındaki fark ne? Basitçe açıklamak gerekirse `const` ile tanımlanan bir değişkenin değerini daha sonraki satırlarda değiştiremeyiz ancak `let` ile tanımlanan değişkenin değerini değiştirebiliriz. Ben `let` ve `const` kullanarak temiz kod yazmanızı ve hata ayıklamanın zor olmasını önlemek için `let` ve `const` 'ı kullanmanızı tavsiye ederim. Temel kural olarak, herhangi bir sabit değer için `let` ve dizi, nesne, ok fonksiyonu ve işlev ifadesi için `const` özelliğini kullanabilirsiniz. - - -## 📔 Object - Nesne - - -Her şey bir nesne olabilir ve nesnelerin özellikleri ve özelliklerinin değerleri vardır, bu nedenle bir nesne bir anahtar değer çiftidir. -Bir nesneyi tam anlamıyla oluşturmak için iki köşeli parantez kullanırız. - -### Boş nesne oluşturmak - -Boş bir nesne - -```js -const person = {} -``` - -### Değerle birlikte nesne oluşturmak - - -Şimdi oluşturacağımız person nesnesinin firstName, lastName, age, country, city ve skills gibi bazı özellikleri olacak şekilde oluşturalım. - -``` -const person = { - firstName: 'Asabeneh', - lastName: 'Yetayeh', - age: 250, - country: 'Finland', - city: 'Helsinki', - skills: [ - 'HTML', - 'CSS', - 'JavaScript', - 'React', - 'Node', - 'MongoDB', - 'Python', - 'D3.js' - ], - isMarried: true -} -console.log(person) -``` - -### Nesneden değerleri alabilmek - -Nesnenin değerlerine iki yöntem kullanarak erişebiliriz: - -- `.` operatörünü kullanarak erişebiliriz -- köşeli parantez kullanarak erişebiliriz - -```js -const person = { - firstName: 'Asabeneh', - lastName: 'Yetayeh', - age: 250, - country: 'Finland', - city: 'Helsinki', - skills: [ - 'HTML', - 'CSS', - 'JavaScript', - 'React', - 'Node', - 'MongoDB', - 'Python', - 'D3.js' - ], - getFullName: function() { - return `${this.firstName}${this.lastName}` - }, - 'phone number': '+3584545454545' -} - -// "." operatörü kullanarak -console.log(person.firstName) -console.log(person.lastName) -console.log(person.age) -console.log(person.location) // undefined - -// kçşeli parantez kullanarak -console.log(person['firstName']) -console.log(person['lastName']) -console.log(person['age']) -console.log(person['age']) -console.log(person['location']) // undefined - -// örneğin, telefon numarasına erişmek için yalnızca köşeli parantez yöntemini kullanırız -console.log(person['phone number']) -``` - -### Object methodları oluşturma - -Şimdi, kişi nesnesinin getFullName özellikleri vardır. getFullName, kişi nesnesinin içindeki işlevdir ve biz ona nesne yöntemi diyoruz. _this_ anahtar sözcüğü, nesnenin kendisine atıfta bulunur. Nesnenin farklı özelliklerinin değerlerine erişmek için _this_ kelimesini kullanabiliriz. Bir arrow funtionu nesne yöntemi olarak kullanamayız çünkü bu sözcüğü nesnenin kendisi yerine bir arrow funtionun içindeki pencereyi ifade eder. Örnek olarak: - -```js -const person = { - firstName: 'Asabeneh', - lastName: 'Yetayeh', - age: 250, - country: 'Finland', - city: 'Helsinki', - skills: [ - 'HTML', - 'CSS', - 'JavaScript', - 'React', - 'Node', - 'MongoDB', - 'Python', - 'D3.js' - ], - getFullName: function() { - return `${this.firstName} ${this.lastName}` - } -} - -console.log(person.getFullName()) -// Asabeneh Yetayeh -``` - -### Object için yeni bir anahtar değer (key) oluşturma - -Nesne, eşlenebilen bir veri yapısıdır ve oluşturulduktan sonra nesnenin içeriğini değiştirebiliriz. - -nesne de yeni key'ler oluşturabilme - -```js -const person = { - firstName: 'Asabeneh', - lastName: 'Yetayeh', - age: 250, - country: 'Finland', - city: 'Helsinki', - skills: [ - 'HTML', - 'CSS', - 'JavaScript', - 'React', - 'Node', - 'MongoDB', - 'Python', - 'D3.js' - ], - getFullName: function() { - return `${this.firstName} ${this.lastName}` - } -} -person.nationality = 'Ethiopian' -person.country = 'Finland' -person.title = 'teacher' -person.skills.push('Meteor') -person.skills.push('SasS') -person.isMarried = true - -person.getPersonInfo = function() { - let skillsWithoutLastSkill = this.skills - .splice(0, this.skills.length - 1) - .join(', ') - let lastSkill = this.skills.splice(this.skills.length - 1)[0] - - let skills = `${skillsWithoutLastSkill}, and ${lastSkill}` - let fullName = this.getFullName() - let statement = `${fullName} is a ${this.title}.\nHe lives in ${this.country}.\nHe teaches ${skills}.` - return statement -} -console.log(person) -console.log(person.getPersonInfo()) -``` - -```sh -Asabeneh Yetayeh is a teacher. -He lives in Finland. -He teaches HTML, CSS, JavaScript, React, Node, MongoDB, Python, D3.js, Meteor, and SasS. -``` - -### Object methodları - -Bir nesneyi manipüle etmek için farklı yöntemler vardır. Mevcut yöntemlerden bazılarını görelim. - -_Object.assign_:Nesneyi orijinal nesneyi değiştirmeden kopyalamak için kullanılır - -```js -const person = { - firstName: 'Asabeneh', - age: 250, - country: 'Finland', - city:'Helsinki', - skills: ['HTML', 'CSS', 'JS'], - title: 'teacher', - address: { - street: 'Heitamienkatu 16', - pobox: 2002, - city: 'Helsinki' - }, - getPersonInfo: function() { - return `I am ${this.firstName} and I live in ${this.city}, ${this.country}. I am ${this.age}.` - } -} - -//Object methods: Object.assign, Object.keys, Object.values, Object.entries -//hasOwnProperty - -const copyPerson = Object.assign({}, person) -console.log(copyPerson) -``` - -#### Object.keys() methodu - -_Object.keys_: Bir nesnenin anahtarlarını veya özelliklerini dizi olarak almak için kullanılır - -```js -const keys = Object.keys(copyPerson) -console.log(keys) //['firstName', 'age', 'country','city', 'skills','title', 'address', 'getPersonInfo'] -const address = Object.keys(copyPerson.address) -console.log(address) //['street', 'pobox', 'city'] -``` - -#### Object.values() methodu - -_Object.values_: Nesnenin key'lerine karşılık gelen değerleri dizi içerisinde almak için kullanılır - -```js -const values = Object.values(copyPerson) -console.log(values) -``` - -#### Object.entries() methodu - -_Object.entries_: Bir dizideki key ve value değerlerini almak için kullanılır - -```js -const entries = Object.entries(copyPerson) -console.log(entries) -``` - -#### hasOwnProperty() methodu - -_hasOwnProperty_: Bir nesnede belirli bir anahtar veya özelliğin bulunup bulunmadığını kontrol etmek için kullanılır - -```js -console.log(copyPerson.hasOwnProperty('name')) -console.log(copyPerson.hasOwnProperty('score')) -``` - -🌕 Tebrikler 8. günü de başarıyla tamamladın. 9. günde görüşmek üzere - -## 💻 Exercises - -### Exercises: Level 1 - -1. Create an empty object called dog -1. Print the the dog object on the console -1. Add name, legs, color, age and bark properties for the dog object. The bark property is a method which return _woof woof_ -1. Get name, legs, color, age and bark value from the dog object -1. Set new properties the dog object: breed, getDogInfo - -### Exercises: Level 2 - -1. Find the person who has many skills in the users object. -1. Count logged in users, count users having greater than equal to 50 points from the following object. - - ````js - const users = { - Alex: { - email: 'alex@alex.com', - skills: ['HTML', 'CSS', 'JavaScript'], - age: 20, - isLoggedIn: false, - points: 30 - }, - Asab: { - email: 'asab@asab.com', - skills: ['HTML', 'CSS', 'JavaScript', 'Redux', 'MongoDB', 'Express', 'React', 'Node'], - age: 25, - isLoggedIn: false, - points: 50 - }, - Brook: { - email: 'daniel@daniel.com', - skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'], - age: 30, - isLoggedIn: true, - points: 50 - }, - Daniel: { - email: 'daniel@alex.com', - skills: ['HTML', 'CSS', 'JavaScript', 'Python'], - age: 20, - isLoggedIn: false, - points: 40 - }, - John: { - email: 'john@john.com', - skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node.js'], - age: 20, - isLoggedIn: true, - points: 50 - }, - Thomas: { - email: 'thomas@thomas.com', - skills: ['HTML', 'CSS', 'JavaScript', 'React'], - age: 20, - isLoggedIn: false, - points: 40 - }, - Paul: { - email: 'paul@paul.com', - skills: ['HTML', 'CSS', 'JavaScript', 'MongoDB', 'Express', 'React', 'Node'], - age: 20, - isLoggedIn: false, - points: 40 - } - }``` - -1. Find people who are MERN stack developer from the users object -1. Set your name in the users object without modifying the original users object -1. Get all keys or properties of users object -1. Get all the values of users object -1. Use the countries object to print a country name, capital, populations and languages. - -### Exercises: Level 3 - -1. Create an object literal called _personAccount_. It has _firstName, lastName, incomes, expenses_ properties and it has _totalIncome, totalExpense, accountInfo,addIncome, addExpense_ and _accountBalance_ methods. Incomes is a set of incomes and its description and expenses is a set of incomes and its description. -2. **** Questions:2, 3 and 4 are based on the following two arrays:users and products () - - ```js - const users = [ - { - _id: 'ab12ex', - username: 'Alex', - email: 'alex@alex.com', - password: '123123', - createdAt:'08/01/2020 9:00 AM', - isLoggedIn: false - }, - { - _id: 'fg12cy', - username: 'Asab', - email: 'asab@asab.com', - password: '123456', - createdAt:'08/01/2020 9:30 AM', - isLoggedIn: true - }, - { - _id: 'zwf8md', - username: 'Brook', - email: 'brook@brook.com', - password: '123111', - createdAt:'08/01/2020 9:45 AM', - isLoggedIn: true - }, - { - _id: 'eefamr', - username: 'Martha', - email: 'martha@martha.com', - password: '123222', - createdAt:'08/01/2020 9:50 AM', - isLoggedIn: false - }, - { - _id: 'ghderc', - username: 'Thomas', - email: 'thomas@thomas.com', - password: '123333', - createdAt:'08/01/2020 10:00 AM', - isLoggedIn: false - } - ]; - - const products = [ - { - _id: 'eedfcf', - name: 'mobile phone', - description: 'Huawei Honor', - price: 200, - ratings: [ - { userId: 'fg12cy', rate: 5 }, - { userId: 'zwf8md', rate: 4.5 } - ], - likes: [] - }, - { - _id: 'aegfal', - name: 'Laptop', - description: 'MacPro: System Darwin', - price: 2500, - ratings: [], - likes: ['fg12cy'] - }, - { - _id: 'hedfcg', - name: 'TV', - description: 'Smart TV:Procaster', - price: 400, - ratings: [{ userId: 'fg12cy', rate: 5 }], - likes: ['fg12cy'] - } - ] - ``` - - Imagine you are getting the above users collection from a MongoDB database. - a. Create a function called signUp which allows user to add to the collection. If user exists, inform the user that he has already an account. - b. Create a function called signIn which allows user to sign in to the application - -3. The products array has three elements and each of them has six properties. - a. Create a function called rateProduct which rates the product - b. Create a function called averageRating which calculate the average rating of a product - -4. Create a function called likeProduct. This function will helps to like to the product if it is not liked and remove like if it was liked. - - -🎉 CONGRATULATIONS ! 🎉 - -[<< Day 7](../07_Day_Functions/07_day_functions.md) | [Day 9 >>](../09_Day_Higher_order_functions/09_day_higher_order_functions.md) diff --git a/Turkish/08_Day_Objects/08_day_starter/data/countries_data.js b/Turkish/08_Day_Objects/08_day_starter/data/countries_data.js deleted file mode 100644 index 073cbd6..0000000 --- a/Turkish/08_Day_Objects/08_day_starter/data/countries_data.js +++ /dev/null @@ -1,2013 +0,0 @@ -const countries = [ - { - name: 'Afghanistan', - capital: 'Kabul', - languages: ['Pashto', 'Uzbek', 'Turkmen'], - population: 27657145, - flag: 'https://restcountries.eu/data/afg.svg', - currency: 'Afghan afghani' - }, - { - name: 'Åland Islands', - capital: 'Mariehamn', - languages: ['Swedish'], - population: 28875, - flag: 'https://restcountries.eu/data/ala.svg', - currency: 'Euro' - }, - { - name: 'Albania', - capital: 'Tirana', - languages: ['Albanian'], - population: 2886026, - flag: 'https://restcountries.eu/data/alb.svg', - currency: 'Albanian lek' - }, - { - name: 'Algeria', - capital: 'Algiers', - languages: ['Arabic'], - population: 40400000, - flag: 'https://restcountries.eu/data/dza.svg', - currency: 'Algerian dinar' - }, - { - name: 'American Samoa', - capital: 'Pago Pago', - languages: ['English', 'Samoan'], - population: 57100, - flag: 'https://restcountries.eu/data/asm.svg', - currency: 'United State Dollar' - }, - { - name: 'Andorra', - capital: 'Andorra la Vella', - languages: ['Catalan'], - population: 78014, - flag: 'https://restcountries.eu/data/and.svg', - currency: 'Euro' - }, - { - name: 'Angola', - capital: 'Luanda', - languages: ['Portuguese'], - population: 25868000, - flag: 'https://restcountries.eu/data/ago.svg', - currency: 'Angolan kwanza' - }, - { - name: 'Anguilla', - capital: 'The Valley', - languages: ['English'], - population: 13452, - flag: 'https://restcountries.eu/data/aia.svg', - currency: 'East Caribbean dollar' - }, - { - name: 'Antarctica', - capital: '', - languages: ['English', 'Russian'], - population: 1000, - flag: 'https://restcountries.eu/data/ata.svg', - currency: 'Australian dollar' - }, - { - name: 'Antigua and Barbuda', - capital: "Saint John's", - languages: ['English'], - population: 86295, - flag: 'https://restcountries.eu/data/atg.svg', - currency: 'East Caribbean dollar' - }, - { - name: 'Argentina', - capital: 'Buenos Aires', - languages: ['Spanish', 'Guaraní'], - population: 43590400, - flag: 'https://restcountries.eu/data/arg.svg', - currency: 'Argentine peso' - }, - { - name: 'Armenia', - capital: 'Yerevan', - languages: ['Armenian', 'Russian'], - population: 2994400, - flag: 'https://restcountries.eu/data/arm.svg', - currency: 'Armenian dram' - }, - { - name: 'Aruba', - capital: 'Oranjestad', - languages: ['Dutch', '(Eastern) Punjabi'], - population: 107394, - flag: 'https://restcountries.eu/data/abw.svg', - currency: 'Aruban florin' - }, - { - name: 'Australia', - capital: 'Canberra', - languages: ['English'], - population: 24117360, - flag: 'https://restcountries.eu/data/aus.svg', - currency: 'Australian dollar' - }, - { - name: 'Austria', - capital: 'Vienna', - languages: ['German'], - population: 8725931, - flag: 'https://restcountries.eu/data/aut.svg', - currency: 'Euro' - }, - { - name: 'Azerbaijan', - capital: 'Baku', - languages: ['Azerbaijani'], - population: 9730500, - flag: 'https://restcountries.eu/data/aze.svg', - currency: 'Azerbaijani manat' - }, - { - name: 'Bahamas', - capital: 'Nassau', - languages: ['English'], - population: 378040, - flag: 'https://restcountries.eu/data/bhs.svg', - currency: 'Bahamian dollar' - }, - { - name: 'Bahrain', - capital: 'Manama', - languages: ['Arabic'], - population: 1404900, - flag: 'https://restcountries.eu/data/bhr.svg', - currency: 'Bahraini dinar' - }, - { - name: 'Bangladesh', - capital: 'Dhaka', - languages: ['Bengali'], - population: 161006790, - flag: 'https://restcountries.eu/data/bgd.svg', - currency: 'Bangladeshi taka' - }, - { - name: 'Barbados', - capital: 'Bridgetown', - languages: ['English'], - population: 285000, - flag: 'https://restcountries.eu/data/brb.svg', - currency: 'Barbadian dollar' - }, - { - name: 'Belarus', - capital: 'Minsk', - languages: ['Belarusian', 'Russian'], - population: 9498700, - flag: 'https://restcountries.eu/data/blr.svg', - currency: 'New Belarusian ruble' - }, - { - name: 'Belgium', - capital: 'Brussels', - languages: ['Dutch', 'French', 'German'], - population: 11319511, - flag: 'https://restcountries.eu/data/bel.svg', - currency: 'Euro' - }, - { - name: 'Belize', - capital: 'Belmopan', - languages: ['English', 'Spanish'], - population: 370300, - flag: 'https://restcountries.eu/data/blz.svg', - currency: 'Belize dollar' - }, - { - name: 'Benin', - capital: 'Porto-Novo', - languages: ['French'], - population: 10653654, - flag: 'https://restcountries.eu/data/ben.svg', - currency: 'West African CFA franc' - }, - { - name: 'Bermuda', - capital: 'Hamilton', - languages: ['English'], - population: 61954, - flag: 'https://restcountries.eu/data/bmu.svg', - currency: 'Bermudian dollar' - }, - { - name: 'Bhutan', - capital: 'Thimphu', - languages: ['Dzongkha'], - population: 775620, - flag: 'https://restcountries.eu/data/btn.svg', - currency: 'Bhutanese ngultrum' - }, - { - name: 'Bolivia (Plurinational State of)', - capital: 'Sucre', - languages: ['Spanish', 'Aymara', 'Quechua'], - population: 10985059, - flag: 'https://restcountries.eu/data/bol.svg', - currency: 'Bolivian boliviano' - }, - { - name: 'Bonaire, Sint Eustatius and Saba', - capital: 'Kralendijk', - languages: ['Dutch'], - population: 17408, - flag: 'https://restcountries.eu/data/bes.svg', - currency: 'United States dollar' - }, - { - name: 'Bosnia and Herzegovina', - capital: 'Sarajevo', - languages: ['Bosnian', 'Croatian', 'Serbian'], - population: 3531159, - flag: 'https://restcountries.eu/data/bih.svg', - currency: 'Bosnia and Herzegovina convertible mark' - }, - { - name: 'Botswana', - capital: 'Gaborone', - languages: ['English', 'Tswana'], - population: 2141206, - flag: 'https://restcountries.eu/data/bwa.svg', - currency: 'Botswana pula' - }, - { - name: 'Bouvet Island', - capital: '', - languages: ['Norwegian', 'Norwegian Bokmål', 'Norwegian Nynorsk'], - population: 0, - flag: 'https://restcountries.eu/data/bvt.svg', - currency: 'Norwegian krone' - }, - { - name: 'Brazil', - capital: 'Brasília', - languages: ['Portuguese'], - population: 206135893, - flag: 'https://restcountries.eu/data/bra.svg', - currency: 'Brazilian real' - }, - { - name: 'British Indian Ocean Territory', - capital: 'Diego Garcia', - languages: ['English'], - population: 3000, - flag: 'https://restcountries.eu/data/iot.svg', - currency: 'United States dollar' - }, - { - name: 'United States Minor Outlying Islands', - capital: '', - languages: ['English'], - population: 300, - flag: 'https://restcountries.eu/data/umi.svg', - currency: 'United States Dollar' - }, - { - name: 'Virgin Islands (British)', - capital: 'Road Town', - languages: ['English'], - population: 28514, - flag: 'https://restcountries.eu/data/vgb.svg', - currency: '[D]' - }, - { - name: 'Virgin Islands (U.S.)', - capital: 'Charlotte Amalie', - languages: ['English'], - population: 114743, - flag: 'https://restcountries.eu/data/vir.svg', - currency: 'United States dollar' - }, - { - name: 'Brunei Darussalam', - capital: 'Bandar Seri Begawan', - languages: ['Malay'], - population: 411900, - flag: 'https://restcountries.eu/data/brn.svg', - currency: 'Brunei dollar' - }, - { - name: 'Bulgaria', - capital: 'Sofia', - languages: ['Bulgarian'], - population: 7153784, - flag: 'https://restcountries.eu/data/bgr.svg', - currency: 'Bulgarian lev' - }, - { - name: 'Burkina Faso', - capital: 'Ouagadougou', - languages: ['French', 'Fula'], - population: 19034397, - flag: 'https://restcountries.eu/data/bfa.svg', - currency: 'West African CFA franc' - }, - { - name: 'Burundi', - capital: 'Bujumbura', - languages: ['French', 'Kirundi'], - population: 10114505, - flag: 'https://restcountries.eu/data/bdi.svg', - currency: 'Burundian franc' - }, - { - name: 'Cambodia', - capital: 'Phnom Penh', - languages: ['Khmer'], - population: 15626444, - flag: 'https://restcountries.eu/data/khm.svg', - currency: 'Cambodian riel' - }, - { - name: 'Cameroon', - capital: 'Yaoundé', - languages: ['English', 'French'], - population: 22709892, - flag: 'https://restcountries.eu/data/cmr.svg', - currency: 'Central African CFA franc' - }, - { - name: 'Canada', - capital: 'Ottawa', - languages: ['English', 'French'], - population: 36155487, - flag: 'https://restcountries.eu/data/can.svg', - currency: 'Canadian dollar' - }, - { - name: 'Cabo Verde', - capital: 'Praia', - languages: ['Portuguese'], - population: 531239, - flag: 'https://restcountries.eu/data/cpv.svg', - currency: 'Cape Verdean escudo' - }, - { - name: 'Cayman Islands', - capital: 'George Town', - languages: ['English'], - population: 58238, - flag: 'https://restcountries.eu/data/cym.svg', - currency: 'Cayman Islands dollar' - }, - { - name: 'Central African Republic', - capital: 'Bangui', - languages: ['French', 'Sango'], - population: 4998000, - flag: 'https://restcountries.eu/data/caf.svg', - currency: 'Central African CFA franc' - }, - { - name: 'Chad', - capital: "N'Djamena", - languages: ['French', 'Arabic'], - population: 14497000, - flag: 'https://restcountries.eu/data/tcd.svg', - currency: 'Central African CFA franc' - }, - { - name: 'Chile', - capital: 'Santiago', - languages: ['Spanish'], - population: 18191900, - flag: 'https://restcountries.eu/data/chl.svg', - currency: 'Chilean peso' - }, - { - name: 'China', - capital: 'Beijing', - languages: ['Chinese'], - population: 1377422166, - flag: 'https://restcountries.eu/data/chn.svg', - currency: 'Chinese yuan' - }, - { - name: 'Christmas Island', - capital: 'Flying Fish Cove', - languages: ['English'], - population: 2072, - flag: 'https://restcountries.eu/data/cxr.svg', - currency: 'Australian dollar' - }, - { - name: 'Cocos (Keeling) Islands', - capital: 'West Island', - languages: ['English'], - population: 550, - flag: 'https://restcountries.eu/data/cck.svg', - currency: 'Australian dollar' - }, - { - name: 'Colombia', - capital: 'Bogotá', - languages: ['Spanish'], - population: 48759958, - flag: 'https://restcountries.eu/data/col.svg', - currency: 'Colombian peso' - }, - { - name: 'Comoros', - capital: 'Moroni', - languages: ['Arabic', 'French'], - population: 806153, - flag: 'https://restcountries.eu/data/com.svg', - currency: 'Comorian franc' - }, - { - name: 'Congo', - capital: 'Brazzaville', - languages: ['French', 'Lingala'], - population: 4741000, - flag: 'https://restcountries.eu/data/cog.svg', - currency: 'Central African CFA franc' - }, - { - name: 'Congo (Democratic Republic of the)', - capital: 'Kinshasa', - languages: ['French', 'Lingala', 'Kongo', 'Swahili', 'Luba-Katanga'], - population: 85026000, - flag: 'https://restcountries.eu/data/cod.svg', - currency: 'Congolese franc' - }, - { - name: 'Cook Islands', - capital: 'Avarua', - languages: ['English'], - population: 18100, - flag: 'https://restcountries.eu/data/cok.svg', - currency: 'New Zealand dollar' - }, - { - name: 'Costa Rica', - capital: 'San José', - languages: ['Spanish'], - population: 4890379, - flag: 'https://restcountries.eu/data/cri.svg', - currency: 'Costa Rican colón' - }, - { - name: 'Croatia', - capital: 'Zagreb', - languages: ['Croatian'], - population: 4190669, - flag: 'https://restcountries.eu/data/hrv.svg', - currency: 'Croatian kuna' - }, - { - name: 'Cuba', - capital: 'Havana', - languages: ['Spanish'], - population: 11239004, - flag: 'https://restcountries.eu/data/cub.svg', - currency: 'Cuban convertible peso' - }, - { - name: 'Curaçao', - capital: 'Willemstad', - languages: ['Dutch', '(Eastern) Punjabi', 'English'], - population: 154843, - flag: 'https://restcountries.eu/data/cuw.svg', - currency: 'Netherlands Antillean guilder' - }, - { - name: 'Cyprus', - capital: 'Nicosia', - languages: ['Greek (modern)', 'Turkish', 'Armenian'], - population: 847000, - flag: 'https://restcountries.eu/data/cyp.svg', - currency: 'Euro' - }, - { - name: 'Czech Republic', - capital: 'Prague', - languages: ['Czech', 'Slovak'], - population: 10558524, - flag: 'https://restcountries.eu/data/cze.svg', - currency: 'Czech koruna' - }, - { - name: 'Denmark', - capital: 'Copenhagen', - languages: ['Danish'], - population: 5717014, - flag: 'https://restcountries.eu/data/dnk.svg', - currency: 'Danish krone' - }, - { - name: 'Djibouti', - capital: 'Djibouti', - languages: ['French', 'Arabic'], - population: 900000, - flag: 'https://restcountries.eu/data/dji.svg', - currency: 'Djiboutian franc' - }, - { - name: 'Dominica', - capital: 'Roseau', - languages: ['English'], - population: 71293, - flag: 'https://restcountries.eu/data/dma.svg', - currency: 'East Caribbean dollar' - }, - { - name: 'Dominican Republic', - capital: 'Santo Domingo', - languages: ['Spanish'], - population: 10075045, - flag: 'https://restcountries.eu/data/dom.svg', - currency: 'Dominican peso' - }, - { - name: 'Ecuador', - capital: 'Quito', - languages: ['Spanish'], - population: 16545799, - flag: 'https://restcountries.eu/data/ecu.svg', - currency: 'United States dollar' - }, - { - name: 'Egypt', - capital: 'Cairo', - languages: ['Arabic'], - population: 91290000, - flag: 'https://restcountries.eu/data/egy.svg', - currency: 'Egyptian pound' - }, - { - name: 'El Salvador', - capital: 'San Salvador', - languages: ['Spanish'], - population: 6520675, - flag: 'https://restcountries.eu/data/slv.svg', - currency: 'United States dollar' - }, - { - name: 'Equatorial Guinea', - capital: 'Malabo', - languages: ['Spanish', 'French'], - population: 1222442, - flag: 'https://restcountries.eu/data/gnq.svg', - currency: 'Central African CFA franc' - }, - { - name: 'Eritrea', - capital: 'Asmara', - languages: ['Tigrinya', 'Arabic', 'English'], - population: 5352000, - flag: 'https://restcountries.eu/data/eri.svg', - currency: 'Eritrean nakfa' - }, - { - name: 'Estonia', - capital: 'Tallinn', - languages: ['Estonian'], - population: 1315944, - flag: 'https://restcountries.eu/data/est.svg', - currency: 'Euro' - }, - { - name: 'Ethiopia', - capital: 'Addis Ababa', - languages: ['Amharic'], - population: 92206005, - flag: 'https://restcountries.eu/data/eth.svg', - currency: 'Ethiopian birr' - }, - { - name: 'Falkland Islands (Malvinas)', - capital: 'Stanley', - languages: ['English'], - population: 2563, - flag: 'https://restcountries.eu/data/flk.svg', - currency: 'Falkland Islands pound' - }, - { - name: 'Faroe Islands', - capital: 'Tórshavn', - languages: ['Faroese'], - population: 49376, - flag: 'https://restcountries.eu/data/fro.svg', - currency: 'Danish krone' - }, - { - name: 'Fiji', - capital: 'Suva', - languages: ['English', 'Fijian', 'Hindi', 'Urdu'], - population: 867000, - flag: 'https://restcountries.eu/data/fji.svg', - currency: 'Fijian dollar' - }, - { - name: 'Finland', - capital: 'Helsinki', - languages: ['Finnish', 'Swedish'], - population: 5491817, - flag: 'https://restcountries.eu/data/fin.svg', - currency: 'Euro' - }, - { - name: 'France', - capital: 'Paris', - languages: ['French'], - population: 66710000, - flag: 'https://restcountries.eu/data/fra.svg', - currency: 'Euro' - }, - { - name: 'French Guiana', - capital: 'Cayenne', - languages: ['French'], - population: 254541, - flag: 'https://restcountries.eu/data/guf.svg', - currency: 'Euro' - }, - { - name: 'French Polynesia', - capital: 'Papeetē', - languages: ['French'], - population: 271800, - flag: 'https://restcountries.eu/data/pyf.svg', - currency: 'CFP franc' - }, - { - name: 'French Southern Territories', - capital: 'Port-aux-Français', - languages: ['French'], - population: 140, - flag: 'https://restcountries.eu/data/atf.svg', - currency: 'Euro' - }, - { - name: 'Gabon', - capital: 'Libreville', - languages: ['French'], - population: 1802278, - flag: 'https://restcountries.eu/data/gab.svg', - currency: 'Central African CFA franc' - }, - { - name: 'Gambia', - capital: 'Banjul', - languages: ['English'], - population: 1882450, - flag: 'https://restcountries.eu/data/gmb.svg', - currency: 'Gambian dalasi' - }, - { - name: 'Georgia', - capital: 'Tbilisi', - languages: ['Georgian'], - population: 3720400, - flag: 'https://restcountries.eu/data/geo.svg', - currency: 'Georgian Lari' - }, - { - name: 'Germany', - capital: 'Berlin', - languages: ['German'], - population: 81770900, - flag: 'https://restcountries.eu/data/deu.svg', - currency: 'Euro' - }, - { - name: 'Ghana', - capital: 'Accra', - languages: ['English'], - population: 27670174, - flag: 'https://restcountries.eu/data/gha.svg', - currency: 'Ghanaian cedi' - }, - { - name: 'Gibraltar', - capital: 'Gibraltar', - languages: ['English'], - population: 33140, - flag: 'https://restcountries.eu/data/gib.svg', - currency: 'Gibraltar pound' - }, - { - name: 'Greece', - capital: 'Athens', - languages: ['Greek (modern)'], - population: 10858018, - flag: 'https://restcountries.eu/data/grc.svg', - currency: 'Euro' - }, - { - name: 'Greenland', - capital: 'Nuuk', - languages: ['Kalaallisut'], - population: 55847, - flag: 'https://restcountries.eu/data/grl.svg', - currency: 'Danish krone' - }, - { - name: 'Grenada', - capital: "St. George's", - languages: ['English'], - population: 103328, - flag: 'https://restcountries.eu/data/grd.svg', - currency: 'East Caribbean dollar' - }, - { - name: 'Guadeloupe', - capital: 'Basse-Terre', - languages: ['French'], - population: 400132, - flag: 'https://restcountries.eu/data/glp.svg', - currency: 'Euro' - }, - { - name: 'Guam', - capital: 'Hagåtña', - languages: ['English', 'Chamorro', 'Spanish'], - population: 184200, - flag: 'https://restcountries.eu/data/gum.svg', - currency: 'United States dollar' - }, - { - name: 'Guatemala', - capital: 'Guatemala City', - languages: ['Spanish'], - population: 16176133, - flag: 'https://restcountries.eu/data/gtm.svg', - currency: 'Guatemalan quetzal' - }, - { - name: 'Guernsey', - capital: 'St. Peter Port', - languages: ['English', 'French'], - population: 62999, - flag: 'https://restcountries.eu/data/ggy.svg', - currency: 'British pound' - }, - { - name: 'Guinea', - capital: 'Conakry', - languages: ['French', 'Fula'], - population: 12947000, - flag: 'https://restcountries.eu/data/gin.svg', - currency: 'Guinean franc' - }, - { - name: 'Guinea-Bissau', - capital: 'Bissau', - languages: ['Portuguese'], - population: 1547777, - flag: 'https://restcountries.eu/data/gnb.svg', - currency: 'West African CFA franc' - }, - { - name: 'Guyana', - capital: 'Georgetown', - languages: ['English'], - population: 746900, - flag: 'https://restcountries.eu/data/guy.svg', - currency: 'Guyanese dollar' - }, - { - name: 'Haiti', - capital: 'Port-au-Prince', - languages: ['French', 'Haitian'], - population: 11078033, - flag: 'https://restcountries.eu/data/hti.svg', - currency: 'Haitian gourde' - }, - { - name: 'Heard Island and McDonald Islands', - capital: '', - languages: ['English'], - population: 0, - flag: 'https://restcountries.eu/data/hmd.svg', - currency: 'Australian dollar' - }, - { - name: 'Holy See', - capital: 'Rome', - languages: ['Latin', 'Italian', 'French', 'German'], - population: 451, - flag: 'https://restcountries.eu/data/vat.svg', - currency: 'Euro' - }, - { - name: 'Honduras', - capital: 'Tegucigalpa', - languages: ['Spanish'], - population: 8576532, - flag: 'https://restcountries.eu/data/hnd.svg', - currency: 'Honduran lempira' - }, - { - name: 'Hong Kong', - capital: 'City of Victoria', - languages: ['English', 'Chinese'], - population: 7324300, - flag: 'https://restcountries.eu/data/hkg.svg', - currency: 'Hong Kong dollar' - }, - { - name: 'Hungary', - capital: 'Budapest', - languages: ['Hungarian'], - population: 9823000, - flag: 'https://restcountries.eu/data/hun.svg', - currency: 'Hungarian forint' - }, - { - name: 'Iceland', - capital: 'Reykjavík', - languages: ['Icelandic'], - population: 334300, - flag: 'https://restcountries.eu/data/isl.svg', - currency: 'Icelandic króna' - }, - { - name: 'India', - capital: 'New Delhi', - languages: ['Hindi', 'English'], - population: 1295210000, - flag: 'https://restcountries.eu/data/ind.svg', - currency: 'Indian rupee' - }, - { - name: 'Indonesia', - capital: 'Jakarta', - languages: ['Indonesian'], - population: 258705000, - flag: 'https://restcountries.eu/data/idn.svg', - currency: 'Indonesian rupiah' - }, - { - name: "Côte d'Ivoire", - capital: 'Yamoussoukro', - languages: ['French'], - population: 22671331, - flag: 'https://restcountries.eu/data/civ.svg', - currency: 'West African CFA franc' - }, - { - name: 'Iran (Islamic Republic of)', - capital: 'Tehran', - languages: ['Persian (Farsi)'], - population: 79369900, - flag: 'https://restcountries.eu/data/irn.svg', - currency: 'Iranian rial' - }, - { - name: 'Iraq', - capital: 'Baghdad', - languages: ['Arabic', 'Kurdish'], - population: 37883543, - flag: 'https://restcountries.eu/data/irq.svg', - currency: 'Iraqi dinar' - }, - { - name: 'Ireland', - capital: 'Dublin', - languages: ['Irish', 'English'], - population: 6378000, - flag: 'https://restcountries.eu/data/irl.svg', - currency: 'Euro' - }, - { - name: 'Isle of Man', - capital: 'Douglas', - languages: ['English', 'Manx'], - population: 84497, - flag: 'https://restcountries.eu/data/imn.svg', - currency: 'British pound' - }, - { - name: 'Israel', - capital: 'Jerusalem', - languages: ['Hebrew (modern)', 'Arabic'], - population: 8527400, - flag: 'https://restcountries.eu/data/isr.svg', - currency: 'Israeli new shekel' - }, - { - name: 'Italy', - capital: 'Rome', - languages: ['Italian'], - population: 60665551, - flag: 'https://restcountries.eu/data/ita.svg', - currency: 'Euro' - }, - { - name: 'Jamaica', - capital: 'Kingston', - languages: ['English'], - population: 2723246, - flag: 'https://restcountries.eu/data/jam.svg', - currency: 'Jamaican dollar' - }, - { - name: 'Japan', - capital: 'Tokyo', - languages: ['Japanese'], - population: 126960000, - flag: 'https://restcountries.eu/data/jpn.svg', - currency: 'Japanese yen' - }, - { - name: 'Jersey', - capital: 'Saint Helier', - languages: ['English', 'French'], - population: 100800, - flag: 'https://restcountries.eu/data/jey.svg', - currency: 'British pound' - }, - { - name: 'Jordan', - capital: 'Amman', - languages: ['Arabic'], - population: 9531712, - flag: 'https://restcountries.eu/data/jor.svg', - currency: 'Jordanian dinar' - }, - { - name: 'Kazakhstan', - capital: 'Astana', - languages: ['Kazakh', 'Russian'], - population: 17753200, - flag: 'https://restcountries.eu/data/kaz.svg', - currency: 'Kazakhstani tenge' - }, - { - name: 'Kenya', - capital: 'Nairobi', - languages: ['English', 'Swahili'], - population: 47251000, - flag: 'https://restcountries.eu/data/ken.svg', - currency: 'Kenyan shilling' - }, - { - name: 'Kiribati', - capital: 'South Tarawa', - languages: ['English'], - population: 113400, - flag: 'https://restcountries.eu/data/kir.svg', - currency: 'Australian dollar' - }, - { - name: 'Kuwait', - capital: 'Kuwait City', - languages: ['Arabic'], - population: 4183658, - flag: 'https://restcountries.eu/data/kwt.svg', - currency: 'Kuwaiti dinar' - }, - { - name: 'Kyrgyzstan', - capital: 'Bishkek', - languages: ['Kyrgyz', 'Russian'], - population: 6047800, - flag: 'https://restcountries.eu/data/kgz.svg', - currency: 'Kyrgyzstani som' - }, - { - name: "Lao People's Democratic Republic", - capital: 'Vientiane', - languages: ['Lao'], - population: 6492400, - flag: 'https://restcountries.eu/data/lao.svg', - currency: 'Lao kip' - }, - { - name: 'Latvia', - capital: 'Riga', - languages: ['Latvian'], - population: 1961600, - flag: 'https://restcountries.eu/data/lva.svg', - currency: 'Euro' - }, - { - name: 'Lebanon', - capital: 'Beirut', - languages: ['Arabic', 'French'], - population: 5988000, - flag: 'https://restcountries.eu/data/lbn.svg', - currency: 'Lebanese pound' - }, - { - name: 'Lesotho', - capital: 'Maseru', - languages: ['English', 'Southern Sotho'], - population: 1894194, - flag: 'https://restcountries.eu/data/lso.svg', - currency: 'Lesotho loti' - }, - { - name: 'Liberia', - capital: 'Monrovia', - languages: ['English'], - population: 4615000, - flag: 'https://restcountries.eu/data/lbr.svg', - currency: 'Liberian dollar' - }, - { - name: 'Libya', - capital: 'Tripoli', - languages: ['Arabic'], - population: 6385000, - flag: 'https://restcountries.eu/data/lby.svg', - currency: 'Libyan dinar' - }, - { - name: 'Liechtenstein', - capital: 'Vaduz', - languages: ['German'], - population: 37623, - flag: 'https://restcountries.eu/data/lie.svg', - currency: 'Swiss franc' - }, - { - name: 'Lithuania', - capital: 'Vilnius', - languages: ['Lithuanian'], - population: 2872294, - flag: 'https://restcountries.eu/data/ltu.svg', - currency: 'Euro' - }, - { - name: 'Luxembourg', - capital: 'Luxembourg', - languages: ['French', 'German', 'Luxembourgish'], - population: 576200, - flag: 'https://restcountries.eu/data/lux.svg', - currency: 'Euro' - }, - { - name: 'Macao', - capital: '', - languages: ['Chinese', 'Portuguese'], - population: 649100, - flag: 'https://restcountries.eu/data/mac.svg', - currency: 'Macanese pataca' - }, - { - name: 'Macedonia (the former Yugoslav Republic of)', - capital: 'Skopje', - languages: ['Macedonian'], - population: 2058539, - flag: 'https://restcountries.eu/data/mkd.svg', - currency: 'Macedonian denar' - }, - { - name: 'Madagascar', - capital: 'Antananarivo', - languages: ['French', 'Malagasy'], - population: 22434363, - flag: 'https://restcountries.eu/data/mdg.svg', - currency: 'Malagasy ariary' - }, - { - name: 'Malawi', - capital: 'Lilongwe', - languages: ['English', 'Chichewa'], - population: 16832910, - flag: 'https://restcountries.eu/data/mwi.svg', - currency: 'Malawian kwacha' - }, - { - name: 'Malaysia', - capital: 'Kuala Lumpur', - languages: ['Malaysian'], - population: 31405416, - flag: 'https://restcountries.eu/data/mys.svg', - currency: 'Malaysian ringgit' - }, - { - name: 'Maldives', - capital: 'Malé', - languages: ['Divehi'], - population: 344023, - flag: 'https://restcountries.eu/data/mdv.svg', - currency: 'Maldivian rufiyaa' - }, - { - name: 'Mali', - capital: 'Bamako', - languages: ['French'], - population: 18135000, - flag: 'https://restcountries.eu/data/mli.svg', - currency: 'West African CFA franc' - }, - { - name: 'Malta', - capital: 'Valletta', - languages: ['Maltese', 'English'], - population: 425384, - flag: 'https://restcountries.eu/data/mlt.svg', - currency: 'Euro' - }, - { - name: 'Marshall Islands', - capital: 'Majuro', - languages: ['English', 'Marshallese'], - population: 54880, - flag: 'https://restcountries.eu/data/mhl.svg', - currency: 'United States dollar' - }, - { - name: 'Martinique', - capital: 'Fort-de-France', - languages: ['French'], - population: 378243, - flag: 'https://restcountries.eu/data/mtq.svg', - currency: 'Euro' - }, - { - name: 'Mauritania', - capital: 'Nouakchott', - languages: ['Arabic'], - population: 3718678, - flag: 'https://restcountries.eu/data/mrt.svg', - currency: 'Mauritanian ouguiya' - }, - { - name: 'Mauritius', - capital: 'Port Louis', - languages: ['English'], - population: 1262879, - flag: 'https://restcountries.eu/data/mus.svg', - currency: 'Mauritian rupee' - }, - { - name: 'Mayotte', - capital: 'Mamoudzou', - languages: ['French'], - population: 226915, - flag: 'https://restcountries.eu/data/myt.svg', - currency: 'Euro' - }, - { - name: 'Mexico', - capital: 'Mexico City', - languages: ['Spanish'], - population: 122273473, - flag: 'https://restcountries.eu/data/mex.svg', - currency: 'Mexican peso' - }, - { - name: 'Micronesia (Federated States of)', - capital: 'Palikir', - languages: ['English'], - population: 102800, - flag: 'https://restcountries.eu/data/fsm.svg', - currency: '[D]' - }, - { - name: 'Moldova (Republic of)', - capital: 'Chișinău', - languages: ['Romanian'], - population: 3553100, - flag: 'https://restcountries.eu/data/mda.svg', - currency: 'Moldovan leu' - }, - { - name: 'Monaco', - capital: 'Monaco', - languages: ['French'], - population: 38400, - flag: 'https://restcountries.eu/data/mco.svg', - currency: 'Euro' - }, - { - name: 'Mongolia', - capital: 'Ulan Bator', - languages: ['Mongolian'], - population: 3093100, - flag: 'https://restcountries.eu/data/mng.svg', - currency: 'Mongolian tögrög' - }, - { - name: 'Montenegro', - capital: 'Podgorica', - languages: ['Serbian', 'Bosnian', 'Albanian', 'Croatian'], - population: 621810, - flag: 'https://restcountries.eu/data/mne.svg', - currency: 'Euro' - }, - { - name: 'Montserrat', - capital: 'Plymouth', - languages: ['English'], - population: 4922, - flag: 'https://restcountries.eu/data/msr.svg', - currency: 'East Caribbean dollar' - }, - { - name: 'Morocco', - capital: 'Rabat', - languages: ['Arabic'], - population: 33337529, - flag: 'https://restcountries.eu/data/mar.svg', - currency: 'Moroccan dirham' - }, - { - name: 'Mozambique', - capital: 'Maputo', - languages: ['Portuguese'], - population: 26423700, - flag: 'https://restcountries.eu/data/moz.svg', - currency: 'Mozambican metical' - }, - { - name: 'Myanmar', - capital: 'Naypyidaw', - languages: ['Burmese'], - population: 51419420, - flag: 'https://restcountries.eu/data/mmr.svg', - currency: 'Burmese kyat' - }, - { - name: 'Namibia', - capital: 'Windhoek', - languages: ['English', 'Afrikaans'], - population: 2324388, - flag: 'https://restcountries.eu/data/nam.svg', - currency: 'Namibian dollar' - }, - { - name: 'Nauru', - capital: 'Yaren', - languages: ['English', 'Nauruan'], - population: 10084, - flag: 'https://restcountries.eu/data/nru.svg', - currency: 'Australian dollar' - }, - { - name: 'Nepal', - capital: 'Kathmandu', - languages: ['Nepali'], - population: 28431500, - flag: 'https://restcountries.eu/data/npl.svg', - currency: 'Nepalese rupee' - }, - { - name: 'Netherlands', - capital: 'Amsterdam', - languages: ['Dutch'], - population: 17019800, - flag: 'https://restcountries.eu/data/nld.svg', - currency: 'Euro' - }, - { - name: 'New Caledonia', - capital: 'Nouméa', - languages: ['French'], - population: 268767, - flag: 'https://restcountries.eu/data/ncl.svg', - currency: 'CFP franc' - }, - { - name: 'New Zealand', - capital: 'Wellington', - languages: ['English', 'Māori'], - population: 4697854, - flag: 'https://restcountries.eu/data/nzl.svg', - currency: 'New Zealand dollar' - }, - { - name: 'Nicaragua', - capital: 'Managua', - languages: ['Spanish'], - population: 6262703, - flag: 'https://restcountries.eu/data/nic.svg', - currency: 'Nicaraguan córdoba' - }, - { - name: 'Niger', - capital: 'Niamey', - languages: ['French'], - population: 20715000, - flag: 'https://restcountries.eu/data/ner.svg', - currency: 'West African CFA franc' - }, - { - name: 'Nigeria', - capital: 'Abuja', - languages: ['English'], - population: 186988000, - flag: 'https://restcountries.eu/data/nga.svg', - currency: 'Nigerian naira' - }, - { - name: 'Niue', - capital: 'Alofi', - languages: ['English'], - population: 1470, - flag: 'https://restcountries.eu/data/niu.svg', - currency: 'New Zealand dollar' - }, - { - name: 'Norfolk Island', - capital: 'Kingston', - languages: ['English'], - population: 2302, - flag: 'https://restcountries.eu/data/nfk.svg', - currency: 'Australian dollar' - }, - { - name: "Korea (Democratic People's Republic of)", - capital: 'Pyongyang', - languages: ['Korean'], - population: 25281000, - flag: 'https://restcountries.eu/data/prk.svg', - currency: 'North Korean won' - }, - { - name: 'Northern Mariana Islands', - capital: 'Saipan', - languages: ['English', 'Chamorro'], - population: 56940, - flag: 'https://restcountries.eu/data/mnp.svg', - currency: 'United States dollar' - }, - { - name: 'Norway', - capital: 'Oslo', - languages: ['Norwegian', 'Norwegian Bokmål', 'Norwegian Nynorsk'], - population: 5223256, - flag: 'https://restcountries.eu/data/nor.svg', - currency: 'Norwegian krone' - }, - { - name: 'Oman', - capital: 'Muscat', - languages: ['Arabic'], - population: 4420133, - flag: 'https://restcountries.eu/data/omn.svg', - currency: 'Omani rial' - }, - { - name: 'Pakistan', - capital: 'Islamabad', - languages: ['English', 'Urdu'], - population: 194125062, - flag: 'https://restcountries.eu/data/pak.svg', - currency: 'Pakistani rupee' - }, - { - name: 'Palau', - capital: 'Ngerulmud', - languages: ['English'], - population: 17950, - flag: 'https://restcountries.eu/data/plw.svg', - currency: '[E]' - }, - { - name: 'Palestine, State of', - capital: 'Ramallah', - languages: ['Arabic'], - population: 4682467, - flag: 'https://restcountries.eu/data/pse.svg', - currency: 'Israeli new sheqel' - }, - { - name: 'Panama', - capital: 'Panama City', - languages: ['Spanish'], - population: 3814672, - flag: 'https://restcountries.eu/data/pan.svg', - currency: 'Panamanian balboa' - }, - { - name: 'Papua New Guinea', - capital: 'Port Moresby', - languages: ['English'], - population: 8083700, - flag: 'https://restcountries.eu/data/png.svg', - currency: 'Papua New Guinean kina' - }, - { - name: 'Paraguay', - capital: 'Asunción', - languages: ['Spanish', 'Guaraní'], - population: 6854536, - flag: 'https://restcountries.eu/data/pry.svg', - currency: 'Paraguayan guaraní' - }, - { - name: 'Peru', - capital: 'Lima', - languages: ['Spanish'], - population: 31488700, - flag: 'https://restcountries.eu/data/per.svg', - currency: 'Peruvian sol' - }, - { - name: 'Philippines', - capital: 'Manila', - languages: ['English'], - population: 103279800, - flag: 'https://restcountries.eu/data/phl.svg', - currency: 'Philippine peso' - }, - { - name: 'Pitcairn', - capital: 'Adamstown', - languages: ['English'], - population: 56, - flag: 'https://restcountries.eu/data/pcn.svg', - currency: 'New Zealand dollar' - }, - { - name: 'Poland', - capital: 'Warsaw', - languages: ['Polish'], - population: 38437239, - flag: 'https://restcountries.eu/data/pol.svg', - currency: 'Polish złoty' - }, - { - name: 'Portugal', - capital: 'Lisbon', - languages: ['Portuguese'], - population: 10374822, - flag: 'https://restcountries.eu/data/prt.svg', - currency: 'Euro' - }, - { - name: 'Puerto Rico', - capital: 'San Juan', - languages: ['Spanish', 'English'], - population: 3474182, - flag: 'https://restcountries.eu/data/pri.svg', - currency: 'United States dollar' - }, - { - name: 'Qatar', - capital: 'Doha', - languages: ['Arabic'], - population: 2587564, - flag: 'https://restcountries.eu/data/qat.svg', - currency: 'Qatari riyal' - }, - { - name: 'Republic of Kosovo', - capital: 'Pristina', - languages: ['Albanian', 'Serbian'], - population: 1733842, - flag: 'https://restcountries.eu/data/kos.svg', - currency: 'Euro' - }, - { - name: 'Réunion', - capital: 'Saint-Denis', - languages: ['French'], - population: 840974, - flag: 'https://restcountries.eu/data/reu.svg', - currency: 'Euro' - }, - { - name: 'Romania', - capital: 'Bucharest', - languages: ['Romanian'], - population: 19861408, - flag: 'https://restcountries.eu/data/rou.svg', - currency: 'Romanian leu' - }, - { - name: 'Russian Federation', - capital: 'Moscow', - languages: ['Russian'], - population: 146599183, - flag: 'https://restcountries.eu/data/rus.svg', - currency: 'Russian ruble' - }, - { - name: 'Rwanda', - capital: 'Kigali', - languages: ['Kinyarwanda', 'English', 'French'], - population: 11553188, - flag: 'https://restcountries.eu/data/rwa.svg', - currency: 'Rwandan franc' - }, - { - name: 'Saint Barthélemy', - capital: 'Gustavia', - languages: ['French'], - population: 9417, - flag: 'https://restcountries.eu/data/blm.svg', - currency: 'Euro' - }, - { - name: 'Saint Helena, Ascension and Tristan da Cunha', - capital: 'Jamestown', - languages: ['English'], - population: 4255, - flag: 'https://restcountries.eu/data/shn.svg', - currency: 'Saint Helena pound' - }, - { - name: 'Saint Kitts and Nevis', - capital: 'Basseterre', - languages: ['English'], - population: 46204, - flag: 'https://restcountries.eu/data/kna.svg', - currency: 'East Caribbean dollar' - }, - { - name: 'Saint Lucia', - capital: 'Castries', - languages: ['English'], - population: 186000, - flag: 'https://restcountries.eu/data/lca.svg', - currency: 'East Caribbean dollar' - }, - { - name: 'Saint Martin (French part)', - capital: 'Marigot', - languages: ['English', 'French', 'Dutch'], - population: 36979, - flag: 'https://restcountries.eu/data/maf.svg', - currency: 'Euro' - }, - { - name: 'Saint Pierre and Miquelon', - capital: 'Saint-Pierre', - languages: ['French'], - population: 6069, - flag: 'https://restcountries.eu/data/spm.svg', - currency: 'Euro' - }, - { - name: 'Saint Vincent and the Grenadines', - capital: 'Kingstown', - languages: ['English'], - population: 109991, - flag: 'https://restcountries.eu/data/vct.svg', - currency: 'East Caribbean dollar' - }, - { - name: 'Samoa', - capital: 'Apia', - languages: ['Samoan', 'English'], - population: 194899, - flag: 'https://restcountries.eu/data/wsm.svg', - currency: 'Samoan tālā' - }, - { - name: 'San Marino', - capital: 'City of San Marino', - languages: ['Italian'], - population: 33005, - flag: 'https://restcountries.eu/data/smr.svg', - currency: 'Euro' - }, - { - name: 'Sao Tome and Principe', - capital: 'São Tomé', - languages: ['Portuguese'], - population: 187356, - flag: 'https://restcountries.eu/data/stp.svg', - currency: 'São Tomé and Príncipe dobra' - }, - { - name: 'Saudi Arabia', - capital: 'Riyadh', - languages: ['Arabic'], - population: 32248200, - flag: 'https://restcountries.eu/data/sau.svg', - currency: 'Saudi riyal' - }, - { - name: 'Senegal', - capital: 'Dakar', - languages: ['French'], - population: 14799859, - flag: 'https://restcountries.eu/data/sen.svg', - currency: 'West African CFA franc' - }, - { - name: 'Serbia', - capital: 'Belgrade', - languages: ['Serbian'], - population: 7076372, - flag: 'https://restcountries.eu/data/srb.svg', - currency: 'Serbian dinar' - }, - { - name: 'Seychelles', - capital: 'Victoria', - languages: ['French', 'English'], - population: 91400, - flag: 'https://restcountries.eu/data/syc.svg', - currency: 'Seychellois rupee' - }, - { - name: 'Sierra Leone', - capital: 'Freetown', - languages: ['English'], - population: 7075641, - flag: 'https://restcountries.eu/data/sle.svg', - currency: 'Sierra Leonean leone' - }, - { - name: 'Singapore', - capital: 'Singapore', - languages: ['English', 'Malay', 'Tamil', 'Chinese'], - population: 5535000, - flag: 'https://restcountries.eu/data/sgp.svg', - currency: 'Brunei dollar' - }, - { - name: 'Sint Maarten (Dutch part)', - capital: 'Philipsburg', - languages: ['Dutch', 'English'], - population: 38247, - flag: 'https://restcountries.eu/data/sxm.svg', - currency: 'Netherlands Antillean guilder' - }, - { - name: 'Slovakia', - capital: 'Bratislava', - languages: ['Slovak'], - population: 5426252, - flag: 'https://restcountries.eu/data/svk.svg', - currency: 'Euro' - }, - { - name: 'Slovenia', - capital: 'Ljubljana', - languages: ['Slovene'], - population: 2064188, - flag: 'https://restcountries.eu/data/svn.svg', - currency: 'Euro' - }, - { - name: 'Solomon Islands', - capital: 'Honiara', - languages: ['English'], - population: 642000, - flag: 'https://restcountries.eu/data/slb.svg', - currency: 'Solomon Islands dollar' - }, - { - name: 'Somalia', - capital: 'Mogadishu', - languages: ['Somali', 'Arabic'], - population: 11079000, - flag: 'https://restcountries.eu/data/som.svg', - currency: 'Somali shilling' - }, - { - name: 'South Africa', - capital: 'Pretoria', - languages: [ - 'Afrikaans', - 'English', - 'Southern Ndebele', - 'Southern Sotho', - 'Swati', - 'Tswana', - 'Tsonga', - 'Venda', - 'Xhosa', - 'Zulu' - ], - population: 55653654, - flag: 'https://restcountries.eu/data/zaf.svg', - currency: 'South African rand' - }, - { - name: 'South Georgia and the South Sandwich Islands', - capital: 'King Edward Point', - languages: ['English'], - population: 30, - flag: 'https://restcountries.eu/data/sgs.svg', - currency: 'British pound' - }, - { - name: 'Korea (Republic of)', - capital: 'Seoul', - languages: ['Korean'], - population: 50801405, - flag: 'https://restcountries.eu/data/kor.svg', - currency: 'South Korean won' - }, - { - name: 'South Sudan', - capital: 'Juba', - languages: ['English'], - population: 12131000, - flag: 'https://restcountries.eu/data/ssd.svg', - currency: 'South Sudanese pound' - }, - { - name: 'Spain', - capital: 'Madrid', - languages: ['Spanish'], - population: 46438422, - flag: 'https://restcountries.eu/data/esp.svg', - currency: 'Euro' - }, - { - name: 'Sri Lanka', - capital: 'Colombo', - languages: ['Sinhalese', 'Tamil'], - population: 20966000, - flag: 'https://restcountries.eu/data/lka.svg', - currency: 'Sri Lankan rupee' - }, - { - name: 'Sudan', - capital: 'Khartoum', - languages: ['Arabic', 'English'], - population: 39598700, - flag: 'https://restcountries.eu/data/sdn.svg', - currency: 'Sudanese pound' - }, - { - name: 'Suriname', - capital: 'Paramaribo', - languages: ['Dutch'], - population: 541638, - flag: 'https://restcountries.eu/data/sur.svg', - currency: 'Surinamese dollar' - }, - { - name: 'Svalbard and Jan Mayen', - capital: 'Longyearbyen', - languages: ['Norwegian'], - population: 2562, - flag: 'https://restcountries.eu/data/sjm.svg', - currency: 'Norwegian krone' - }, - { - name: 'Swaziland', - capital: 'Lobamba', - languages: ['English', 'Swati'], - population: 1132657, - flag: 'https://restcountries.eu/data/swz.svg', - currency: 'Swazi lilangeni' - }, - { - name: 'Sweden', - capital: 'Stockholm', - languages: ['Swedish'], - population: 9894888, - flag: 'https://restcountries.eu/data/swe.svg', - currency: 'Swedish krona' - }, - { - name: 'Switzerland', - capital: 'Bern', - languages: ['German', 'French', 'Italian'], - population: 8341600, - flag: 'https://restcountries.eu/data/che.svg', - currency: 'Swiss franc' - }, - { - name: 'Syrian Arab Republic', - capital: 'Damascus', - languages: ['Arabic'], - population: 18564000, - flag: 'https://restcountries.eu/data/syr.svg', - currency: 'Syrian pound' - }, - { - name: 'Taiwan', - capital: 'Taipei', - languages: ['Chinese'], - population: 23503349, - flag: 'https://restcountries.eu/data/twn.svg', - currency: 'New Taiwan dollar' - }, - { - name: 'Tajikistan', - capital: 'Dushanbe', - languages: ['Tajik', 'Russian'], - population: 8593600, - flag: 'https://restcountries.eu/data/tjk.svg', - currency: 'Tajikistani somoni' - }, - { - name: 'Tanzania, United Republic of', - capital: 'Dodoma', - languages: ['Swahili', 'English'], - population: 55155000, - flag: 'https://restcountries.eu/data/tza.svg', - currency: 'Tanzanian shilling' - }, - { - name: 'Thailand', - capital: 'Bangkok', - languages: ['Thai'], - population: 65327652, - flag: 'https://restcountries.eu/data/tha.svg', - currency: 'Thai baht' - }, - { - name: 'Timor-Leste', - capital: 'Dili', - languages: ['Portuguese'], - population: 1167242, - flag: 'https://restcountries.eu/data/tls.svg', - currency: 'United States dollar' - }, - { - name: 'Togo', - capital: 'Lomé', - languages: ['French'], - population: 7143000, - flag: 'https://restcountries.eu/data/tgo.svg', - currency: 'West African CFA franc' - }, - { - name: 'Tokelau', - capital: 'Fakaofo', - languages: ['English'], - population: 1411, - flag: 'https://restcountries.eu/data/tkl.svg', - currency: 'New Zealand dollar' - }, - { - name: 'Tonga', - capital: "Nuku'alofa", - languages: ['English', 'Tonga (Tonga Islands)'], - population: 103252, - flag: 'https://restcountries.eu/data/ton.svg', - currency: 'Tongan paʻanga' - }, - { - name: 'Trinidad and Tobago', - capital: 'Port of Spain', - languages: ['English'], - population: 1349667, - flag: 'https://restcountries.eu/data/tto.svg', - currency: 'Trinidad and Tobago dollar' - }, - { - name: 'Tunisia', - capital: 'Tunis', - languages: ['Arabic'], - population: 11154400, - flag: 'https://restcountries.eu/data/tun.svg', - currency: 'Tunisian dinar' - }, - { - name: 'Turkey', - capital: 'Ankara', - languages: ['Turkish'], - population: 78741053, - flag: 'https://restcountries.eu/data/tur.svg', - currency: 'Turkish lira' - }, - { - name: 'Turkmenistan', - capital: 'Ashgabat', - languages: ['Turkmen', 'Russian'], - population: 4751120, - flag: 'https://restcountries.eu/data/tkm.svg', - currency: 'Turkmenistan manat' - }, - { - name: 'Turks and Caicos Islands', - capital: 'Cockburn Town', - languages: ['English'], - population: 31458, - flag: 'https://restcountries.eu/data/tca.svg', - currency: 'United States dollar' - }, - { - name: 'Tuvalu', - capital: 'Funafuti', - languages: ['English'], - population: 10640, - flag: 'https://restcountries.eu/data/tuv.svg', - currency: 'Australian dollar' - }, - { - name: 'Uganda', - capital: 'Kampala', - languages: ['English', 'Swahili'], - population: 33860700, - flag: 'https://restcountries.eu/data/uga.svg', - currency: 'Ugandan shilling' - }, - { - name: 'Ukraine', - capital: 'Kiev', - languages: ['Ukrainian'], - population: 42692393, - flag: 'https://restcountries.eu/data/ukr.svg', - currency: 'Ukrainian hryvnia' - }, - { - name: 'United Arab Emirates', - capital: 'Abu Dhabi', - languages: ['Arabic'], - population: 9856000, - flag: 'https://restcountries.eu/data/are.svg', - currency: 'United Arab Emirates dirham' - }, - { - name: 'United Kingdom of Great Britain and Northern Ireland', - capital: 'London', - languages: ['English'], - population: 65110000, - flag: 'https://restcountries.eu/data/gbr.svg', - currency: 'British pound' - }, - { - name: 'United States of America', - capital: 'Washington, D.C.', - languages: ['English'], - population: 323947000, - flag: 'https://restcountries.eu/data/usa.svg', - currency: 'United States dollar' - }, - { - name: 'Uruguay', - capital: 'Montevideo', - languages: ['Spanish'], - population: 3480222, - flag: 'https://restcountries.eu/data/ury.svg', - currency: 'Uruguayan peso' - }, - { - name: 'Uzbekistan', - capital: 'Tashkent', - languages: ['Uzbek', 'Russian'], - population: 31576400, - flag: 'https://restcountries.eu/data/uzb.svg', - currency: "Uzbekistani so'm" - }, - { - name: 'Vanuatu', - capital: 'Port Vila', - languages: ['Bislama', 'English', 'French'], - population: 277500, - flag: 'https://restcountries.eu/data/vut.svg', - currency: 'Vanuatu vatu' - }, - { - name: 'Venezuela (Bolivarian Republic of)', - capital: 'Caracas', - languages: ['Spanish'], - population: 31028700, - flag: 'https://restcountries.eu/data/ven.svg', - currency: 'Venezuelan bolívar' - }, - { - name: 'Viet Nam', - capital: 'Hanoi', - languages: ['Vietnamese'], - population: 92700000, - flag: 'https://restcountries.eu/data/vnm.svg', - currency: 'Vietnamese đồng' - }, - { - name: 'Wallis and Futuna', - capital: 'Mata-Utu', - languages: ['French'], - population: 11750, - flag: 'https://restcountries.eu/data/wlf.svg', - currency: 'CFP franc' - }, - { - name: 'Western Sahara', - capital: 'El Aaiún', - languages: ['Spanish'], - population: 510713, - flag: 'https://restcountries.eu/data/esh.svg', - currency: 'Moroccan dirham' - }, - { - name: 'Yemen', - capital: "Sana'a", - languages: ['Arabic'], - population: 27478000, - flag: 'https://restcountries.eu/data/yem.svg', - currency: 'Yemeni rial' - }, - { - name: 'Zambia', - capital: 'Lusaka', - languages: ['English'], - population: 15933883, - flag: 'https://restcountries.eu/data/zmb.svg', - currency: 'Zambian kwacha' - }, - { - name: 'Zimbabwe', - capital: 'Harare', - languages: ['English', 'Shona', 'Northern Ndebele'], - population: 14240168, - flag: 'https://restcountries.eu/data/zwe.svg', - currency: 'Botswana pula' - } -] diff --git a/Turkish/08_Day_Objects/08_day_starter/index.html b/Turkish/08_Day_Objects/08_day_starter/index.html deleted file mode 100644 index a86b373..0000000 --- a/Turkish/08_Day_Objects/08_day_starter/index.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - 30DaysOfJavaScript:08 Day - - - -

30DaysOfJavaScript:08 Day

-

Objects

- - - - - - - \ No newline at end of file diff --git a/Turkish/08_Day_Objects/08_day_starter/scripts/main.js b/Turkish/08_Day_Objects/08_day_starter/scripts/main.js deleted file mode 100644 index 421fb87..0000000 --- a/Turkish/08_Day_Objects/08_day_starter/scripts/main.js +++ /dev/null @@ -1,2 +0,0 @@ -console.log(countries) -alert('Open the console and check if the countries has been loaded') \ No newline at end of file diff --git a/Turkish/16_Day_JSON/16_day_json.md b/Turkish/16_Day_JSON/16_day_json.md deleted file mode 100644 index 11b6459..0000000 --- a/Turkish/16_Day_JSON/16_day_json.md +++ /dev/null @@ -1,598 +0,0 @@ -
-

30 Days Of JavaScript: JSON

- - - - - Twitter Follow - - -Author: -Asabeneh Yetayeh
- January, 2020 -
- -
- -[<< Gün 15](../15_Day_Classes/15_day_classes.md) | [Gün 17 >>](../17_Day_Web_storages/17_day_web_storages.md) - -![Thirty Days Of JavaScript](../../images/banners/day_1_16.png) - -- [Gün 16](#day-16) - - [JSON](#json) - - [JSON'u JavaScript Nesnesine Dönüştürme](#converting-json-to-javascript-object) - - [JSON.parse()](#jsonparse) - - [JSON.parse() ile bir reviver fonksiyonu kullanma](#using-a-reviver-function-with-jsonparse) - - [Nesneyi JSON'a Dönüştürme](#converting-object-to-json) - - [JSON.stringify ile Filtre Dizisi Kullanma](#using-a-filter-array-with-jsonstringify) - - [Egzersizler](#exercises) - - [Egzersiz Seviye 1](#exercises-level-1) - - [Egzersiz Seviye 2](#exercises-level-2) - - [Egzersiz Seviye 3](#exercises-level-3) - -# Gün 16 - -## JSON - -JSON, javascript nesne kavramı anlamına gelir. JSON syntaxı(sözdizim), JavaScript nesne gösterimi sözdiziminden türetilmiştir, ancak JSON biçimi yalnızca metin veya dizedir. JSON, depolama ve taşıma için hafif bir veri formatıdır. JSON, çoğunlukla bir sunucudan bir istemciye veri gönderildiğinde kullanılır. JSON, XML'e göre kullanımı daha kolay bir alternatiftir. - -**Örnek:** - -```js -{ -"users":[ - { - "firstName":"Asabeneh", - "lastName":"Yetayeh", - "age":250, - "email":"asab@asb.com" - }, - { - "firstName":"Alex", - "lastName":"James", - "age":25, - "email":"alex@alex.com" - }, - { - "firstName":"Lidiya", - "lastName":"Tekle", - "age":28, - "email":"lidiya@lidiya.com" - } -] -} -``` - -Yukarıdaki JSON örneği, normal bir nesneden çok farklı değildir. O zaman, fark nedir? Aradaki fark, bir JSON nesnesinin anahtarının çift tırnaklı olması veya bir dize olması gerektiğidir. JavaScript Object ve JSON, JSON'u Object ve Object'i JSON olarak değiştirebileceğimize çok benzer. - -Yukarıdaki örneği daha detaylı görelim, küme paranteziyle başlıyor. Kıvrımlı parantez içinde bir değer dizisine sahip "users" anahtarı vardır. Dizinin içinde farklı nesnelerimiz var ve her nesnenin anahtarı var, her anahtarın çift tırnak işareti olması gerekiyor. Örneğin, sadece firstName yerine "firstNaMe" kullanıyoruz, ancak nesnede anahtarları çift tırnak işaretleri olmadan kullanıyoruz. Bu, bir nesne ile bir JSON arasındaki en büyük farktır. JSON hakkında daha fazla örnek görelim. - -**Örnek:** - -```js -{ - "Alex": { - "email": "alex@alex.com", - "skills": [ - "HTML", - "CSS", - "JavaScript" - ], - "age": 20, - "isLoggedIn": false, - "points": 30 - }, - "Asab": { - "email": "asab@asab.com", - "skills": [ - "HTML", - "CSS", - "JavaScript", - "Redux", - "MongoDB", - "Express", - "React", - "Node" - ], - "age": 25, - "isLoggedIn": false, - "points": 50 - }, - "Brook": { - "email": "daniel@daniel.com", - "skills": [ - "HTML", - "CSS", - "JavaScript", - "React", - "Redux" - ], - "age": 30, - "isLoggedIn": true, - "points": 50 - }, - "Daniel": { - "email": "daniel@alex.com", - "skills": [ - "HTML", - "CSS", - "JavaScript", - "Python" - ], - "age": 20, - "isLoggedIn": false, - "points": 40 - }, - "John": { - "email": "john@john.com", - "skills": [ - "HTML", - "CSS", - "JavaScript", - "React", - "Redux", - "Node.js" - ], - "age": 20, - "isLoggedIn": true, - "points": 50 - }, - "Thomas": { - "email": "thomas@thomas.com", - "skills": [ - "HTML", - "CSS", - "JavaScript", - "React" - ], - "age": 20, - "isLoggedIn": false, - "points": 40 - }, - "Paul": { - "email": "paul@paul.com", - "skills": [ - "HTML", - "CSS", - "JavaScript", - "MongoDB", - "Express", - "React", - "Node" - ], - "age": 20, - "isLoggedIn": false, - "points": 40 - } -} -``` - -### JSON'u JavaScript Nesnesine Dönüştürme - -Çoğunlukla JSON verilerini HTTP yanıtından veya bir dosyadan alırız, ancak JSON'u bir dize olarak saklayabiliriz ve gösterim amacıyla Object olarak değiştirebiliriz. JavaScript'te _JSON_ anahtar sözcüğü _parse()_ ve _stringify()_ yöntemlerine sahiptir. JSON'u bir nesneye dönüştürmek istediğimizde, _JSON.parse()_ kullanarak JSON'u ayrıştırırız. Nesneyi JSON olarak değiştirmek istediğimizde _JSON.stringify()_ kullanırız. - -#### JSON.parse() - -```js -JSON.parse(json[, reviver]) -// json or text , the data -// reviver opsiyonel callback fonksiyonudur -/* JSON.parse(json, (key, value) => { - -}) -*/ -``` - -```js -const usersText = `{ -"users":[ - { - "firstName":"Asabeneh", - "lastName":"Yetayeh", - "age":250, - "email":"asab@asb.com" - }, - { - "firstName":"Alex", - "lastName":"James", - "age":25, - "email":"alex@alex.com" - }, - { - "firstName":"Lidiya", - "lastName":"Tekle", - "age":28, - "email":"lidiya@lidiya.com" - } -] -}` - -const usersObj = JSON.parse(usersText, undefined, 4) -console.log(usersObj) -``` - -### JSON.parse() ile bir reviver fonksiyonu kullanma - -Reviver fonksiyonunu formatlayıcı olarak kullanmak için isim ve soyadı değerini formatlamak istediğimiz tuşları koyuyoruz. Diyelim ki, JSON verilerinin ad ve soyadını biçimlendirmekle ilgileniyoruz. - -```js -const usersText = `{ -"users":[ - { - "firstName":"Asabeneh", - "lastName":"Yetayeh", - "age":250, - "email":"asab@asb.com" - }, - { - "firstName":"Alex", - "lastName":"James", - "age":25, - "email":"alex@alex.com" - }, - { - "firstName":"Lidiya", - "lastName":"Tekle", - "age":28, - "email":"lidiya@lidiya.com" - } -] -}` - -const usersObj = JSON.parse(usersText, (key, value) => { - let newValue = - typeof value == 'string' && key != 'email' ? value.toUpperCase() : value - return newValue -}) -console.log(usersObj) -``` - -_JSON.parse()_ kullanımı çok kullanışlıdır. İsteğe bağlı parametreyi geçmenize gerek yok, sadece gerekli parametre ile kullanabilirsiniz ve çok şey başaracaksınız. - -### Nesneyi JSON'a Dönüştürme - -Nesneyi JSON olarak değiştirmek istediğimizde _JSON.stringify()_ kullanırız. stringify yöntemi, bir gerekli parametre ve iki isteğe bağlı parametre alır. Değiştirici filtre olarak kullanılır ve boşluk bir girintidir. Nesnedeki anahtarlardan herhangi birini filtrelemek istemiyorsak, tanımsız olarak geçebiliriz. - -```js -JSON.stringify(obj, replacer, space) -// json or text , the data -// reviver opsiyonel callback fonksiyonudur -``` - -Aşağıdaki nesneyi bir string değere dönüştürelim. İlk önce tüm anahtarları kullanalım ve ayrıca 4 boşluk girintisine sahip olalım. - -```js -const users = { - Alex: { - email: 'alex@alex.com', - skills: ['HTML', 'CSS', 'JavaScript'], - age: 20, - isLoggedIn: false, - points: 30 - }, - Asab: { - email: 'asab@asab.com', - skills: [ - 'HTML', - 'CSS', - 'JavaScript', - 'Redux', - 'MongoDB', - 'Express', - 'React', - 'Node' - ], - age: 25, - isLoggedIn: false, - points: 50 - }, - Brook: { - email: 'daniel@daniel.com', - skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'], - age: 30, - isLoggedIn: true, - points: 50 - }, - Daniel: { - email: 'daniel@alex.com', - skills: ['HTML', 'CSS', 'JavaScript', 'Python'], - age: 20, - isLoggedIn: false, - points: 40 - }, - John: { - email: 'john@john.com', - skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node.js'], - age: 20, - isLoggedIn: true, - points: 50 - }, - Thomas: { - email: 'thomas@thomas.com', - skills: ['HTML', 'CSS', 'JavaScript', 'React'], - age: 20, - isLoggedIn: false, - points: 40 - }, - Paul: { - email: 'paul@paul.com', - skills: [ - 'HTML', - 'CSS', - 'JavaScript', - 'MongoDB', - 'Express', - 'React', - 'Node' - ], - age: 20, - isLoggedIn: false, - points: 40 - } -} - -const txt = JSON.stringify(users, undefined, 4) -console.log(txt) // text, JSON- anlamına gelir, çünkü json bir nesnenin string biçimidir. -``` - -```sh -{ - "Alex": { - "email": "alex@alex.com", - "skills": [ - "HTML", - "CSS", - "JavaScript" - ], - "age": 20, - "isLoggedIn": false, - "points": 30 - }, - "Asab": { - "email": "asab@asab.com", - "skills": [ - "HTML", - "CSS", - "JavaScript", - "Redux", - "MongoDB", - "Express", - "React", - "Node" - ], - "age": 25, - "isLoggedIn": false, - "points": 50 - }, - "Brook": { - "email": "daniel@daniel.com", - "skills": [ - "HTML", - "CSS", - "JavaScript", - "React", - "Redux" - ], - "age": 30, - "isLoggedIn": true, - "points": 50 - }, - "Daniel": { - "email": "daniel@alex.com", - "skills": [ - "HTML", - "CSS", - "JavaScript", - "Python" - ], - "age": 20, - "isLoggedIn": false, - "points": 40 - }, - "John": { - "email": "john@john.com", - "skills": [ - "HTML", - "CSS", - "JavaScript", - "React", - "Redux", - "Node.js" - ], - "age": 20, - "isLoggedIn": true, - "points": 50 - }, - "Thomas": { - "email": "thomas@thomas.com", - "skills": [ - "HTML", - "CSS", - "JavaScript", - "React" - ], - "age": 20, - "isLoggedIn": false, - "points": 40 - }, - "Paul": { - "email": "paul@paul.com", - "skills": [ - "HTML", - "CSS", - "JavaScript", - "MongoDB", - "Express", - "React", - "Node" - ], - "age": 20, - "isLoggedIn": false, - "points": 40 - } -} -``` - -### JSON.stringify ile Filtre Dizisi Kullanma - -Şimdi, replacerı filtre olarak kullanalım. Kullanıcı nesnesinin uzun bir anahtar listesi var ama biz sadece birkaçıyla ilgileniyoruz. Örnekte gösterildiği gibi dizide tutmak istediğimiz anahtarları koyuyoruz ve replacer yerine kullanıyoruz. - -```js -const user = { - firstName: 'Asabeneh', - lastName: 'Yetayeh', - country: 'Finland', - city: 'Helsinki', - email: 'alex@alex.com', - skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Python'], - age: 250, - isLoggedIn: false, - points: 30 -} - -const txt = JSON.stringify(user,['firstName', 'lastName', 'country', 'city', 'age'],4) -console.log(txt) -``` - -```sh -{ - "firstName": "Asabeneh", - "lastName": "Yetayeh", - "country": "Finland", - "city": "Helsinki", - "age": 250 -} -``` - -🌕 Sen olağanüstüsün. Artık verileri depolamak veya bir HTTP sunucusu göndermek için kullanabileceğiniz hafif bir veri formatı biliyorsunuz. Büyüklüğe giden yolda 16 adım öndesin. Şimdi beyniniz ve kasınız için bazı egzersizler yapın. - -## Egzersizler - -```js -const skills = ['HTML', 'CSS', 'JS', 'React','Node', 'Python'] -let age = 250; -let isMarried = true -const student = { - firstName:'Asabeneh', - lastName:'Yetayehe', - age:250, - isMarried:true, - skills:['HTML', 'CSS', 'JS', 'React','Node', 'Python', ] -} -const txt = `{ - "Alex": { - "email": "alex@alex.com", - "skills": [ - "HTML", - "CSS", - "JavaScript" - ], - "age": 20, - "isLoggedIn": false, - "points": 30 - }, - "Asab": { - "email": "asab@asab.com", - "skills": [ - "HTML", - "CSS", - "JavaScript", - "Redux", - "MongoDB", - "Express", - "React", - "Node" - ], - "age": 25, - "isLoggedIn": false, - "points": 50 - }, - "Brook": { - "email": "daniel@daniel.com", - "skills": [ - "HTML", - "CSS", - "JavaScript", - "React", - "Redux" - ], - "age": 30, - "isLoggedIn": true, - "points": 50 - }, - "Daniel": { - "email": "daniel@alex.com", - "skills": [ - "HTML", - "CSS", - "JavaScript", - "Python" - ], - "age": 20, - "isLoggedIn": false, - "points": 40 - }, - "John": { - "email": "john@john.com", - "skills": [ - "HTML", - "CSS", - "JavaScript", - "React", - "Redux", - "Node.js" - ], - "age": 20, - "isLoggedIn": true, - "points": 50 - }, - "Thomas": { - "email": "thomas@thomas.com", - "skills": [ - "HTML", - "CSS", - "JavaScript", - "React" - ], - "age": 20, - "isLoggedIn": false, - "points": 40 - }, - "Paul": { - "email": "paul@paul.com", - "skills": [ - "HTML", - "CSS", - "JavaScript", - "MongoDB", - "Express", - "React", - "Node" - ], - "age": 20, - "isLoggedIn": false, - "points": 40 - } -} -` -``` - -### Egzersiz Seviye 1 - -1. JSON.stringify() kullanarak skills dizisini JSON olarak değiştirin -1. age değerini stringify et -1. isMarried değerini stringify et -1. student nesnesini stringify et - -### Egzersiz Seviye 2 - -1. Öğrenciler nesnesini yalnızca firstName, lastName ve skills özellikleriyle stringify edin - -### Egzersiz Seviye 3 - -1. *txt* JSON'u nesneye ayrıştırın. -2. *txt* içinde saklanan değişkenden birçok skills'e sahip olan kullanıcıyı bulun. - -🎉 TEBRİKLER ! 🎉 - -[<< Gün 15](../15_Day_Classes/15_day_classes.md) | [Gün 17 >>](../17_Day_Web_storages/17_day_web_storages.md) diff --git a/Turkish/17_Day_Web_storages/17_day_web_storages.md b/Turkish/17_Day_Web_storages/17_day_web_storages.md deleted file mode 100644 index bc1c55b..0000000 --- a/Turkish/17_Day_Web_storages/17_day_web_storages.md +++ /dev/null @@ -1,234 +0,0 @@ -
-

30 Days Of JavaScript: Web Storages

- - - - - Twitter Follow - - -Author: -Asabeneh Yetayeh
- January, 2020 -
- -
- -[<< Gün 16](../16_Day_JSON/16_day_json.md) | [Gün 18 >>](../18_Day_Promises/18_day_promises.md) - -![Thirty Days Of JavaScript](../../images/banners/day_1_17.png) - -- [Gün 17](#day-17) - - [HTML5 Web Storage(Depolama)](#html5-web-storage) - - [sessionStorage](#sessionstorage) - - [localStorage](#localstorage) - - [Web Storages Kullanım Durumu(alanlar)](#use-case-of-web-storages) - - [HTML5 Web Depolama Nesneleri](#html5-web-storage-objects) - - [Öğeyi localStorage'a ayarlama](#setting-item-to-the-localstorage) - - [Öğeyi localStorage'dan alma](#getting-item-from-localstorage) - - [localStorage'ı temizleme](#clearing-the-localstorage) - - [Egzersizler](#exercises) - - [Egzersiz: Seviye 1](#exercises-level-1) - - [Egzersiz: Seviye 2](#exercises-level-2) - - [Egzersiz: Seviye 3](#exercises-level-3) - -# Gün 17 - -## HTML5 Web Storage(Depolama) - -Web Depolama (sessionStorage ve localStorage), geleneksel tanımlama bilgilerine göre önemli avantajlar sunan yeni bir HTML5 API'sidir. HTML5'ten önce, uygulama verilerinin her sunucu isteğine dahil olan çerezlerde saklanması gerekiyordu. Web depolaması daha güvenlidir ve büyük miktarda veri web sitesi performansını etkilemeden local(yerel) olarak depolanabilir. Çerezlerin birçok web tarayıcısında veri depolama sınırı, çerez başına yaklaşık 4 KB'dir. Web Storage çok daha büyük verileri (en az 5MB) depolayabiliriz ve asla sunucuya aktarılmaz. Aynı veya bir kaynaktan gelen tüm siteler aynı verileri depolayabilir ve bunlara erişebilir. - -Depolanan verilere JavaScript kullanılarak erişilebilir; bu, geleneksel olarak sunucu tarafı programlama ve ilişkisel veritabanlarını içeren birçok şeyi yapmak için istemci tarafı komut dosyası oluşturma yeteneğinden yararlanmanızı sağlar. İki Web Depolama nesnesi vardır: - -- sessionStorage -- localStorage - -localStorage, sessionStorage'a benzer, ancak localStorage'da depolanan verilerin sona erme süresi olmamasına rağmen, sessionStorage'da depolanan verilerin sayfa oturumu sona erdiğinde, yani sayfa kapatıldığında silinmesi dışında. - -localStorage veya sessionStorage'da depolanan verilerin sayfanın protokolüne özel olduğuna dikkat edilmelidir. - -Anahtarlar ve değerler her zaman dizelerdir (nesnelerde olduğu gibi tamsayı tuşlarının otomatik olarak dizelere dönüştürüleceğini unutmayın). - -![web_storage](../images/web_storage.png) - -### sessionStorage - -sessionStorage yalnızca tarayıcı sekmesinde veya pencere oturumunda kullanılabilir. Verileri tek bir web sayfası oturumunda depolamak için tasarlanmıştır. Bu, pencere kapatılırsa oturum verilerinin kaldırılacağı anlamına gelir. sessionStorage ve localStorage benzer yöntemlere sahip olduğundan, sadece localStorage'a odaklanacağız. - -### localStorage - -HTML5 localStorage, son kullanma verisi olmadan tarayıcıda veri depolamak için kullanılan web depolama API'sinin para birimidir. Veriler, tarayıcı kapatıldıktan sonra bile tarayıcıda mevcut olacaktır. localStorage, tarayıcı oturumları arasında bile tutulur. Bu, tarayıcı kapatılıp yeniden açıldığında ve ayrıca sekmeler ve pencereler arasında anında verilerin hala mevcut olduğu anlamına gelir. - -Web Depolama verileri, her iki durumda da farklı tarayıcılar arasında mevcut değildir. Örneğin, Firefox'ta oluşturulan depolama nesnelerine tıpkı çerezler gibi Internet Explorer'da erişilemez. -Yerel depolama üzerinde çalışmak için beş yöntem vardır: -_setItem(), getItem(), removeItem(), clear(), key()_ - -### Web Storages Kullanım Durumu(alanlar) - -Web Depolarının bazı kullanım durumları şunlardır: - -- verileri geçici olarak depolamak -- kullanıcının alışveriş sepetine koyduğu ürünleri kaydetme -- veriler, sayfa istekleri, birden çok tarayıcı sekmesi arasında ve ayrıca localStorage kullanılarak tarayıcı oturumları arasında kullanılabilir hale getirilebilir -- localStorage kullanılarak tamamen çevrimdışı olarak kullanılabilir -- Web Depolama, sonraki isteklerin sayısını en aza indirmek için istemcide bazı statik veriler depolandığında harika bir performans kazancı olabilir. Görüntüler bile Base64 kodlaması kullanılarak dizelerde saklanabilir. -- kullanıcı kimlik doğrulama yöntemi için kullanılabilir - -Yukarıda bahsedilen örnekler için localStorage kullanmak mantıklıdır. O halde sessionStorage'ı ne zaman kullanmamız gerektiğini merak ediyor olabilirsiniz. - -Bazı durumlarda, pencere kapanır kapanmaz verilerden kurtulmak istiyoruz. Ya da uygulamanın başka bir pencerede açık olan aynı uygulamaya müdahale etmesini istemiyorsak. Bu senaryolar en iyi şekilde sessionStorage ile sunulur. - -Şimdi, bu Web Depolama API'lerinden nasıl yararlanılacağını görelim. - -## HTML5 Web Depolama Nesneleri - -HTML web depolama, istemcide veri depolamak için iki nesne sağlar: - -- window.localStorage - son kullanma tarihi olmayan verileri depolar -- window.sessionStorage - bir oturum için veri depolar (tarayıcı sekmesi kapatıldığında veriler kaybolur) Çoğu modern tarayıcı Web Depolamayı destekler, ancak localStorage ve sessionStorage için tarayıcı desteğini kontrol etmek iyidir. Web Depolama nesneleri için mevcut yöntemleri görelim. - -Web Depolama Nesneleri: - -- _localStorage_ - localStorage nesnesini görüntülemek için -- _localStorage.clear()_ - localStrogedaki her şeyi kaldırmak için -- _localStorage.setItem()_ - verileri localStorage'da depolamak için. Bir anahtar ve bir değer parametresi alır. -- _localStorage.getItem()_ - localStorage'da depolanan verileri görüntülemek için. Parametre olarak bir anahtar alır. -- _localStorage.removeItem()_ - depolanan öğeyi localStorage'dan kaldırmak için. Parametre olarak bir anahtar alır. -- _localStorage.key()_ - localStorage'da depolanan verileri görüntülemek için. Parametre olarak indeks alır. - -![local_storage](../images/local_storage.png) - -### Öğeyi localStorage'a ayarlama - -Bir localStorage'da saklanacak verileri ayarladığımızda, bir dize olarak saklanacaktır. Bir diziyi veya nesneyi depoluyorsak, orijinal verinin dizi yapısını veya nesne yapısını kaybetmediğimiz sürece, formatı korumak için önce onu dizgelendirmemiz gerekir. - -Verileri localStorage'da _localStorage.setItem_ yöntemini kullanarak depolarız. - -```js -//syntax -localStorage.setItem('key', 'value') -``` - -- String ifadeleri localStorage üzerinde saklama - -```js -localStorage.setItem('firstName', 'Asabeneh') // değer string olduğundan onu stringleştirmeyiz -console.log(localStorage) -``` - -```sh -Storage {firstName: 'Asabeneh', length: 1} -``` - -- Number ifadeleri localStorage üzerinde saklama - -```js -localStorage.setItem('age', 200) -console.log(localStorage) -``` - -```sh - Storage {age: '200', firstName: 'Asabeneh', length: 2} -``` - -- Bir diziyi localStorage'da depolamak. Bir diziyi, nesneyi veya nesne dizisini depoluyorsak, önce nesneyi dizgelendirmemiz gerekir. Aşağıdaki örneğe bakın. - -```js -const skills = ['HTML', 'CSS', 'JS', 'React'] -//Biçimi korumak için önce skills dizisinin dizilmesi gerekir. -const skillsJSON = JSON.stringify(skills, undefined, 4) -localStorage.setItem('skills', skillsJSON) -console.log(localStorage) -``` - -```sh -Storage {age: '200', firstName: 'Asabeneh', skills: 'HTML,CSS,JS,React', length: 3} -``` - -```js -let skills = [ - { tech: 'HTML', level: 10 }, - { tech: 'CSS', level: 9 }, - { tech: 'JS', level: 8 }, - { tech: 'React', level: 9 }, - { tech: 'Redux', level: 10 }, - { tech: 'Node', level: 8 }, - { tech: 'MongoDB', level: 8 } -] - -let skillJSON = JSON.stringify(skills) -localStorage.setItem('skills', skillJSON) -``` - -- Bir nesneyi localStorage'da depolamak. Nesneleri bir localStorage'a depolamadan önce, nesnenin dizelenmesi gerekir. - -```js -const user = { - firstName: 'Asabeneh', - age: 250, - skills: ['HTML', 'CSS', 'JS', 'React'] -} - -const userText = JSON.stringify(user, undefined, 4) -localStorage.setItem('user', userText) -``` - -### Öğeyi localStorage'dan alma - -_localStorage.getItem()_ yöntemini kullanarak yerel depodan veri alıyoruz.. - -```js -//syntax -localStorage.getItem('key') -``` - -```js -let firstName = localStorage.getItem('firstName') -let age = localStorage.getItem('age') -let skills = localStorage.getItem('skills') -console.log(firstName, age, skills) -``` - -```sh - 'Asabeneh', '200', '['HTML','CSS','JS','React']' -``` - -Gördüğünüz gibi skills string formatında. Normal diziye ayrıştırmak için JSON.parse() kullanalım. - -```js -let skills = localStorage.getItem('skills') -let skillsObj = JSON.parse(skills, undefined, 4) -console.log(skillsObj) -``` - -```sh -['HTML','CSS','JS','React'] -``` - -### localStorage'ı temizleme - -Clear yöntemi, yerel depolamada depolanan her şeyi temizleyecektir. - -```js -localStorage.clear() -``` - -🌕 Kararlısınız. Artık Web Depolama biliyorsunuz ve küçük verileri istemci tarayıcılarında nasıl depolayacağınızı biliyorsunuz. Büyüklüğe giden yolda 17 adım öndesin. Şimdi beyniniz ve kasınız için bazı egzersizler yapın. - -## Egzersizler - -### Egzersiz: Seviye 1 - -1. Adınızı, soyadınızı, yaşınızı, ülkenizi, şehrinizi tarayıcınızın localStorage'ında saklayın. - -### Egzersiz: Seviye 2 - -1. Bir öğrenci nesnesi oluşturun. Öğrenci nesnesinin adı, soyadı, yaşı, becerileri, ülkesi, kayıtlı anahtarları ve anahtarların değerleri olacaktır. Öğrenci nesnesini tarayıcınızın localStorage'ında saklayın. - -### Egzersiz: Seviye 3 - -1. personAccount adlı bir nesne oluşturun. ad, soyad, gelirler, giderler özelliklerine sahip olup totalIncome, totalExpense, accountInfo,addIncome, addExpense ve accountBalance yöntemlerine sahip olsun. Gelirler bir dizi gelirdir ve tanımı ve giderleri de bir dizi gider ve tanımıdır. - -🎉 TEBRİKLER ! 🎉 - -[<< Gün 16](../16_Day_JSON/16_day_json.md) | [Gün 18 >>](../18_Day_Promises/18_day_promises.md) diff --git a/Turkish/18_Day_Promises/18_day_promises.md b/Turkish/18_Day_Promises/18_day_promises.md deleted file mode 100644 index c3cab0f..0000000 --- a/Turkish/18_Day_Promises/18_day_promises.md +++ /dev/null @@ -1,272 +0,0 @@ -
-

30 Days Of JavaScript: Promises

- - - - - Twitter Follow - - -Author: -Asabeneh Yetayeh
- January, 2020 -
- -
- -[<< Gün 17](../17_Day_Web_storages/17_day_web_storages.md) | [Gün 19>>](../19_Day_Closures/19_day_closures.md) - -![Thirty Days Of JavaScript](../../images/banners/day_1_18.png) - -- [Gün 18](#gün-18) - - [Promise](#promise) - - [Callbacks](#callbacks) - - [Promise yapıcısı](#promise-constructor) - - [Fetch API](#fetch-api) - - [Async ve Await](#async-and-await) - - [Egzersizler](#egzersizler) - - [Egzersiz: Seviye 1](#egzersiz-level-1) - - [Egzersiz: Seviye 2](#egzersiz-level-2) - - [Egzersiz: Seviye 3](#egzersiz-level-3) - -# Gün 18 - -## Promise - -Biz insanlar, belirli bir zamanda bir faaliyette bulunma sözü veririz veya alırız. Sözümüzü tutarsak başkalarını mutlu ederiz, ama sözümüzü tutmazsak hoşnutsuzluklara yol açabilir. JavaScript'te promise(söz) vermenin yukarıdaki örneklerle ortak bir yanı vardır. - -Bir promise, JavaScript'te asynchronous işlemleri işlemenin bir yoludur. Asynchronous bir eylemin nihai başarı değeri veya başarısızlık nedeni ile işleyicilere izin verir. Bu, asynchronous yöntemlerin synchronous yöntemler gibi değerler döndürmesine olanak tanır: asynchronous yöntem, nihai değeri hemen döndürmek yerine, gelecekte bir noktada değeri sağlama sözü verir. - -Bir Promise şu durumlardan birindedir: - -- pending: başlangıç ​​durumunda, ne tamamlandı ne de reddedildi. -- fulfilled: işlemin başarıyla tamamlandığı anlamına gelir. -- rejected: işlemin başarısız olduğu anlamına gelir. - -Bekleyen bir promise ya bir değerle yerine getirilebilir(fulfilled) ya da bir sebeple (error) rejected olabilir. Bu seçeneklerden herhangi biri gerçekleştiğinde, bir sözün o zaman yöntemiyle sıraya alınan ilişkili işleyiciler çağrılır. (Karşılık gelen bir işleyici(handler) eklendiğinde promise zaten fulfilled veya rejected ise, işleyici(handler) çağrılır, bu nedenle asynchronous bir işlemin tamamlanması ile işleyicilerinin eklenmesi arasında bir yarış koşulu yoktur.) - -As the Promise.prototype.then() and Promise.prototype.catch() methods return promises, they can be chained. - -## Callbacks - -Promise çok iyi anlamak için önce callback mantığını anlayalım. Aşağıdaki callback örneklerini görelim. Aşağıdaki kod bloklarında, callback ve promise arasındaki farkları fark edeceksiniz. - -- callback - Let us see a callback function which can take two parameters. The first parameter is err and the second is result. If the err parameter is false, there will not be error other wise it will return an error. - -In this case the err has a value and it will return the err block. - -```js -//Callback -const doSomething = callback => { - setTimeout(() => { - const skills = ['HTML', 'CSS', 'JS'] - callback('It did not go well', skills) - }, 2000) -} - -const callback = (err, result) => { - if (err) { - return console.log(err) - } - return console.log(result) -} - -doSomething(callback) -``` - -```sh -// 2 saniye sonra yazdırıcak -It did not go well -``` - -Bu durumda hata yanlıştır ve sonuç olan else bloğunu döndürür. - -```js -const doSomething = callback => { - setTimeout(() => { - const skills = ['HTML', 'CSS', 'JS'] - callback(false, skills) - }, 2000) -} - -doSomething((err, result) => { - if (err) { - return console.log(err) - } - return console.log(result) -}) -``` - -```sh -// 2 saniye sonra yazdırıcak -["HTML", "CSS", "JS"] -``` - -### Promise yapıcısı - -Promise yapıcısını kullanarak bir promise oluşturabiliriz. `new` anahtar kelimesini, ardından `Promise` kelimesini ve ardından bir parantez kullanarak yeni bir promise oluşturabiliriz. Parantez içinde bir `callback` işlevi alır. Promise callback fonksiyonu, `resolve` ve `reject` fonksiyonları olmak üzere iki parametreye sahiptir. - -```js -// syntax -const promise = new Promise((resolve, reject) => { - resolve('success') - reject('failure') -}) -``` - -```js -// Promise -const doPromise = new Promise((resolve, reject) => { - setTimeout(() => { - const skills = ['HTML', 'CSS', 'JS'] - if (skills.length > 0) { - resolve(skills) - } else { - reject('Something wrong has happened') - } - }, 2000) -}) - -doPromise - .then(result => { - console.log(result) - }) - .catch(error => console.log(error)) -``` - -```sh -["HTML", "CSS", "JS"] -``` - -Yukarıdaki promise kararlılıkla yerine getirilmiştir. Promise'ın reject ile kararlaştırıldığı başka bir örnek verelim. - -```js -// Promise -const doPromise = new Promise((resolve, reject) => { - setTimeout(() => { - const skills = ['HTML', 'CSS', 'JS'] - if (skills.includes('Node')) { - resolve('fullstack developer') - } else { - reject('Something wrong has happened') - } - }, 2000) -}) - -doPromise - .then(result => { - console.log(result) - }) - .catch(error => console.error(error)) -``` - -```sh -Something wrong has happened -``` - -## Fetch API - -Fetch API'si, kaynakları (ağ genelindekiler dahil) almak için bir interface sağlar. XMLHttpRequest kullanan herkese tanıdık gelecektir, ancak yeni API daha güçlü ve esnek bir özellik seti sağlar. Bu görevde, url ve APIS istemek için fetch kullanacağız. Buna ek olarak, fetch API'sini kullanarak ağ kaynaklarına erişimde promise kullanım durumunu gösterelim. - -```js -const url = 'https://restcountries.com/v2/all' // countries api -fetch(url) - .then(response => response.json()) // API verilerine JSON olarak erişme - .then(data => { - // verileri almak - console.log(data) - }) - .catch(error => console.error(error)) // yanlış bir şey olursa işleme hatası -``` - -## Async ve Await - -Async ve Await, promise yerine getirmenin zarif bir yoludur. Anlaşılması kolay ve yazması temiz. - -```js -const square = async function (n) { - return n * n -} - -square(2) -``` - -```sh -Promise {: 4} -``` - -Bir fonksiyonun önündeki async kelimesi, fonksiyonun bir promise vereceği anlamına gelir. Yukarıdaki kare fonksiyonu bir değer yerine bir promise verir. - -Promise gelen değere nasıl erişiriz? Promise verilen değere erişmek için, wait anahtar sözcüğünü kullanacağız. - -```js -const square = async function (n) { - return n * n -} -const value = await square(2) -console.log(value) -``` - -```sh -4 -``` - -Şimdi, yukarıdaki örnekte de görebileceğiniz gibi, bir fonksiyonun önüne async yazarak bir promise oluşturun ve bir promise değer almak için bekliyoruz. Async ve await birlikte çalışır, biri olmadan diğeri olamaz. - -API verilerini hem promise yöntemini kullanarak hem de async ve await yöntemini kullanarak getirelim. - -- promise - -```js -const url = 'https://restcountries.com/v2/all' -fetch(url) - .then(response => response.json()) - .then(data => { - console.log(data) - }) - .catch(error => console.error(error)) -``` - -- async ve await - -```js -const fetchData = async () => { - try { - const response = await fetch(url) - const countries = await response.json() - console.log(countries) - } catch (err) { - console.error(err) - } -} -console.log('===== async and await') -fetchData() -``` - -🌕 Sen gerçeksin ve sözünü tuttun ve 18. güne ulaştın. Sözünü tut ve azimle meydan oku. Büyüklüğe giden yolda 18 adım öndesin. Şimdi beyniniz ve kaslarınız için bazı egzersizler yapın - -## Egzersizler - -```js -const countriesAPI = 'https://restcountries.com/v2/all' -const catsAPI = 'https://api.thecatapi.com/v1/breeds' -``` - -### Egzersiz: Seviye 1 - -1. Fetch kullanarak countriesAPI'sini okuyun ve country, capital, languages, population ve area adını yazdırın. - -### Egzersiz: Seviye 2 - -1. Tüm kedi adlarını catNames değişkenine yazdırın. - -### Egzersiz: Seviye 3 - -1. catsAPI'sini okuyun ve kedinin ortalama ağırlığını metrik birimde bulun. -2. countriesAPI'sini okuyun ve en büyük(largest) 10 ülkeyi bulun. -3. countriesAPI'sini okuyun ve dünyada resmi olarak kullanılan toplam dil sayısını bulun. - -🎉 TEBRİKLER ! 🎉 - -[<< Gün 17](../17_Day_Web_storages/17_day_web_storages.md) | [Gün 19>>](../19_Day_Closures/19_day_closures.md) diff --git a/Turkish/19_Day_Closures/19_day_closures.md b/Turkish/19_Day_Closures/19_day_closures.md deleted file mode 100644 index 503f8b8..0000000 --- a/Turkish/19_Day_Closures/19_day_closures.md +++ /dev/null @@ -1,104 +0,0 @@ -
-

30 Days Of JavaScript: Closures

- - - - - Twitter Follow - - -Author: -Asabeneh Yetayeh
- January, 2020 -
- -
- -[<< Gün 18](../18_Day_Promises/18_day_promises.md) | [Gün 20 >>](../20_Day_Writing_clean_codes/20_Day_writing_clean_codes.md) - -![Thirty Days Of JavaScript](../../images/banners/day_1_19.png) -- [Gün 19](#gün-19) - - [Closure](#closure) - - [Egzersizler](#egzersizler) - - [Egzersiz: Seviye 1](#egzersiz-seviye-1) - - [Egzersiz: Seviye 2](#egzersiz-seviye-2) - - [Egzersiz: Seviye 3](#egzersiz-seviye-3) - -# Gün 19 - -## Closure - -JavaScript, bir outer(dış) fonksiyonu içine yazma fonksiyonu izni verir. İstediğimiz kadar inner(iç) fonksiyon yazabiliriz. Inner fonksiyon, outer fonksiyonun değişkenlerine erişiyorsa, buna closure(kapatma) denir. - -```js -function outerFunction() { - let count = 0; - function innerFunction() { - count++ - return count - } - - return innerFunction -} -const innerFunc = outerFunction() - -console.log(innerFunc()) -console.log(innerFunc()) -console.log(innerFunc()) -``` - -```sh -1 -2 -3 -``` - -Inner(iç) fonksiyonlara daha fazla örnek vermek gerekirse - -```js -function outerFunction() { - let count = 0; - function plusOne() { - count++ - return count - } - function minusOne() { - count-- - return count - } - - return { - plusOne:plusOne(), - minusOne:minusOne() - } -} -const innerFuncs = outerFunction() - -console.log(innerFuncs.plusOne) -console.log(innerFuncs.minusOne) -``` - -```sh -1 -0 -``` - -🌕 İlerleme kaydediyorsun. Hızınızı koruyun, iyi işlere devam edin. Şimdi beyniniz ve kasınız için bazı egzersizler yapın. - -## Egzersizler - -### Egzersiz: Seviye 1 - -1. Bir inner(iç) fonksiyonu olan closure yapısı oluşturun. - -### Egzersiz: Seviye 2 - -1. Üç tane inner(iç) fonksiyonu olan closure yapısı oluşturun. - -### Egzersiz: Seviye 3 - -1. Bir personAccount outer(dış) fonksiyonu oluşturun. Ad, soyad, gelir ve gider inner(iç) değişkenleridir. totalIncome, totalExpense, accountInfo,addIncome, addExpense ve accountBalance inner fonksiyonlara sahiptir. - -🎉 TEBRİKLER ! 🎉 - -[<< Gün 18](../18_Day_Promises/18_day_promises.md) | [Gün 20 >>](../20_Day_Writing_clean_codes/20_Day_writing_clean_codes.md) \ No newline at end of file diff --git a/Turkish/20_Day_Writing_clean_codes/20_Day_writing_clean_codes.md b/Turkish/20_Day_Writing_clean_codes/20_Day_writing_clean_codes.md deleted file mode 100644 index ef7b1d1..0000000 --- a/Turkish/20_Day_Writing_clean_codes/20_Day_writing_clean_codes.md +++ /dev/null @@ -1,341 +0,0 @@ -
-

30 Days Of JavaScript: Writing Clean Codes

- - - - - Twitter Follow - - -Author: -Asabeneh Yetayeh
- January, 2020 -
- -
- -[<< Gün 19](../19_Day_Closures/19_day_closures.md) | [Gün 21 >>](../21_Day_DOM/21_day_dom.md) - -![Thirty Days Of JavaScript](../../images/banners/day_1_20.png) -- [Gün 20](#gun-20) - - [Temiz Kod Yazmak](#temiz-kod-yazmak) - - [JavaScript Stil Kılavuzu](#javaScript-stil-kılavuzu) - - [Neden stil kılavuzuna ihtiyacımız var?](#neden-stil-kılavuzuna-ihtiyacımız-var) - - [Airbnb JavaScript Style Guide](#airbnb-javascript-style-guide) - - [Standard JavaScript Style Guide](#standard-javascript-style-guide) - - [Google JavaScript Style Guide](#google-javascript-style-guide) - - [JavaScript Kodlama Kuralları](#javaScript-kodlama-kuralları) - - [30DaysOfJavaScript'te kullanılan kurallar](#30DaysOfJavaScript-kullanılan-kurallar) - - [Değişkenler](#Degiskenler) - - [Arrays(Diziler)](#arrays) - - [Fonksiyonlar](#fonksiyonlar) - - [Döngüler](#donguler) - - [Nesneler](#nesneler) - - [Koşullar](#kosullar) - - [Sınıflar](#sınıflar) - -# Gün 20 - -## Temiz Kod Yazmak - -### JavaScript Stil Kılavuzu - -JavaScript stil kılavuzu, JavaScript kodunun nasıl yazılması ve düzenlenmesi gerektiğini söyleyen bir dizi standarttır. Bu bölümde JavaScript rehberlerinden ve temiz kod nasıl yazılırdan bahsedeceğiz. - -JavaScript bir programlama dilidir ve insan dili gibi syntax(sözdizimi) yapısına sahiptir. JavaScript'in sözdizimi, kolaylık ve basitlik adına belirli bir stil yönergesini izleyerek yazılmalıdır. - -### Neden stil kılavuzuna ihtiyacımız var? - -Çok uzun zamandır tek başına kodlama yapıyorsun ama şimdi bir ekip halinde çalışıyorsun gibi düşünelim. Tek çalıştığın sürece nasıl kod yazdığınız bu kadar önemli değil, ancak 10 veya 20 veya daha fazla geliştirici ekibinde bir projede ve aynı kod tabanı üzerinde çalıştığınızda, kod dağınık ve yönetilmesi zor olacaktır. İzlenecek herhangi bir yönerge yoktur. - -Kendi yönergelerinizi ve sözleşmelerinizi geliştirebilir veya iyi geliştirilmiş yönergeleri de uyarlayabilirsiniz. Bize en yaygın bilinen yönergeleri bildirin. -En yaygın JavaScript Stil Kılavuzları - -- Airbnb JavaScript Style Guide -- JavaScript Standard Style Guide -- Google JavaScript Style Guide - -#### Airbnb JavaScript Style Guide - -Airbnb, internetteki en popüler JavaScript stil kılavuzlarından birine sahiptir. JavaScript'in neredeyse her yönünü de kapsar ve birçok geliştirici ve şirket tarafından benimsenmiştir. [Airbnb stil rehberine](https://github.com/airbnb/javascript) göz atabilirsiniz. ben de denemenizi tavsiye ederim. Stillerinin kullanımı çok kolay ve anlaşılması kolaydır. - -#### Standard JavaScript Style Guide - -Bu kılavuz Airbnb kadar popüler değil ama bakmaya değer. [Stil kılavuzlarında](https://standardjs.com/) noktalı virgülü kaldırdılar. - -#### Google JavaScript Style Guide - -Google'ın yönergesi hakkında pek bir şey söylemiyorum ve kullanmadım, bunun yerine şu [link'e](https://google.github.io/styleguide/jsguide.html) bir göz atmanızı öneririm. - -### JavaScript Kodlama Kuralları - -Bu görevde ayrıca genel JavaScript kodlama yazım kurallarını ve kılavuzlarını kullandık. Kodlama kuralları, bir kişi, bir ekip veya bir şirket tarafından geliştirilen programlama için stil yönergeleridir. - -Kodlama kuralları aşağıdakilere yardımcı olur: - -- temiz kod yazmak -- kod okunabilirliğini geliştirmek -- kodun yeniden kullanılabilirliğini ve sürdürülebilirliğini geliştirmek için - -Kodlama kuralları şunları içerir: - -- Değişkenler için adlandırma ve bildirim kuralları -- Fonksiyonlar için adlandırma ve bildirim kuralları -- Boşluk, girinti ve yorumların kullanımına ilişkin kurallar -- Programlama uygulamaları ve ilkeleri - -#### 30DaysOfJavaScript'te kullanılan kurallar - -Bu meydan okumada normal JavaScript kuralını takip ediyoruz, ancak yazma tercihimi de ekledim. - -- Değişkenler ve fonksiyonlar için camelCase kullandık. -- Tüm değişken isimleri bir harfle başlar. -- Sabitler, diziler, nesneler ve işlevler için *const* kullanmayı seçtik. Çift alıntı yerine tek tırnak veya ters tik kullanmayı tercih ettik. Tek alıntı moda oluyor. -- Kodumuzdan noktalı virgülleri de kaldırdık ama bu kişisel tercih meselesidir. -- Aritmetik operatörler, atama operatörleri ve virgülden sonra boşluk -- Fonksiyon bildirimi yerine arrow function -- Fonksiyon bir satır ise, implicit return yerine explicit return -- Bir nesnenin son değerinin sonunda virgül yok -- Daha uzun versiyon yerine +=, -=, *= /=, **= bunu tercih ediyoruz -- console.log()'u kullandığımızda, konsolun nereden geldiğini belirlemek için bir etiket dizgisi ile yazdırmak iyidir. - -#### Değişkenler - -```js -let firstName = 'Asabeneh' -let lastName = 'Yetayeh' -let country = 'Finland' -let city = 'Helsinki' -const PI = Math.PI -const gravity = 9.81 -``` - -#### Arrays(Diziler) - -Dizi isimlerini çoğul yapmayı seçtik - -- names -- numbers -- countries -- languages -- skills -- fruits -- vegetables - -```js -// arrays -const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook'] -const numbers = [0, 3.14, 9.81, 37, 98.6, 100] -const countries = ['Finland', 'Denmark', 'Sweden', 'Norway', 'Iceland'] -const languages = ['Amharic', 'Arabic', 'English', 'French', 'Spanish'] -const skills = ['HTML', 'CSS', 'JavaScript', 'React', 'Python'] -const fruits = ['banana', 'orange', 'mango', 'lemon'] -const vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] -``` - -#### Fonksiyonlar - -Şimdiye kadar çok tanıdık fonksiyon declaration, expression fonksiyon, arrow fonksiyon ve anonymous fonksiyon sahipsiniz. Bu zorlukta, diğer fonksiyonlar yerine arrow fonksiyonunu kullanma eğilimindeyiz. Arrow fonksiyonu, diğer fonksiyonların yerine geçmez. Ayrıca arrow fonksiyon ve fonksiyon declaration tam olarak aynı değildir. Bu yüzden ne zaman kullanacağınızı ve ne zaman kullanmayacağınızı bilmelisiniz. Farkı diğer bölümlerde ayrıntılı olarak ele alacağım. Fonksiyon bir satır ise, implicit return yerine explicit return kullanacağız. - -```js -// bir kişinin tam adını döndüren fonksiyon -const printFullName = (firstName, lastName) => firstName + ' ' + lastName -// bir sayının karesini döndüren fonksiyon -const square = (n) => n * n -// rastgele hexa renkleri oluşturan fonksiyon -const hexaColor = () => { - const str = '0123456789abcdef' - let hexa = '#' - let index - for (let i = 0; i < 6; i++) { - index = Math.floor(Math.random() * str.length) - hexa += str[index] - } - return hexa -} -// tarih ve saati gösteren bir fonskiyon -const showDateTime = () => { - const now = new Date() - const year = now.getFullYear() - const month = now.getMonth() + 1 - const date = now.getDate() - let hours = now.getHours() - let minutes = now.getMinutes() - if (hours < 10) { - hours = '0' + hours - } - if (minutes < 10) { - minutes = '0' + minutes - } - const dateMonthYear = date + '.' + month + '.' + year - const time = hours + ':' + minutes - const fullTime = dateMonthYear + ' ' + time - return fullTime -} -``` - -`new Dat().toLocaleString()` geçerli tarih ve saati görüntülemek için de kullanılabilir. `toLocaleString()` yöntemleri farklı argümanlar alır. Bu [bağlantıdan](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString) tarih ve saat hakkında daha fazla bilgi edinebilirsiniz. - -#### Döngüler - -Bu zorluklarda birçok döngü türünü ele alıyoruz. Normal for döngüsü, while döngüsü, do while döngüsü, for of döngüsü, forEach döngüsü ve for in döngüsü. -Bunları nasıl kullandığımızı görelim: - -```js -for (let i = 0; i < n; i++){ - console.log() -} -// dizi değişkenlerini tanımlıyoruz -const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook'] -// normal for döngüsü kullanarak bir diziyi yineleme -let len = names.length; -for(let i = 0; i < len; i++){ - console.log(names[i].toUpperCase()) -} -// for of kullanarak bir diziyi yinelemek -for( const name of names) { - console.log(name.toUpperCase()) -} -// forEach kullanarak bir diziyi yineleme -names.forEach((name) => name.toUpperCase()) -const person = { - firstName: 'Asabeneh', - lastName: 'Yetayeh', - age: 250, - country: 'Finland', - city: 'Helsinki', - skills: ['HTML','CSS','JavaScript','React','Node','MongoDB','Python','D3.js'], - isMarried: true -} -for(const key in person) { - console.log(key) -} -``` - -#### Nesneler - -Nesne değişmezini *const* ile tanımlarız. - -```js -// nesne değişmezi tanımlama -const person = { - firstName: 'Asabeneh', - lastName: 'Yetayeh', - age: 250, - country: 'Finland', - city: 'Helsinki', - skills: ['HTML','CSS','JavaScript','TypeScript', 'React','Node','MongoDB','Python','D3.js'], - isMarried: true -} -// nesne anahtarları aracılığıyla yineleme -for(const key in person) { - console.log(key, person[key]) -} -``` - -#### Koşullar - - Önceki zorluklarda if, if else, if else if else, switch ve üçlü operatörleri bahsetmiştik. - - ```js - // syntax(sözdimi) -if (condition) { - // kodun bu kısmı doğru koşul için çalıştırılır -} else { - // kodun bu kısmı yanlış koşul için çalıştırılır -} - ``` - - ```js - // if else -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 - ``` - - ```js - // if else if else if else -let a = 0 -if (a > 0) { - console.log(`${a} is a positive number`) -} else if (a < 0) { - console.log(`${a} is a negative number`) -} else if (a == 0) { - console.log(`${a} is zero`) -} else { - console.log(`${a} is not a number`) -} - ``` - - ```js - // Daha fazla switch kullanımı -let dayUserInput = prompt('What day is today ?') -let 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.') -} - ``` - - ```js - // ternary (Üçlü) - let isRaining = true -isRaining - ? console.log('You need a rain coat.') - : console.log('No need for a rain coat.') - ``` - -#### Sınıflar - -Sınıfı büyük harfle başlayan CamelCase ile tanımlıyoruz - -```js -// syntax -class ClassName { - // code goes here -} -``` - -```js -// sınıfımızı oluşturuyoruz -class Person { - constructor(firstName, lastName) { - console.log(this) // buradan çıktı alıyoruz - this.firstName = firstName - this.lastName = lastName - } -} -``` - -Takip ettiğiniz stil kılavuzu ne olursa olsun tutarlı olun. Bazı programlama paradigmalarını ve tasarım modellerini takip edin. Unutmayın, kodunuzu belirli bir düzende veya şekilde yazmazsanız, kodunuzu okumak zor olacaktır. Bu nedenle, okunabilir kod yazarak kendiniz veya kodunuzu okuyacak biri için bir iyilik yapın. - -🌕 Düzenlisin. Artık temiz kod yazmayı biliyorsun, böylece İngilizce bilen herkes kodunuzu anlayabilir. Her zaman ilerliyorsunuz ve mükemmelliğe giden yolda 20 adım öndesiniz. - -🎉 TEBRİKLER ! 🎉 - -[<< Gün 19](../19_Day_Closures/19_day_closures.md) | [Gün 21 >>](../21_Day_DOM/21_day_dom.md) \ No newline at end of file diff --git a/Turkish/readMe.md b/Turkish/readMe.md deleted file mode 100644 index eaeea93..0000000 --- a/Turkish/readMe.md +++ /dev/null @@ -1,670 +0,0 @@ -# 30 Days Of JavaScript - -| # Day | Konular | -| ----- | :------------------------------------------------------------------------------------------------------------------------------------------------: | -| 01 | [Giriş](./readMe.md) | -| 02 | [Veri Tipleri](./02_Day_Data_types/02_day_data_types.md) | -| 03 | [Boolean, Operatörler, Tarih](./03_Day_Booleans_operators_date/03_booleans_operators_date.md) | -| 04 | [Koşullar](./04_Day_Conditionals/04_day_conditionals.md) | -| 05 | [Diziler](./05_Day_Arrays/05_day_arrays.md) | -| 06 | [Döngüler](./06_Day_Loops_Donguler/06_day_loops.md) | -| 07 | [Fonksiyonlar](./07_Day_Functions/07_day_functions.md) | -| 08 | [Nesneler](./08_Day_Objects/08_day_objects.md) | -| 09 | [Yüksek Dereceli Fonksiyonlar](./09_Day_Higher_order_functions/09_day_higher_order_functions.md) | -| 10 | [Setler Ve Haritalar](./10_Day_Sets_and_Maps/10_day_Sets_and_Maps.md) | -| 11 | [Yıkıcılar Ve Yapıcılar](./11_Day_Destructuring_and_spreading/11_day_destructuring_and_spreading.md) | -| 12 | [Düzenli İfadeler](./12_Day_Regular_expressions/12_day_regular_expressions.md) | -| 13 | [Consol Nesne Metodları](./13_Day_Console_object_methods/13_day_console_object_methods.md) | -| 14 | [Hata Yönetimi](./14_Day_Error_handling/14_day_error_handling.md) | -| 15 | [Sınıflar](./15_Day_Classes/15_day_classes.md) | -| 16 | [JSON](./16_Day_JSON/16_day_json.md) | -| 17 | [Web Depoları](./17_Day_Web_storages/17_day_web_storages.md) | -| 18 | [Promise'ler](./18_Day_Promises/18_day_promises.md) | -| 19 | [Closure](./19_Day_Closures/19_day_closures.md) | -| 20 | [Temiz Kod Yazımı](./20_Day_Writing_clean_codes/20_day_writing_clean_codes.md) | -| 21 | [DOM](./21_Day_DOM/21_day_dom.md) | -| 22 | [Dom Manipülasyonu](./22_Day_Manipulating_DOM_object/22_day_manipulating_DOM_object.md) | -| 23 | [Olay Tetikleyiciler](./23_Day_Event_listeners/23_day_event_listeners.md) | -| 24 | [Mini Proje: Güneş Sistemi](./24_Day_Project_solar_system/24_day_project_solar_system.md) | -| 25 | [Mini Proje: Dünya Ülkeleri Veri Görselleştirme 1](./25_Day_World_countries_data_visualization_1/25_day_world_countries_data_visualization_1.md) | -| 26 | [Mini Project: Dünya Ülkeleri Veri Görselleştirme 2](./26_Day_World_countries_data_visualization_2/26_day_world_countries_data_visualization_2.md) | -| 27 | [Mini Proje: Portföy](./27_Day_Mini_project_portfolio/27_day_mini_project_portfolio.md) | -| 28 | [Mini Proje: Liderler Sıralaması](./28_Day_Mini_project_leaderboard/28_day_mini_project_leaderboard.md) | -| 29 | [Mini Proje: Animasyon Karakterleri](./29_Day_Mini_project_animating_characters/29_day_mini_project_animating_characters.md) | -| 30 | [Son Proje](./30_Day_Mini_project_final/30_day_mini_project_final.md) | - -🧡🧡🧡 MUTLU KODLAMALAR 🧡🧡🧡 - -
- Yazarı daha fazla eğitim materyalleri oluşturabilmesi için destekleyebilirsiniz.
-Paypal Logo -
- -
-

30 Günde JavaScript: Giriş

- - - - - Twitter Follow - - -Yazar: -Asabeneh Yetayeh
- Ocak, 2020 -
- -
- -🇬🇧 [English](../readMe.md) -🇪🇸 [Spanish](../Spanish/readme.md) -🇷🇺 [Russian](../RU/README.md) -🇦🇿 [Azerbaijan](../Azerbaijani/readMe.md) -🇰🇷 [Korean](../Korea/README.md) -🇻🇳 [Vietnamese](../Vietnamese/README.md) -🇵🇱 [Polish](../Polish/readMe.md) - -
- -
- - -[2. Gün >>](./02_Day_Data_types/02_day_data_types.md) - -![30 Günde JavaScript](../images/day_1_1.png) - -- [30 Günde JavaScript](#30-günde-javascript) -- [📔 1. Gün](#-1-gün) - - [Giriş](#giriş) - - [Gereksinimler](#gereksinimler) - - [Kurulum](#kurulum) - - [Node.js Kurulumu](#nodejs-kurulumu) - - [Tarayıcı](#tarayıcı) - - [Google Chrome Kurulumu](#google-chrome-kurulumu) - - [Google Chrome Konsolu Açmak](#google-chrome-konsolu-açmak) - - [Tarayıcı Konsolunda Kod Yazmak](#tarayıcı-konsolunda-kod-yazmak) - - [Console.log](#consolelog) - - [Çoklu Değişkenler ile Console.log ](#çoklu-değişkenler-ile-consolelog) - - [Yorumlar](#yorumlar) - - [Sözdizimi](#sözdizimi) - - [Aritmetik İşlemler](#aritmetik-i̇şlemler) - - [Kod Editörü](#kod-editörü) - - [Visual Studio Code Kurulumu](#visual-studio-code-Kurulumu) - - [Visual Studio Code Kullanımı](#visual-studio-code-kullanımı) - - [Bir Web Sayfasında JavaScript Kodları Oluşturma](#bir-web-sayfasında-javascript-kodları-oluşturma) - - [Satır İçi Oluşturma](#satır-İçi-oluşturma) - - [Sayfa İçi Oluşturma](#dahili-oluşturma) - - [Dış Dosyadan Oluşturma](#harici-oluşturma) - - [Birden Fazla Dış Dosyadan Oluşturma](#çoklu-harici-oluşturma) - - [Veri Türlerine Giriş](#veri-türlerine-giriş) - - [Sayılar](#sayılar) - - [String](#string) - - [Boolean](#boolean) - - [Tanımsız](#tanımsız) - - [Null(Boş)](#nullboş) - - [Veri Türlerini Konrol Etme](#veri-türlerini-kontrol-etme) - - [Tekrardan Yorumlar](#tekrardan-yorumlar) - - [Değişkenler](#değişkenler) -- [💻 1. Gün: Egzersizler](#-1-gün-egzersizler) - -# 📔 1. Gün - -## Giriş - -30 Günlük JavaScript programlama kursuna katılmaya karar verdiğiniz için **tebrikler**. Bu kursta, bir JavaScript programcısı olmak için ihtiyacınız olan her şeyi ve genel olarak tüm programlama kavramınlarını öğreneceksiniz. Eğitimin sonunda 30 Günlük JavaScript programlama kursu tamamlama sertifikası alacaksınız. Yardıma ihtiyacınız olması veya başkalarına yardım etmek istemeniz durumunda [telegram grubuna](https://t.me/ThirtyDaysOfJavaScript) katılabilirsiniz. - -**30GündeJavaScript** eğitimi, hem yeni başlayanlar için hem de uzman JavaScript geliştiricileri için rehber niteliği taşımaktadır. JavaScript'e Hoş Geldiniz. JavaScript web'in dilidir. JavaScript'i kullanmaktan ve öğretmekten zevk alıyorum, umuyorum siz de öğrenirken ve kullanırken zevk alacaksınız. - -Bu adım adım JavaScript kursunda, insanlık tarihindeki en popüler programlama dili olan JavaScript'i öğreneceksininiz. -JavaScript **_web sitelerine interaktiflik katmak, mobil-masaüstü-oyun uygulamaları geliştirmek_** için, hatta günümüzde JavaScript ile **_makina öğrenimi_** ve **_Yapay Zeka_** uygulamaları da geliştirebilirsiniz. -**_JavaScript (JS)_** son yıllarda popülaritesi artırarak altı yıl üst üste lider ve Github'da en çok kullanılan programlama dili olmuştur. - -## Gereksinimler - -Bu kursu takip etmek için önceden programlama bilgisine sahip olmanıza gerek yoktur. Sadece ihtiyacınız olanlar şunlardır: - -1. Motivasyon -2. Bir bilgisayar -3. İnternet -4. Bir tarayıcı -5. Bir kod editörü - -## Kurulum - -Bir geliştirici olmak için motivasyonunuz ve güçlü bir arzunuz olduğuna inanıyorum. Eğer bilgisayar ve İnternete sahipseniz, artık başlamak için her şeye sahipsiniz. - -### Node.js Kurulumu - -Şu aşamada belki Node.js'e ihtiyacınız olmayabilir, fakat ilerisi için ihtiyacınız olacaktır. Dilerseniz şuan [node.js](https://nodejs.org/en/) yükleyebilirsiniz. - -![Node download](../images/download_node.png) - -Görseldeki web sitesinden son sürümü indirin ve çift tıklayarak bilgisayarınıza yükleyin. - -![Install node](../images/install_node.png) - -Node.js'i başarılı bir şekilde yüklediğinizi kontrol etmek için komut satırı(cmd) ya da terminal ekranınızda aşağıdaki komutu kullanabilirsiniz. - -```sh -asabeneh $ node -v -v12.14.0 -``` - -Bu eğitimi hazırlarken Node.js'in 12.14.0 sürümünü kullanıyordum. Muhtemelen sizin kullanacağınız sürüm çok daha güncel olacaktır. - -### Tarayıcı - -Kullanabileceğiniz çok sayıda tarayıcı bulunmaktadır. Ancak, kesinlikle Google Chrome tarayıcısını kullanmanızı öneriyorum. - -#### Google Chrome Kurulumu - -[Google Chrome](https://www.google.com/chrome/) yükleyin. Tarayıcı konsoluna küçük JavaScript kodları yazabiliriz, ancak uygulamaları geliştirmek için tarayıcı konsolunu kullanmayız. - -![Google Chrome](../images/google_chrome.png) - -#### Google Chrome Konsolu Açmak - -Tarayıcının sağ üst köşesindeki üç noktaya tıkladıktan sonra, _Diğer Araçlar -> Geliştirici Araçları_ öğesine ulaşarak veya F12 kısayolu kullanarak geliştirici araçlarını açabilirsiniz. Ben kısayolu kullanmayı tercih ediyorum. - -![Opening chrome](../images/opening_developer_tool.png) - -Geliştiri araçları kısmındaki consol sekmesine erişmek için aşağıdaki kısayolu kullanabilirsiniz. - -```sh -Mac -Command+Option+J - -Windows/Linux: -Ctl+Shift+J -``` - -![Opening console](../images/opening_chrome_console_shortcut.png) - -Google Chrome konsolunu açtıktan sonra görseldeki sekmeleri keşfetmeye çalışın. Zamanımızın çoğunu Konsolda geçireceğiz. Konsol, JavaScript kodlarımızı çalıştırabileceğimiz alandır. Google Console V8 motoru, JavaScript kodumuzu makine koduna Dönüştürerek makine ile iletişim kurmamızı sağlar. Google Chrome konsoluna bir JavaScript kodu yazalım: - -![write code on console](../images/js_code_on_chrome_console.png) - -#### Tarayıcı Konsolunda Kod Yazmak - -Google konsoluna veya herhangi bir tarayıcı konsoluna, herhangi bir JavaScript kodu yazabiliriz. Fakat, bu eğitimde yalnızca Google Chrome konsoluna odaklanacağız. Aşağıdaki kısa yolları kullanarak konsolunuzu açın: - -```sh -Mac -Command+Option+I - -Windows: -Ctl+Shift+I -``` - -##### Console.log - -İlk JavaScript kodumuzu yazmak için, yerleşik bir fonksiyon olan **console.log()** fonksiyonunu kullandık. Çıktı ekranına `'Hello, World!'` cümlesini console.log() fonksiyonu kullanarak yazırdık. - -```js -console.log("Hello, World!"); -``` - -##### Çoklu Değişkenler ile Console.log - -**console.log()** fonksiyonu virgülle ayrılmış birden fazla parametre alabilir. Kullanımı şu şekildedir:**`console.log(param1, param2, param3)`** - -![console log multiple arguments](../images/console_log_multipl_arguments.png) - -```js -console.log("Hello", "World", "!"); -console.log("HAPPY", "NEW", "YEAR", 2020); -console.log("Welcome", "to", 30, "Days", "Of", "JavaScript"); -``` - -Yukarıdaki kod parçacığından da görebileceğiniz gibi, _`console.log()`_ birden çok değişken veri türü alabilir. - -Tebrikler! İlk JavaScript kodunuzu _`console.log()`_ kullanarak yazdınız. - -##### Yorumlar - -Kodumuza yorum ekleyebiliriz. Yorumlar, kodu daha okunabilir hale getirmek ve kodumuzda açıklamalar bırakmak için çok önemlidir. JavaScript, kodumuzun yorum bölümünü çalıştırmaz. JavaScript'te `//` ile başlayan satırlar ve `/*...*/` işaretler arasında yer alan herhangi metinler yorum olarak algılanır. - -**Örnek: Tek Satırlı Açıklama** - -```js -// Bu ilk yorum -// Bu ikinci yorum -// Ben tek satırlık bir yorumum -``` - -**Örnek: Çok Satırlı Açıklama** - -```js -/* - Bu çok satırlı bir yorumdur - Çok satırlı yorumlar birden çok satır alabilir - JavaScript web'in dilidir - */ -``` - -##### Sözdizimi - -Programlama dilleri insan dillerine benzer. Türkçe veya diğer birçok dil, anlamlı bir mesaj iletmek için kelimeler, deyimler, cümleler, birleşik cümleler ve daha fazlasını kullanır. Sözdiziminin Türkçedeki anlamı, bir dilde cümleler oluşturmak için sözcüklerin dilbilgisi kurallarına göre dizilişi, sıralanışıdır. Sözdiziminin teknik tanımına baktığımızda, bir bilgisayar dilindeki ifadelerin yapısıdır. Programlama dillerinin kendilerine özgü sözdizimleri vardır. JavaScript bir programlama dilidir ve diğer programlama dilleri gibi kendi sözdizimine sahiptir. Kodlarımızı JavaScript'in anladığı sözdizimi kuralları çerçevesinde yazmaz isek, farklı türde hatalar ortaya çıkar. Farklı JavaScript hata türlerini daha sonra keşfedeceğiz ve açıklayacağız. Şimdilik sözdizimi hatalarını basitçe görelim. - -![Error](../images/raising_syntax_error.png) - -Görselde görülen şekilde kasıtlı olarak hatalar yaptım. Hatalar sonucunda konsol bize sözdizimi hataları verdi. Aslında, uyarı metinleri bilgilendiricidir. Ne tür bir hata yapıldığını bildiririrler. Bu hata mesajlarını okuyarak yapmış olduğumuz sözdizim hatasını düzeltebilir ve sorunları çözebiliriz. Bir programdaki hataları tanımlama ve kaldırma işlemine hata ayıklama denir(debugging). Hataları düzeltelim: - -```js -console.log("Hello, World!"); -console.log("Hello, World!"); -``` - -Şimdiye kadar,_`console.log()`_ kullanarak metnin nasıl görüntüleneceğini gördük. Eğer _`console.log()`_ kullanarak metin yazdırmak istiyor isek, metni tek tırnak, çift tırnak veya ters tırnak işaretleri içiresine almamız gerekir. -**Örnek:** - -```js -console.log("Hello, World!"); -console.log("Hello, World!"); -console.log(`Hello, World!`); -``` - -#### Aritmetik İşlemler - -Şimdi, Google Chrome konsolunda sayı veri türleri için _`console.log()`_ kullanarak JavaScript kodları yazma konusunda daha fazla pratik yapalım. -JavaScript kullanarak matematiksel hesaplamalar da yapabiliriz. Aşağıdaki basit hesaplamaları yapalım. -Konsolda **_console.log()_** işlevi olmadan doğrudan işlemler yaptırabiliriz. Ancak, buna ilişkin kullanımlar, bu eğitimde açıklanmamıştır, çünkü eğitimimiz boyuncu biz bu fonksiyonları hep bir kod editöründe kullanacağız. Dilerseniz konsola doğrudan sayıları yazarak da işlemleri gerçekleştirebilirsiniz. - -![Arithmetic](../images/arithmetic.png) - -```js -console.log(2 + 3); // Toplama -console.log(3 - 2); // Çıkarma -console.log(2 * 3); // Çarpma -console.log(3 / 2); // Bölme -console.log(3 % 2); // Mod Alma -console.log(3 ** 2); // ;Üs Alma 3 ** 2 == 3 * 3 -``` - -### Kod Editörü - -Kodlarımızı tarayıcı konsoluna yazabiliriz, ancak daha büyük projeler için böyle bir şey yapmamız mümkün olamaz. Gerçek bir çalışma ortamında, geliştiriciler kodlarını yazmak için farklı kod düzenleyicileri kullanırlar. Bu 30günlükJavaScript eğitiminde Visual Studio Code editörünü kullanacağız. - -#### Visual Studio Code Kurulumu - -Çok popüler ve açık kaynak kodlu olan Visual Studio Code(Metin Düzenleyicisi)'u tavsiye ederim. [download Visual Studio Code](https://code.visualstudio.com/), Fakat başka editörler kullanıyorsanız, kullanıdığınız editör ile devam edebilirsin. - -![Vscode](../images/vscode.png) - -Visual Studio Code yüklediyseniz, kullanmaya başlayalım. - -#### Visual Studio Code Kullanımı - -Visual Studio Kodunu açtığınızda, görseldeki gibi bir arayüz açılacaktır. Görsellerde belrtilen simgelerle uğraşarak özellikleri hakkında deneyim edinebilirsiniz. - -![Vscode ui](../images/vscode_ui.png) - -![Vscode add project](../images/adding_project_to_vscode.png) - -![Vscode open project](../images/opening_project_on_vscode.png) - -![script file](../images/scripts_on_vscode.png) - -![Installing Live Server](../images/vsc_live_server.png) - -![running script](../images/running_script.png) - -![coding running](../images/launched_on_new_tab.png) - -## Bir Web Sayfasında JavaScript Kodları Oluşturma - -JavaScript bir web sayfasına üç farklı şekilde eklenebilir: - -- **_Satır İçi oluşturma_** -- **_Dahili oluşturma_** -- **_Harici oluşturma_** -- **_Çoklu Harici oluşturma_** - -Aşağıdaki bölümlerde web sayfanıza JavaScript kodu eklemenin farklı yolları gösterilmektedir. - -### Satır İçi Oluşturma - -Masaüstünüzde veya istediğiniz herhangi bir yerde, bir proje klasörü oluşturun. Klasör adına 30GundeJS adını verebilirsiniz, klasör içerisinde _`index.html`_ dosyası oluşturun. Sonrasında aşağıdaki kodu yapıştırın ve bu _.html_ uzantılı dosyayı [Chrome](https://www.google.com/chrome/) gibi bir tarayıcıda açın. - -```html - - - - 30DaysOfScript: Satır İçi script - - - - - -``` - -Şimdi, ilk satır içi script dosyanızı yazdınız. JavaScript yerleşik fonksiyon olan _`alert ()`_ kullanarak,bir açılır uyarı mesajı oluşturabiliriz - -### Dahili Oluşturma - -Dahili scripti _`head`_ veya _`body`_ etiketleri arasına yazılabilir, ancak bunun HTML belgesinin body kısmına yazılması tercih edilir. Öncelikle sayfanın _`head`_ kısmına yazalım. - -```html - - - - 30GündeScript:Dahili Script - - - - -``` - -Çoğu zaman dahili bir scripti bu şekilde yazarız. JavaScript kodunun, html sayfamızın _`body`_ kısmına yazılması en çok tercih edilen seçenektir. _`Console.log()`_ çıktısını görmek için tarayıcınızın konsolunu açınız. - -```html - - - - 30GündeScript:Dahili Script - - - - - - -``` - -_`console.log()`_ çıktısını görmek için tarayıcı konsolunu açın. - -![js code from vscode](../images/js_code_vscode.png) - -### Harici Oluşturma - -Dahili scripte benzer şekilde, harici sicript bağlantısı da head etiketleri arasında veya body etiketleri arasında olabilir, ancak body etiketleri arasına eklenmesi tercih edilir. -Öncelikle '.js' uzantılı harici bir JavaScript dosyası oluşturmalıyız. '.js' uzantılı tüm dosyalar JavaScript dosyalarıdır. Proje klasörü içersine 'introdiction.js' adında bir dosya oluşturun ve içine aşağıdaki kodu yazın. Ardından bu oluşturduğunuz 'introdiction.js' dosyanızı, html sayfanızdaki head veya body etiketinin arasına ekleyerek, 'introdiction.js' adlı JavaScript dosyamızı tanıtalım. - -```js -console.log("30GündeJavaScript'e hoş geldiniz!"); -``` - -Harici script dosyasının _head_ etiketi arasında tanımlama: - -```html - - - - 30GündeJavaScript:Harici script - - - - -``` - -Harici script dosyasının _body_ etiketi arasında tanımlama: - -```html - - - - 30GündeJavaScript:Harici script - - - - - - - -``` - -_`console.log()`_ çıktısını görmek için tarayıcı konsolunu açın. - -### Çoklu Harici Oluşturma - -Ayrıca birden çok harici JavaScript dosyasını da bir web sayfası içerisine bağlayabiliriz. -Oluşturduğumuz proje klasörü içerisine yeniden `helloworld.js` isimli bir JavaScript dosyası oluşturalım. - -```js -console.log("Hello, World!"); -``` - -```html - - - - Çoklu Harici Scriptler - - - - - - -``` - -_ana.js dosyanız, diğer tüm .js dosyalarınızın altında olmalıdır_. Derleme yapılırken satırlar yukarıdan aşağıya okunduğu için ana JavaScript dosyanınız en son okunması önem taşımaktadır. - -![Multiple Script](../images/multiple_script.png) - -## Veri Türlerine Giriş - -JavaScript'te ve diğer programlama dillerinde, farklı tiplerde veri türleri vardır. JavaScript ilkel veri tipleri şunlardır: _String(metin), Number(sayı), Boolean(T-F), undefined(tanımsız), NulL(boş)_, ve _Symbol(sembol)_. - -### Sayılar - -- Tam sayılar: Integer (sıfır dahil negatif ve pozitif) - Örnek: - ... -3, -2, -1, 0, 1, 2, 3 ... -- Ondalıklı sayılar: (Float / Decimal) - Example - ... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ... - -### String - -Tek tırnak, çift tırnak veya ters tırnak(backtick) arasında yer alan, bir veya daha fazla karakterden oluşan metinsel değerlerdir.(Her tür karakterleri içerisinde barındırabilir.) - -**Örnek:** - -```js -"a"; -"Asabeneh"; -'YusufAgca'; -"Turkey-ATATÜRK"; -'JavaScript güzel bir programlama dilidir'; -"Öğrenmeyi seviyorum"; -`Unutma, ayrıca bir ters tırnak kullanarak bir dize de oluşturabiliriz`; -("string veri türü, bir karakter kadar küçük, sayfalar kadar büyük olabilir."); -``` - -### Boolean - -Boolean veri türü, yalnızca True(doğru) veya False(yanlış) bir değer alır-dönderir. - -**Örnek:** - -```js -true; // ışık yanıyorsa, değer doğrudur -false; // ışık kapalıysa, değer yanlıştır -``` - -### Tanımsız - -JavaScript'te, bir değişkene bir değer atamaz isek, değeri undefined olarak alır. Buna ek olarak, bir fonksiyon hiçbir şey döndürmüyorsa, döndereceği tanım 'undefined' tır. - -```js -let ismim; -console.log(ismim); // undefined, çünkü henüz değişkene bir değer atanmamış. -``` - -### Null(Boş) - -JavaScript'te 'null' boş bir değer anlamına gelir. - -```js -let bosDeger = null; -``` - -## Veri Türlerini Kontrol Etme - -Bir değişkenin veri türünü kontrol etmek için **typeof** operatörünü kullanırız. Aşağıdaki örneğe bakın. - -```js -console.log(typeof "Asabeneh"); // string -console.log(typeof 5); // number -console.log(typeof true); // boolean -console.log(typeof null); // object type -console.log(typeof undefined); // undefined -``` - -## Tekrardan Yorumlar - -JavaScript'te yorum yapmanın diğer programlama dillerine benzer olduğunu unutmayın. Kodunuzu daha okunabilir hale getirmek için yorumlar önemlidir. -Yorum yapmanın iki yolu vardır: - -- _Tek satırlı yorum_ -- _Çok satırlı yorum_ - -```js -// Bu satırda istediğiniz yorumu bırakabilirsiniz. -// Bu fonksiyonun amacı sayıları hesaplar. -// İlerde kodunuzu rahat anlayabilmek için yorumlar bırakmaya özen gösterin. -``` - -Çok satırlı yorum: - -```js -/* - let konum = 'İstabul'; - let age = "34"; - let evliMi = true; - Bu kısım çok satırlı yorum bloğudur. -*/ -``` - -## Değişkenler - -Değişkenlere veri _kapsayıcılar_ diyebiliriz. Unutmayınız ki değişkenler, verileri belleklerde(_Ram_) saklar. Bir değişken atandığında belleklerde kendisi için yer ayrılır. Bir değişkene bir değer(veri) atandığında, bellek alanı bu verilerle doldurulur. Değişken tanımlamak için, _var_, _let_, veya _const_ Anahtar kelimelerini(keywords) kullanırız. - -Değişken değerinin kodumuzun farklı yerlerinde değiştirilmesi gerekiyorsa, _let_ kullanırız. Eğer değişken verisi hiçbir yerde değişmeyecek ise bu durumda _const_ kullanırız. Örneğin, Pi sayısı, ülke adları veya yerçekimi ivmesi gibi değişmeyen, sabit değerler için _const_ kullanırız. Bu eğitimde _var_ kullanmayacağız ve kullanmanızı tavsiye etmiyorum. Çok fazla sızıntısı olduğundan dolayı _var_ değişken tanımlayıcısını kullanmanız hatalara sebep olacaktır. Var, let ve const hakkında diğer bölümlerde(Scope) ayrıntılı olarak konuşacağız. Şimdilik, yukarıdaki açıklama işimizi görecektir. - -Geçerli bir JavaScript değişken adı aşağıdaki kurallara uymalıdır: - -- JavaScript değişken adı bir sayı ile başlamamalıdır. -- JavaScript değişken adı, dolar işareti ve alt çizgi dışında özel karakterlere izin vermez.(Türkçe karakterlere özellike dikkat ediniz.) -- JavaScript değişken adı, camelCase kuralına uymalı. -- JavaScript değişken adı sözcükler arasında boşluk olmamalıdır. - -Aşağıda geçerli JavaScript değişkenlerine örnekler verilmiştir. - -```js -ad; -soyAd; -ulke; -sehir; -anneAdi; -age; -evliMi; - -soy_ad; -evli_mi; -anne_adi; - -sayi1; -sayi_1; -_sayi_1; -$sayi1; -yil2020; -yil_2020; -``` - -Listenin ilk bölümünde belirtilen değişken isimleri JavaScript'te camelCase bildirim kuralına uyularak yazılmıştır. Bu eğitimde, camelCase değişken adı yazım kurallarını uygulayacağız. - -Geçersiz değişken adlarına örnek: - -```js - first-name - 1_num - num_#_1 -``` - -Şimdi değişkenleri farklı veri tipleriyle birlikte tanımlayalım. Bir değişken tanımlamak için değişken adından önce _let_ veya _const_ anahtar kelimelerini kullanmamız gerekir. Değişken adının ardından eşittir işareti (atama operatörü) ve bir değer (atanmış veri) yazarız. - -```js -// Sözdizimi -let degiskenAdi = degeri; -``` - -Değişkenin adı, farklı değer verilerini depolayabilir. Ayrıntılı örnekler için aşağıya bakın. - -**Değişken tanımlama örnekleri** - -```js -// Farklı veri türlerinin, farklı değişkenlerini tanımlama -let ad = "Yusuf"; // bir kişinin adı -let soyAd = 'Agca'; // bir kişinni soyadı -let ulke = "Türkiye"; // ülke -let sehir = "Ankara"; // başkent -let yas = 27; // yaş -let instagram = "@yusuffagcaa" // instagram adresi -let evliMi = false; - -console.log(ad, soyAd, ulke, sehir, yas, instagram, evliMi); -``` - -```sh -Yusuf Agca Türkiye İstanbul 27 @yusuffagcaa false -``` - -```js -// Değişkenlere sayı değerleri tanımlama -let yas = 100; // yas -const yerCekim = 9.81; // m/s2 cinsinden yer çekimi değeri -const kaynamaNoktasi = 100; // °C cinsinden suyun kaynama noktası -const PI = 3.14; // geometrik sabit -console.log(yerCekim, kaynamaNoktasi, PI); -``` - -```sh -9.81 100 3.14 -``` - -```js -// Birden fazla değişkenleri virgül ile ayırarak tek satırda tanımlayabiliriz. Ancak ayrı satırlarda tanımlamak, kodu daha okunabilir kıldığı için tavsiye ederim. -let isim = "YunusKaraman", - is = "Lokmacı", - konum = "Bagcılar"; -console.log(isim, is, konum); -``` - -```sh -YunusKaraman Lokmacı Bagcılar -``` - -01-Day klasörü içindeki _index.html_ dosyasını tarayıcınızda açtığınızda, şu sonucu alıyor olacaksınız: - -![Day one](../images/day_1.png) - -🌕 Harikasınız! 1. gün eğitimini tamamladınız ve mükemmel olma yolundasınız. Şimdi beyniniz ve kasınız için bazı egzersizler yapın. - -# 💻 1. Gün: Egzersizler - -1. _"Yorumlar kodu okunabilir hale getirmeye yardımcı olur"_ yazan tek satırlı bir yorum yazın -2. _"30GundeJavaScript eğitimine hoş geldiniz"_ yazan başka bir yorum satırı oluşturun -3. _"Yorumlar kodu okunabilir, yeniden kullanımı kolay ve bilgilendirici bir hale getirir."_ yazılı, birden çok satıra yayılmış çok satırlı bir yorum yazın - -4. Bir degisken.js isimli dosya oluşturun ve bu _.js_ dosyasında string, boolean, undefined ve null veri türlerinde değişkenler oluşturun -5. Bir veriturleri.js isimli dosya oluşturun farklı veri türlerindeki verileri kontrol etmek için JavaScript **_typeof_** operatörünü kullanın. -6. Herhangi bir değer ataması yapmadan dört adet değişken yazın -7. Oluşturduğunuz değişkenlere değer ataması yapın -8. Adınızı, soyadınızı, medeni durumunuzu, ülkenizi ve yaşınızı birden çok satırda olacak şekilde saklamak için değişkenleri ve değerlerini oluşturun -9. Adınızı, soyadınızı, medeni durumunuzu, ülkenizi ve yaşınızı tek bir satırda olacak şekilde saklamak için değişkenleri ve değerlerini oluşturun -10. _benimYasim_ ve _seninYasin_ adlı iki değişken oluşturun ve bunlara aşağıdaki değerleri atayın. Ardından bunları tarayıcının konsolunda çalıştırın - -```sh -Ben 25 Yaşındayım. -Sen 30 Yaşındasın. -``` - -🎉 TEBRİKLER ! 🎉 - -[2. Gün >>](./02_Day_Data_types/02_day_data_types.md) diff --git a/Vietnamese/02_Day_Data_types/02_day_data_types.md b/Vietnamese/02_Day_Data_types/02_day_data_types.md deleted file mode 100644 index 64b5fea..0000000 --- a/Vietnamese/02_Day_Data_types/02_day_data_types.md +++ /dev/null @@ -1,979 +0,0 @@ -
-

Học JavaScript trong 30 ngày: Kiểu dữ liệu

- - - - - Twitter Follow - - - Tác giả: - Asabeneh Yetayeh
- Tháng 1, 2020 -
-
- - -[<< Ngày 1](../README.md) | [Ngày 3 >>](../03_Day_Booleans_operators_date/03_booleans_operators_date.md) - -![Ngày thứ hai học JavaScript](../../images/banners/day_1_2.png) - -- [📔 Ngày 2](#-day-2) - - [Kiểu dữ liệu](#data-types) - - [Kiểu dữ liệu nguyên thuỷ](#primitive-data-types) - - [Kiểu dữ liệu không nguyên thủy](#non-primitive-data-types) - - [Số](#numbers) - - [Khai báo kiểu dữ liệu Number](#declaring-number-data-types) - - [Đối tượng math](#math-object) - - [Tạo số ngẫu nhiên](#random-number-generator) - - [Chuỗi](#strings) - - [Nối chuỗi](#string-concatenation) - - [Nối chuỗi bằng toán tử cộng](#concatenating-using-addition-operator) - - [Chuỗi dài](#long-literal-strings) - - [Chuỗi thoát trong Strings](#escape-sequences-in-strings) - - [Template Literals (Template Strings)](#template-literals-template-strings) - - [Phương thức chuỗi](#string-methods) - - [Xác định kiểu dữ liệu và truyền](#checking-data-types-and-casting) - - [Kiểm tra kiểu dữ liệu](#checking-data-types) - - [Thay đổi kiểu dữ liệu (Truyền)](#changing-data-type-casting) - - [String thành Int](#string-to-int) - - [String thành Float](#string-to-float) - - [Float thành Int](#float-to-int) - - [💻 Day 2: Bài tập](#-day-2-exercises) - - [Bài tập: Cấp độ 1](#exercise-level-1) - - [Bài tập: Cấp độ 2](#exercise-level-2) - - [Bài tập: Cấp độ 3](#exercises-level-3) - -# 📔 Ngày 2 - -## Kiểu dữ liệu - -Trong phần trước, chúng ta đã đề cập một chút về kiểu dữ liệu. Dữ liệu hoặc giá trị có kiểu dữ liệu. Kiểu dữ liệu mô tả các đặc điểm của dữ liệu. Các kiểu dữ liệu có thể được chia thành hai: - -1. Kiểu dữ liệu nguyên thủy -2. Kiểu dữ liệu không nguyên thủy (Tham chiếu đối tượng) - -### Kiểu dữ liệu nguyên thuỷ - -Các kiểu dữ liệu nguyên thuỷ trong JavaScript bao gồm: - - 1. Số - Số thực, số nguyên - 2. Chuỗi - Bất kỳ ký tự nào nằm trong dấu nháy đơn nháy kép, back-tick - 3. Boolean - `true` hoặc `false` - 4. Null - rỗng hoặc không có giá trị - 5. Undefined - khai báo không gán giá trị - -Các kiểu dữ liệu không nguyên thủy trong JavaScript bao gồm: - -1. Objects -2. Functions -3. Arrays - -Bây giờ, chúng ta hãy xem các kiểu dữ liệu nguyên thủy và không nguyên thủy chính xác nghĩa là gì. -Kiểu dữ liệu *nguyên thủy* là kiểu dữ liệu bất biến (không thể sửa đổi). Khi một kiểu dữ liệu nguyên thủy được tạo, chúng ta không thể sửa đổi nó. - -**Example:** - -```js -let word = 'JavaScript' -``` - -Nếu chúng tôi cố gắng sửa đổi chuỗi được lưu trữ trong biến *word*, JavaScript sẽ phát sinh lỗi. Bất kỳ kiểu dữ liệu nào dưới dấu ngoặc kép, dấu ngoặc kép hoặc dấu ngoặc kép đều là kiểu dữ liệu chuỗi. - -```js -word[0] = 'Y' -``` - -Biểu thức này không thay đổi chuỗi được lưu trữ trong biến *word*. Vì vậy, chúng ta có thể nói rằng các chuỗi không thể sửa đổi hay nói cách khác là bất biến. -Các kiểu dữ liệu ban đầu được so sánh bằng các giá trị của nó. Hãy để chúng tôi so sánh các giá trị dữ liệu khác nhau. Xem ví dụ bên dưới: - -```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 -``` - -### Kiểu dữ liệu không nguyên thuỷ - -Các kiểu dữ liệu *không nguyên thủy* có thể sửa đổi hoặc thay đổi được. Chúng ta có thể sửa đổi giá trị của các kiểu dữ liệu không nguyên thủy sau khi nó được tạo. -Hãy để chúng tôi xem bằng cách tạo một mảng. Mảng là một danh sách các giá trị dữ liệu trong một dấu ngoặc vuông. Mảng có thể chứa các kiểu dữ liệu giống nhau hoặc khác nhau. Giá trị mảng được tham chiếu bởi chỉ mục của chúng. Trong JavaScript, chỉ mục mảng bắt đầu từ 0. Tức là, phần tử đầu tiên của một mảng được tìm thấy ở chỉ số 0, phần tử thứ hai ở chỉ mục một và phần tử thứ ba ở chỉ mục hai, v.v. - -```js -let nums = [1, 2, 3] -nums[0] = 10 - -console.log(nums) // [10, 2, 3] -``` - -Như bạn có thể thấy, một mảng, một kiểu dữ liệu không phải nguyên thủy có thể thay đổi được. Các kiểu dữ liệu không nguyên thủy không thể được so sánh theo giá trị. Ngay cả khi hai kiểu dữ liệu không nguyên thủy có cùng thuộc tính và giá trị, chúng cũng không hoàn toàn bằng nhau. - -```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) // false -``` - -Quy tắc ngón tay cái, chúng tôi không so sánh các kiểu dữ liệu không nguyên thủy. Không so sánh mảng, hàm hoặc đối tượng. -Các giá trị không nguyên thủy được gọi là kiểu tham chiếu, vì chúng đang được so sánh bằng tham chiếu thay vì giá trị. Hai đối tượng chỉ hoàn toàn bằng nhau nếu chúng tham chiếu đến cùng một đối tượng cơ bản. - -```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 -``` - -Nếu bạn gặp khó khăn trong việc hiểu sự khác biệt giữa kiểu dữ liệu nguyên thủy và kiểu dữ liệu không nguyên thủy, bạn không phải là người duy nhất. Hãy bình tĩnh và chuyển sang phần tiếp theo và cố gắng quay lại sau một thời gian. Bây giờ chúng ta hãy bắt đầu các kiểu dữ liệu theo kiểu số. - -## Số - -Số là số nguyên và giá trị thập phân có thể thực hiện tất cả các phép toán số học. -Hãy xem một số ví dụ về Số. - -### Khai báo kiểu dữ liệu số - -```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) -``` - -### Đối tượng Math - -Trong JavaScript, Đối tượng Math cung cấp rất nhiều phương thức để tương tác các con số. - -```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 with base E of x, Math.log(x) -console.log(Math.log(2)) // 0.6931471805599453 -console.log(Math.log(10)) // 2.302585092994046 - -// Returns the natural logarithm of 2 and 10 respectively -console.log(Math.LN2) // 0.6931471805599453 -console.log(Math.LN10) // 2.302585092994046 - -// Trigonometry -Math.sin(0) -Math.sin(60) - -Math.cos(0) -Math.cos(60) -``` - -#### Tạo số ngẫu nhiên - -Đối tượng Math trong JavaScript có phương thức `random()` để tạo ra số ngẫu nhiên từ 0 đến 0,999999999... - -```js -let randomNum = Math.random() // generates 0 to 0.999... -``` - -Bây giờ, chúng ta hãy xem cách sử dụng phương thức `random()` để tạo số ngẫu nhiên từ 0 đến 10: - -```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) // số từ 0 đến 10 -``` - -## Chuỗi - -Chuỗi là văn bản, nằm dưới dấu **nháy kép**, **nháy đơn**, **back-tick**. Để khai báo một chuỗi, chúng ta cần tên biến, toán tử gán, giá trị dưới dấu nháy đơn, dấu nháy kép hoặc dấu ngoặc kép. -Hãy xem một số ví dụ về chuỗi: - -```js -let space = ' ' // chuỗi rỗng -let firstName = 'Asabeneh' -let lastName = 'Yetayeh' -let country = 'Finland' -let city = 'Helsinki' -let language = 'JavaScript' -let job = 'teacher' -let quote = "The saying,'Seeing is Believing' is not correct in 2020." -let quotWithBackTick = `The saying,'Seeing is Believing' is not correct in 2020.` -``` - -### Nối chuỗi - -Nối hai hoặc nhiều chuỗi với nhau được gọi là nối chuỗi. -Sử dụng các chuỗi được khai báo trong phần Chuỗi trước: - -```js -let fullName = firstName + space + lastName; // nối hai chuỗi với nhau. -console.log(fullName); -``` - -```sh -Asabeneh Yetayeh -``` - -Chúng ta có thể nối các chuỗi theo nhiều cách khác nhau. - -#### Sử dụng toán tử cộng để nối chuỗi - -Nối chuỗi bằng cách sử dụng toán tử bổ sung là một cách cũ. Cách nối này tẻ nhạt và dễ xảy ra lỗi. Thật tốt khi biết cách nối theo cách này, nhưng tôi thực sự khuyên bạn nên sử dụng chuỗi mẫu ES6 (sẽ giải thích ở phần sau). - -```js -// Khai báo biến với các kiểu dữ liệu khác nhau -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 string addition - -console.log(personInfoOne) -``` - -```sh -Asabeneh Yetayeh. I am 250. I live in Finland -``` - -#### Chuỗi dài - -Một chuỗi có thể là một ký tự hoặc đoạn hoặc một trang. Nếu độ dài chuỗi quá lớn, nó không vừa với một dòng. Chúng ta có thể sử dụng ký tự gạch chéo ngược (\\) ở cuối mỗi dòng để chỉ ra rằng chuỗi sẽ tiếp tục ở dòng tiếp theo. - -**Ví dụ:** - -```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) -``` - -#### Chuỗi thoát trong Strings - -Trong JavaScript và các ngôn ngữ lập trình khác \ theo sau một số ký tự là một chuỗi thoát. Hãy xem các ký tự thoát phổ biến nhất: - -- \n: new line -- \t: Tab, means 8 spaces -- \\\\: Back slash -- \\': Single quote (') -- \\": Double quote (") - -```js -console.log('I hope everyone is enjoying the Học JavaScript trong 30 ngày 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 backslash symbol (\\)') // Để viết một dấu gạch chéo ngược -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\' isn\'t correct in 2020') -``` - -Kết quả trong console: - -```sh -I hope everyone is enjoying the Học JavaScript trong 30 ngày challenge. -Do you ? -Days Topics Exercises -Day 1 3 5 -Day 2 3 5 -Day 3 3 5 -Day 4 3 5 -This is a backslash symbol (\) -In every programming language it starts with "Hello, World!" -In every programming language it starts with 'Hello, World!' -The saying 'Seeing is Believing' isn't correct in 2020 -``` - -#### Template Literals (Template Strings) - -Để tạo chuỗi mẫu, chúng tôi sử dụng hai dấu tích. Chúng ta có thể đưa dữ liệu vào dưới dạng các biểu thức bên trong một chuỗi mẫu. Để nhập dữ liệu, chúng tôi đặt biểu thức bằng một dấu ngoặc nhọn ({}) trước dấu $. Xem cú pháp bên dưới. - -```js -//Syntax -`String literal text` -`String literal text ${expression}` -``` - -**Ví dụ: 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 -``` - -**Ví dụ: 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 expressions, 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 -``` - -### Phương thức String - -Mọi thứ trong JavaScript đều là một đối tượng. Chuỗi là một kiểu dữ liệu nguyên thủy có nghĩa là chúng ta không thể sửa đổi nó sau khi nó được tạo. Đối tượng string có nhiều phương thức string. Có nhiều phương thức chuỗi khác nhau có thể giúp chúng tôi làm việc với chuỗi. - -1. *length*: Phương thức `length` trả về độ dài của chuỗi bao gồm không gian trống. - -**Example:** - -```js -let js = 'JavaScript' -console.log(js.length) // 10 -let firstName = 'Asabeneh' -console.log(firstName.length) // 8 -``` - -2. *Truy cập các ký tự trong chuỗi*: Chúng ta có thể truy cập từng ký tự trong một chuỗi bằng cách sử dụng chỉ mục của nó. Trong lập trình, việc đếm bắt đầu từ 0. Chỉ số đầu tiên của chuỗi bằng 0 và chỉ số cuối cùng là độ dài của chuỗi trừ đi một. - - ![Truy cập string theo index](../../images/string_indexes.png) - -phương thức này thay đổi chuỗi thành chữ thường.. - -```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()*: thay đổi chuỗi thành chữ hoa. - -```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()*: thay đổi chuỗi thành chữ thường. - -```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()*: Cần có hai đối số, index bắt đầu và số ký tự để cắt. - -```js -let string = 'JavaScript' -console.log(string.substr(4,6)) // Script - -let country = 'Finland' -console.log(country.substr(3, 4)) // land -``` - -6. *substring()*: Nó có hai đối số, index bắt đầu và index dừng nhưng nó không bao gồm ký tự ở index dừng. - -```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()*: Tách một chuỗi tại một vị trí được chỉ định. - -```js -let string = 'Học JavaScript trong 30 ngày' - -console.log(string.split()) // Changes to an array -> ["Học JavaScript trong 30 ngày"] -console.log(string.split(' ')) // Split to an array at space -> ["30", "Days", "Of", "JavaScript"] - -let firstName = 'Asabeneh' - -console.log(firstName.split()) // Change to an array - > ["Asabeneh"] -console.log(firstName.split('')) // Split to an array at each letter -> ["A", "s", "a", "b", "e", "n", "e", "h"] - -let countries = 'Finland, Sweden, Norway, Denmark, and Iceland' - -console.log(countries.split(',')) // tách thành mảng tại dấu phẩy -> ["Finland", " Sweden", " Norway", " Denmark", " and Iceland"] -console.log(countries.split(', ')) //  ["Finland", "Sweden", "Norway", "Denmark", "and Iceland"] -``` - -8. *trim()*: Loại bỏ khoảng trắng ở đầu hoặc cuối chuỗi. - -```js -let string = ' Học JavaScript trong 30 ngày ' - -console.log(string) -console.log(string.trim(' ')) - -let firstName = ' Asabeneh ' - -console.log(firstName) -console.log(firstName.trim()) // vẫn xóa khoảng trắng ở đầu và cuối chuỗi -``` - -```sh - Học JavaScript trong 30 ngày -Học JavaScript trong 30 ngày - Asabeneh -Asabeneh -``` - -9. *includes()*: Nó nhận một đối số chuỗi con và nó kiểm tra xem đối số chuỗi con có tồn tại trong chuỗi hay không. `include()` trả về kiểu boolean. Nếu một chuỗi con tồn tại trong một chuỗi, nó trả về `true`, ngược lại là `false`. - -```js -let string = 'Học JavaScript trong 30 ngày' - -console.log(string.includes('Days')) // true -console.log(string.includes('days')) // false - it is case sensitive! -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()*: nhận như một tham số là chuỗi con cũ và một chuỗi con mới. - -```js -string.replace(oldsubstring, newsubstring) -``` - -```js -let string = 'Học JavaScript trong 30 ngày' -console.log(string.replace('JavaScript', 'Python')) // 30 Days Of Python - -let country = 'Finland' -console.log(country.replace('Fin', 'Noman')) // Nomanland -``` - -11. *charAt()*: Lấy index và nó trả về giá trị tại index đó - -```js -string.charAt(index) -``` - -```js -let string = 'Học JavaScript trong 30 ngày' -console.log(string.charAt(0)) // 3 - -let lastIndex = string.length - 1 -console.log(string.charAt(lastIndex)) // t -``` - -12. *charCodeAt()*: Lấy index và nó trả về mã char (số ASCII) của giá trị tại index đó. - -```js -string.charCodeAt(index) -``` - -```js -let string = 'Học JavaScript trong 30 ngày' -console.log(string.charCodeAt(3)) // D ASCII number is 68 - -let lastIndex = string.length - 1 -console.log(string.charCodeAt(lastIndex)) // t ASCII is 116 - -``` - -13. *indexOf()*: Lấy một chuỗi con và nếu chuỗi con tồn tại trong một chuỗi, nó trả về vị trí đầu tiên của chuỗi con nếu không tồn tại nó trả về `-1`. - -```js -string.indexOf(substring) -``` - -```js -let string = 'Học JavaScript trong 30 ngày' - -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()*: Lấy một chuỗi con và nếu chuỗi con tồn tại trong một chuỗi, nó trả về vị trí cuối cùng của chuỗi con nếu nó không tồn tại, nó trả về `-1`. - - -```js -//syntax -string.lastIndexOf(substring) -``` - -```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()*: nối các chuỗi được truyền vào nó - -```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*: nó nhận một chuỗi con làm đối số và nó kiểm tra xem chuỗi có bắt đầu bằng chuỗi con được chỉ định hay không. Nó trả về kiểu boolean (`true` hoặc `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*: nó nhận một chuỗi con làm đối số và nó kiểm tra xem chuỗi có kết thúc bằng chuỗi con được chỉ định hay không. Nó trả về kiểu boolean (`true` hoặc `false`). - -```js -string.endsWith(substring) -``` - -```js -let string = 'Love is the most powerful feeling in the world' - -console.log(string.endsWith('world')) // true -console.log(string.endsWith('love')) // false -console.log(string.endsWith('in the 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*: nó nhận một chuỗi con làm đối số và nó trả về index của kết quả khớp đầu tiên. Giá trị tìm kiếm có thể là một chuỗi hoặc một mẫu biểu thức chính quy. - -```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 -console.log(string.search(/javascript/gi)) // 7 -``` - -19. *match*: nó nhận một chuỗi con hoặc một mẫu biểu thức chính quy làm đối số và nó trả về một mảng nếu có khớp nếu không thì nó trả về null. Hãy để chúng tôi xem mẫu biểu thức chính quy trông như thế nào. Nó bắt đầu bằng dấu / và kết thúc bằng dấu /. - -```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 -``` - -Cú pháp match - -```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"] -``` - -Chúng ta hãy tách các số từ văn bản bằng cách sử dụng một biểu thức chính quy. Đây không phải là phần biểu thức chính quy, đừng hoảng sợ! Chúng ta sẽ đề cập đến các cụm từ thông dụng ở phần sau. - -```js -let txt = 'In 2019, I ran 30 Days of Python. Now, in 2020 I am 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()*: lặp lại 1 chuỗi với số lần được truyền vào nó. - -```js -string.repeat(n) -``` - -```js -let string = 'love' -console.log(string.repeat(10)) // lovelovelovelovelovelovelovelovelovelove -``` - -## Kiểm tra kiểu dữ liệu và Ép kiểu - -### Kiểm tra kiểu dữ liệu - -Để kiểm tra kiểu dữ liệu của một biến nào đó, sử dụng từ khoá `typeof`. - -**Ví dụ:** - -```js -// Các kiểu dữ liệu trong Javascript -// Dưới đây là các kiểu khai báo dữ liệu khác nhau - -let firstName = 'Asabeneh' // string -let lastName = 'Yetayeh' // string -let country = 'Finland' // string -let city = 'Helsinki' // string -let age = 250 // number -let job // undefined, vì chưa gán giá trị - -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 -``` - -### Đổi kiểu dữ liệu (Ép kiểu) - -- Kép kiểu: Chuyển đổi một kiểu dữ liệu này sang kiểu dữ liệu khác. Có các phương thức như `parseInt()`, `parseFloat()`, `Number()`, `dấu +`, `str()`. -Khi chúng ta thực hiện các phép toán số học, đầu tiên chuỗi số phải được chuyển đổi thành số nguyên hoặc float nếu không nó sẽ trả về lỗi. - -#### String thành Int - -Chúng ta có thể chuyển đổi chuỗi số thành một số. Bất kỳ số nào bên trong một dấu ngoặc kép là một chuỗi số. Ví dụ về chuỗi số: '10', '5', v.v. -Chúng ta có thể chuyển đổi chuỗi thành số bằng các phương pháp sau: - -- parseInt() -- Number() -- Dấu cộng (+) - -```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 thành Float - -Chúng ta có thể chuyển đổi chuỗi số thực thành một số thực. Bất kỳ số thực nào bên trong dấu ngoặc kép đều là chuỗi số thực. Ví dụ về chuỗi số thực: '9.81', '3.14', '1.44', v.v. -Chúng ta có thể chuyển đổi chuỗi số thực thành số bằng các phương pháp sau: - -- parseFloat() -- Number() -- Dấu cộng (+) - -```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(numFloat) // 9.81 -``` - -#### Float thành Int - -Chúng ta có thể chuyển đổi số thực thành số nguyên. -Sử dụng phương thức `parseInt()` để chuyển đổi float thành int: - -```js -let num = 9.81 -let numInt = parseInt(num) - -console.log(numInt) // 9 -``` - -🌕 Bạn thật tuyệt vời. Bạn vừa hoàn thành thử thách ngày thứ 2 và bạn đang đi trước hai bước trên con đường vươn tới sự vĩ đại. Bây giờ hãy thực hiện một số bài tập cho não và cho cơ của bạn. - -## 💻 Ngày 2: Bài tập - -### Bài tập: Cấp độ 1 - -1. Khai báo một biến có tên là challenge và gán giá trị là **'Học JavaScript trong 30 ngày'**. -2. In chuỗi trên console của trình duyệt bằng __console.log()__. -3. In __độ dài__ của chuỗi trên console của trình duyệt bằng cách sử dụng __console.log()__. -4. Đổi thành chữ in hoa tất cả ký tự trong chuỗi bằng phương thức __toUpperCase()__. -5. Đổi thành chữ thường tất cả ký tự trong chuỗi bằng phương thức __toLowerCase()__. -6. Cắt (slice) từ đầu tiên của chuỗi bằng cách sử dụng phương thức __substr()__ hoặc __substring()__. -7. Cắt bỏ cụm từ *Học JavaScript* from *Học JavaScript trong 30 ngày*. -8. Sử dụng phương thức __includes()__ để kiểm tra xem __Script__ có trong chuỗi hay không. -9. Tách __string__ thành __array__ sử dụng phương thức __split()__ -10. Tách chuỗi __Học JavaScript trong 30 ngày__ tại khoảng trắng bằng phương thức __split()__ -11. 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon' __tách__ chuỗi tại dấu phẩy và đổi thành một mảng. -12. Sử dụng __replace()__ để đổi __Học JavaScript trong 30 ngày__ thành __Học Python trong 30 ngày__. -13. Ký tự ở index 15 trong chuỗi 'Học JavaScript trong 30 ngày' là gì? Sử dụng phương thức __charAt()__. -14. Mã ký tự của J trong chuỗi 'Học JavaScript trong 30 ngày' bằng cách sử dụng là gì __charCodeAt()__ -15. Sử dụng phương thức __indexOf__ để xác định vị trí của lần xuất hiện đầu tiên của từ __o__ trong Học JavaScript trong 30 ngày -16. Sử dụng phương thức __lastIndexOf__ để xác định vị trí của lần xuất hiện cuối cùng của từ __o__ trong __Học JavaScript trong 30 ngày__. -17. Sử dụng phương thức __indexOf__ để tìm vị trí xuất hiện đầu tiên của từ __vì__ trong câu sau:__'Bạn không thể kết thúc câu bằng bởi vì bởi vì bởi vì là một liên từ'__ -18. Sử dụng phương thức __lastIndexOf__ để tìm vị trí xuất hiện cuối cùng của từ __vì__ trong câu sau:__'Bạn không thể kết thúc câu bằng bởi vì bởi vì bởi vì là một liên từ'__ -19. Sử dụng phương thức __search__ để tìm vị trí xuất hiện đầu tiên của từ __vì__ trong câu sau:__'Bạn không thể kết thúc câu bằng bởi vì bởi vì bởi vì là một liên từ'__ -20. Sử dụng phương thức __trim()__ để xóa mọi khoảng trắng ở đầu và cuối chuỗi. ví dụ ' Học JavaScript trong 30 ngày '. -21. Sử dụng phương thức __startsWith()__ với chuỗi *Học JavaScript trong 30 ngày* và làm kết quả thành `true`. -22. Sử dụng phương thức __endsWith()__ với chuỗi *Học JavaScript trong 30 ngày* và làm cho kết quả thành `true`. -23. Sử dụng phương thức __match()__ để tìm tất cả chữ __o__ có trong __Học JavaScript trong 30 ngày__ -24. Sử dụng __concat()__ để thêm 'Học JavaScript trong' và '30 ngày' vào 1 chuỗi, 'Học JavaScript trong 30 ngày' -25. Sử dụng phương thức __repeat()__ để in __Học JavaScript trong 30 ngày__ 2 lần. - -### Bài tập: Cấp độ 2 - -1. `Sử dụng console.log()` in ra câu lệnh sau: - - ```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 one another. - ``` - -2. Sử dụng `console.log()` in ra câu trích dẫn sau đây của Mẹ 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." - ``` - -3. Kiểm tra xem typeof '10' có bằng 10 hay không. Nếu không, hãy làm cho nó bằng nhau. -4. Kiểm tra xem `parseFloat('9, 8')` có bằng 10 hay không nếu không hãy làm cho nó bằng 10. -5. Kiểm tra xem có tìm thấy 'on' trong python và jargon không. -6. _Tôi hy vọng khóa học này không chứa đầy những biệt ngữ_. Kiểm tra nếu _biệt ngữ_ có trong câu. -7. Tạo một số ngẫu nhiên từ 0 đến 100. -8. Tạo một số ngẫu nhiên từ 50 đến 100. -9. Tạo một số ngẫu nhiên từ 0 đến 255. -10. Truy cập các ký tự chuỗi 'JavaScript' bằng cách sử dụng số ngẫu nhiên. -11. Sử dụng `console.log()` và các ký tự thoát để in mẫu sau. - - ```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 - ``` - -12. Sử dụng __substr__ để cắt ra cụm từ __bởi vì bởi vì__ từ câu sau:__'Bạn không thể kết thúc câu bằng bởi vì bởi vì bởi vì là một liên từ'__ - -### Bài tập: Cấp độ 3 - -1. 'Tình yêu là điều tuyệt vời nhất trên thế giới này. Một số đã tìm thấy tình yêu của mình và một số vẫn đang tìm kiếm tình yêu của mình.' Đếm số từ __tình yêu__ trong câu này. -2. Sử dụng __match()__ để đếm số lần từ __vì_ trong câu sau:__'Bạn không thể kết thúc câu bằng bởi vì bởi vì bởi vì là một liên từ'__ -3. Clean the following text and find the most frequent word (hint, use replace and regular expressions). - - ```js - const sentence = '%I $am@% a %tea@cher%, &and& I lo%#ve %te@a@ching%;. The@re $is no@th@ing; &as& mo@re rewarding as educa@ting &and& @emp%o@weri@ng peo@ple. ;I found tea@ching m%o@re interesting tha@n any ot#her %jo@bs. %Do@es thi%s mo@tiv#ate yo@u to be a tea@cher!? %Th#is 30#Days&OfJavaScript &is al@so $the $resu@lt of &love& of tea&ching' - ``` - -4. Tính tổng thu nhập hàng năm của người đó bằng cách trích các số từ văn bản sau. 'Anh ấy kiếm được 5000 euro từ lương mỗi tháng, 10000 euro tiền thưởng hàng năm, các khóa học trực tuyến 15000 euro mỗi tháng.' - -🎉 CHÚC MỪNG ! 🎉 - -[<< Ngày 1](../README.md) | [Ngày 3 >>](../03_Day_Booleans_operators_date/03_booleans_operators_date.md) diff --git a/Vietnamese/README.md b/Vietnamese/README.md deleted file mode 100644 index aee5862..0000000 --- a/Vietnamese/README.md +++ /dev/null @@ -1,669 +0,0 @@ -# Học JavaScript trong 30 ngày - -| # Ngày | Phần | -| ----- | :-------------------------------------------------------------------------------------------------------------------------------------------------: | -| 01 | [Giới thiệu](./readMe.md) | -| 02 | [Kiểu dữ liệu](./02_Day_Data_types/02_day_data_types.md) | -| 03 | [Booleans, Toán tử, Date](./03_Day_Booleans_operators_date/03_booleans_operators_date.md) | -| 04 | [Điều kiện](./04_Day_Conditionals/04_day_conditionals.md) | -| 05 | [Mảng](./05_Day_Arrays/05_day_arrays.md) | -| 06 | [Vòng lặp](./06_Day_Loops/06_day_loops.md) | -| 07 | [Functions](./07_Day_Functions/07_day_functions.md) | -| 08 | [Objects](./08_Day_Objects/08_day_objects.md) | -| 09 | [Đào sâu vào Functions](./09_Day_Higher_order_functions/09_day_higher_order_functions.md) | -| 10 | [Sets và Maps](./10_Day_Sets_and_Maps/10_day_Sets_and_Maps.md) | -| 11 | [Destructuring và Spreading](./11_Day_Destructuring_and_spreading/11_day_destructuring_and_spreading.md) | -| 12 | [Biểu thức chính quy](./12_Day_Regular_expressions/12_day_regular_expressions.md) | -| 13 | [Phương thức Console Object](./13_Day_Console_object_methods/13_day_console_object_methods.md) | -| 14 | [Error Handling](./14_Day_Error_handling/14_day_error_handling.md) | -| 15 | [Classes](./15_Day_Classes/15_day_classes.md) | -| 16 | [JSON](./16_Day_JSON/16_day_json.md) | -| 17 | [Web Storages](./17_Day_Web_storages/17_day_web_storages.md) | -| 18 | [Promises](./18_Day_Promises/18_day_promises.md) | -| 19 | [Closure](./19_Day_Closures/19_day_closures.md) | -| 20 | [Viết Clean Code](./20_Day_Writing_clean_codes/20_day_writing_clean_codes.md) | -| 21 | [DOM](./21_Day_DOM/21_day_dom.md) | -| 22 | [Thao tác với DOM Object](./22_Day_Manipulating_DOM_object/22_day_manipulating_DOM_object.md) | -| 23 | [Event Listeners](./23_Day_Event_listeners/23_day_event_listeners.md) | -| 24 | [Dự án nhỏ: Hệ mặt trời](./24_Day_Project_solar_system/24_day_project_solar_system.md) | -| 25 | [Dự án nhỏ: Hiển thị dữ liệu các quốc gia trên thế giới 1](./25_Day_World_countries_data_visualization_1/25_day_world_countries_data_visualization_1.md) | -| 26 | [Dự án nhỏ: Hiển thị dữ liệu các quốc gia trên thế giới 2](./26_Day_World_countries_data_visualization_2/26_day_world_countries_data_visualization_2.md) | -| 27 | [Dự án nhỏ: Portfolio](./27_Day_Mini_project_portfolio/27_day_mini_project_portfolio.md) | -| 28 | [Dự án nhỏ: Bảng xếp hạng](./28_Day_Mini_project_leaderboard/28_day_mini_project_leaderboard.md) | -| 29 | [Dự án nhỏ:Nhân vật hoạt hình](./29_Day_Mini_project_animating_characters/29_day_mini_project_animating_characters.md) | -| 30 | [Dự án cuối cùng](./30_Day_Mini_project_final/30_day_mini_project_final.md) | - -🧡🧡🧡 CHÚC BẠN CODE VUI VẺ 🧡🧡🧡 - -
- Ủng hộ tác giả để bổ sung thêm nhiều kiến thức bổ ích
- - Paypal Logo - -
- -
-

Học JavaScript trong 30 ngày: Giới thiệu

- - - - - Twitter Follow - -
- Tác giả: - Asabeneh Yetayeh
- Tháng 1, 2020 -
-
- -🇬🇧 [Tiếng Anh](./readMe.md) -🇪🇸 [Tiếng Tây Ban Nha](./Spanish/readme.md) -🇷🇺 [Tiếng Nga](./RU/README.md) -KR [Tiếng Hàn](./Korea/README.md) - -
- -
- - -[Ngày 2 >>](./02_Day_Data_types/02_day_data_types.md) - -![Ngày thứ 2 học JavaScript](../images/day_1_1.png) - -- [Học JavaScript trong 30 ngày](#30-days-of-javascript) -- [📔 Ngày 1](#-day-1) - - [Giới thiệu](#introduction) - - [Yêu cầu](#requirements) - - [Thiết lập](#setup) - - [Cài Node.js](#install-nodejs) - - [Trình duyệt](#browser) - - [Cài Google Chrome](#installing-google-chrome) - - [Mở Console Google Chrome](#opening-google-chrome-console) - - [Viết code trên Console trình duyệt](#writing-code-on-browser-console) - - [Console.log](#consolelog) - - [Console.log có nhiều tham số](#consolelog-with-multiple-arguments) - - [Comments](#comments) - - [Cú pháp](#syntax) - - [Toán tử](#arithmetics) - - [Code Editor](#code-editor) - - [Cài Visual Studio Code](#installing-visual-studio-code) - - [Cách sử dụng Visual Studio Code](#how-to-use-visual-studio-code) - - [Thêm JavaScript vào trang web](#adding-javascript-to-a-web-page) - - [Inline Script](#inline-script) - - [Internal Script](#internal-script) - - [External Script](#external-script) - - [Nhiều External Scripts](#multiple-external-scripts) - - [Giới thiệu về Kiểu dữ liệu](#introduction-to-data-types) - - [Numbers](#numbers) - - [Strings](#strings) - - [Booleans](#booleans) - - [Undefined](#undefined) - - [Null](#null) - - [Xác định kiểu dữ liệu](#checking-data-types) - - [Comments tiếp](#comments-again) - - [Biến](#variables) -- [💻 Ngày 1: Bài tập](#-day-1-exercises) - -# 📔 Ngày 1 - -## Giới thiệu - -**Chúc mừng bạn** đã quyết định tham gia học JavaScript trong 30 ngày. Trong thử thách này, bạn sẽ học mọi thứ bạn cần để trở thành một lập trình viên JavaScript, toàn bộ khái niệm về lập trình. Cuối thử thách, bạn sẽ nhận được chứng chỉ hoàn thành thử thách lập trình 30DaysOfJavaScript. Trong trường hợp bạn cần giúp đỡ hoặc nếu bạn muốn giúp đỡ người khác, bạn có thể tham gia [nhóm Telegram](https://t.me/ThirtyDaysOfJavaScript). - -Thử thách **30DaysOfJavaScript** là để hướng dẫn cho cả người mới học và các lập trình viên JavaScript nâng cao. Chào bạn đến với JavaScript. JavaScript là ngôn ngữ lập trình của web. Tôi thích sử dụng và chia sẻ kiến thức về JavaScript và tôi hy vọng bạn cũng sẽ làm như vậy. - -Trong các thử thách JavaScript này, bạn sẽ học JavaScript, ngôn ngữ lập trình phổ biến nhất thế giới đến thời điểm hiện tại. -JavaScript sử dụng để **_thêm tính tương tác cho các trang web, để phát triển ứng dụng di động, ứng dụng máy tính để bàn, trò chơi_** và ngày nay JavaScript có thể được sử dụng cho **_machine learning_** and **_AI_**. -**_JavaScript (JS)_** ngày càng phổ biến trong những năm gần đây và dẫn đầu các ngôn ngữ lập trình trong 6 năm liên tiếp và là ngôn ngữ lập trình được sử dụng nhiều nhất trên Github. - -## Yêu cầu - -Bạn không cần phải có kiến thức về lập trình để bắt đầu thử thách này, bạn chỉ cần có: - -1. Động lực -2. Máy tính (Laptop) -3. Kết nối mạng -4. Trình duyệt -5. Code editor (VSCode) - -## Thiết lập - -Tôi tin rằng bạn có động lực và muốn trở thành một lập trình viên, máy tính và kết nối mạng. Nếu bạn đã có đầy đủ thì chúng ta hãy bắt đầu. - -### Cài Node.js - -Bạn có thể không cần phải cài Node.js ngay bây giờ nhưng sau này thì có thể cần đến. Cài [Node.js](https://nodejs.org/en/). - -![Tải node](../images/download_node.png) - -Sau khi tải xong, nhấn đúp để cài đặt - -![Cài node](../images/install_node.png) - -Chúng ta có thể kiểm tra xem Node đã cài hay chưa bằng cách mở terminal hoặc cmd trên máy tính. - -```sh -$ node -v -v12.14.0 -``` - -Khi làm bài hướng dẫn này tôi đang sử dụng phiên bản Node 12.14.0, nhưng hiện tại phiên bản Node.js được đề xuất để tải xuống là v17.6.0, bạn có thể sử dụng phiên bản Node mới nhất. - -### Trình duyệt - -Hiện tại có rất nhiều trình duyệt web, tuy nhiên tôi đề xuất nên sử dụng Google Chrome. - -#### Cài Google Chrome - -Cài [Google Chrome](https://www.google.com/chrome/) nếu bạn chưa cài nó. Chúng ta có thể viết code JavaScript trên console trình duyệt, nhưng chúng ta không sử dụng console trình duyệt để lập trình. - -![Google Chrome](../images/google_chrome.png) - -#### Mở Console Google Chrome - - -Bạn có thể mở console Google Chrome bằng cách nhấp vào ba dấu chấm ở trên cùng bên phải trình duyệt, chọn _More tools -> Developer tools_ hoặc sử dụng phím tắt. - -![Mở chrome](../images/opening_developer_tool.png) - -Để mở Console Google Chrome bằng phím tắt: - -```sh -Mac -Command+Option+J - -Windows/Linux: -Ctl+Shift+J (hoặc F12) -``` - -![Mở console](../images/opening_chrome_console_shortcut.png) - -Sau khi bạn mở console Google Chrome, hãy thử khám phá các nút được đánh dấu bên dưới. Chúng ta sẽ dành phần lớn thời gian trên Console. Console là nơi bạn viết code JavaScript. Công cụ Google Console V8 sẽ chuyển code của bạn thành mã máy. -Bây giờ chúng ta sẽ viết mã JavaScript trên console của Google Chrome: - -![viết code trên console](../images/js_code_on_chrome_console.png) - -#### Viết code trên Console của trình duyệt - -Chúng ta có thể viết bất kỳ code JavaScript nào trên console của Google hoặc bất kỳ console của trình duyệt nào. Tuy nhiên, đối với thử thách này, chúng ta chỉ sử dụng console của Google Chrome. Mở console bằng cách sử dụng: - -```sh -Mac -Command+Option+I - -Windows: -Ctl+Shift+I (hoặc F12) -``` - -##### Console.log - -Để viết code JavaScript, chúng ta sẽ sử dụng 1 hàm có sẵn là **console.log()**. Chúng ta sẽ truyền vào một tham số và hàm sẽ hiển thị kết quả đã truyền vào. Chúng ta sẽ truyền `'Hello, World'` dưới dạng là tham số vào hàm `console.log()`. - -```js -console.log('Hello, World!') -``` - -##### Console.log có nhiều tham số - -Hàm **`console.log()`** có thể nhận nhiều tham số được phân cách bằng dấu phẩy. Cú pháp sẽ giống như này:**`console.log(param1, param2, param3)`** - -![console log có nhiều tham số](../images/console_log_multipl_arguments.png) - -```js -console.log('Hello', 'World', '!') -console.log('MỪNG', 'NGÀY', '8/3', 2022) -console.log('Chào bạn', 'đến với ', 30, 'Days', 'Of', 'JavaScript') -``` - -Bạn có thể thấy đoạn code bên trên, hàm _`console.log()`_ có thể nhận nhiều tham số. - -Chúc mừng! Bạn đã viết code JavaScript bằng cách sử dụng _`console.log()`_. - -##### Comments - -Chúng ta có thể thêm comment vào code. Comment rất quan trọng để làm cho code dễ đọc hơn và để lại nhận xét trong code. JavaScript không chạy phần đã comment trong code. Trong JavaScript, bất kỳ dòng nào bắt đầu bằng `//` trong JavaScript đều là một comment, và bất kỳ cái gì kèm theo như thế này `//` đều là comment. - -**Ví dụ: Comment 1 dòng** - -```js -// Đây là comment thứ nhất -// Đây là comment thứ hai -// Đây là comment 1 dòng -``` - -**Ví dụ: Comment nhiều dòng** - -```js -/* - Đây là comment nhiều dòng - Comment nhiều dòng có thể có nhiều dòng - JavaScript là ngôn ngữ của web - */ -``` - -##### Cú pháp - -Ngôn ngữ lập trình tương tự như ngôn ngữ của con người. Tiếng Việt hoặc nhiều ngôn ngữ khác sử dụng các từ, cụm từ, câu, câu ghép và nhiều ngôn ngữ khác để truyền tải một thông điệp có ý nghĩa. Ý nghĩa cú pháp trong tiếng Việt là _sự sắp xếp các từ và cụm từ để tạo ra các câu có cấu trúc trong một ngôn ngữ_. Định nghĩa kỹ thuật của cú pháp là cấu trúc của các câu lệnh trong một ngôn ngữ máy tính. Ngôn ngữ lập trình cũng có cú pháp. JavaScript là một ngôn ngữ lập trình và giống như các ngôn ngữ lập trình khác, nó có cú pháp riêng. Nếu chúng ta không viết một cú pháp mà JavaScript hiểu, nó sẽ phát sinh các loại lỗi khác nhau. Chúng ta sẽ khám phá các loại lỗi trong JavaScript khác nhau ở phần sau. Bây giờ, hãy xem 1 cú pháp bị lỗi bên dưới. - -![Lỗi](../images/raising_syntax_error.png) - -Tôi đã phạm một sai lầm có chủ ý. Kết quả là console làm tăng lỗi cú pháp. Trên thực tế, cú pháp rất nhiều thông tin. Nó thông báo loại sai lầm đã được thực hiện. Bằng cách đọc hướng dẫn phản hồi lỗi, chúng ta có thể sửa cú pháp và khắc phục sự cố. Quá trình xác định và loại bỏ lỗi khỏi chương trình được gọi là gỡ lỗi (debug). Bây giờ chúng ta sẽ gỡ lỗi: - -```js -console.log('Hello, World!') -console.log('Hello, World!') -``` - -Hiện tại, chúng ta đã thấy cách hiển thị văn bản bằng cách sử dụng _`console.log()`_. Nếu chúng ta in văn bản hoặc chuỗi bằng cách sử dụng _`console.log()`_, văn bản phải nằm trong dấu nháy đơn, dấu ngoặc kép hoặc que ngược. - -**Ví dụ:** - -```js -console.log('Hello, World!') -console.log("Hello, World!") -console.log(`Hello, World!`) -``` - -#### Toán tử - -Bây giờ, chúng ta sẽ viết code JavaScript nhiều hơn bằng cách sử dụng _`console.log()`_ trên console của Google Chrome cho các kiểu dữ liệu số. Ngoài văn bản, chúng ta cũng có thể thực hiện các phép tính toán bằng JavaScript. Chúng ta sẽ thực hiện các phép tính đơn giản sau. Có thể viết code JavaScript trên console Google Chrome trực tiếp mà không cần hàm **_`console.log()`_**. Tuy nhiên, nó được đưa vào phần này vì hầu hết thử thách này sẽ diễn ra trong code editor, nơi việc sử dụng hàm là bắt buộc. - -![Toán tử](../images/arithmetic.png) - -```js -console.log(2 + 3) // Cộng -console.log(3 - 2) // Trừ -console.log(2 * 3) // Nhân -console.log(3 / 2) // Chia -console.log(3 % 2) // Chia lấy dư -console.log(3 ** 2) // Luỹ thừa 3 ** 2 == 3 * 3 -``` - -### Code Editor - -Chúng ta có thể viết code trên console của trình duyệt, nhưng nó sẽ không dành cho các dự án lớn hơn. Trong môi trường làm việc thực tế, các lập trình viên sử dụng các code editor khác nhau để viết code. Trong thử thách Học JavaScript trong 30 ngày này, chúng ta sẽ sử dụng Visual Studio Code. - -#### Cài Visual Studio Code - -Visual Studio Code là một trình soạn thảo văn bản nguồn mở rất phổ biến. Tôi muốn giới thiệu bạn [tải Visual Studio Code](https://code.visualstudio.com/), nhưng nếu bạn muốn sử dụng các editor, hãy thoải mái làm theo những gì bạn có. - -![Vscode](../images/vscode.png) - -Nếu bạn đã cài đặt Visual Studio Code, bây giờ chúng ta sẽ sử dụng nó. - -#### Cách sử dụng Visual Studio Code - -Mở Visual Studio Code bằng cách nhấp đúp vào biểu tượng. Khi đã mở, bạn sẽ thấy giao diện như này. Hãy làm quen với các phần mà được đánh dấu. - -![Vscode ui](../images/vscode_ui.png) - -![Vscode thêm mới dự án](../images/adding_project_to_vscode.png) - -![Vscode mở dự án](../images/opening_project_on_vscode.png) - -![file script](../images/scripts_on_vscode.png) - -![Cài Live Server](../images/vsc_live_server.png) - -![chạy script](../images/running_script.png) - -![chạy code](../images/launched_on_new_tab.png) - -## Thêm JavaScript vào trang web - -JavaScript có thể thêm vào trang web bằng 3 cách: - -- **_Inline script_** -- **_Internal script_** -- **_External script_** -- **_Multiple External scripts_** - -Các phần sau đây sẽ hướng dẫn các cách khác nhau để thêm code JavaScript vào trang web. - -### Inline Script - -Tạo thư mục trên màn hình hoặc ở bất kỳ vị trí nào, đặt tên là 30DaysOfJS và tạo tệp có tên **_`index.html`_**. Sau đó, dán mã sau và mở nó trong trình duyệt, ví dụ [Chrome](https://www.google.com/chrome/). - -```html - - - - 30DaysOfScript:Inline Script - - - - - -``` - -Bây giờ, bạn vừa viết inline script (nhúng trực tiếp) đầu tiên của mình. Chúng tôi có thể tạo một popup cảnh báo bằng cách sử dụng hàm có sẵn _`alert()`_ . - -### Internal Script - -Internal Script có thể được viết trong thẻ _`head`_ hoặc _`body`_, nhưng nó sẽ được ưu tiên chạy trước khi viết trong phần body của tệp HTML. -Trước tiên, chúng ta hãy viết trên phần head của trang. - -```html - - - - 30DaysOfScript:Internal Script - - - - -``` - -Đây là cách chúng ta sẽ viết Inernal Script trong thử thách này. Viết code JavaScript trong phần body là tùy chọn ưu tiên nhất. Mở console của trình duyệt để xem kết quả từ `console.log()`. - -```html - - - - 30DaysOfScript:Internal Script - - - - - - -``` - -Mở console của trình duyệt để xem kết quả từ `console.log()`. - -![js code từ vscode](../images/js_code_vscode.png) - -### External Script - -Tương tự như Internal Script, External Script có thể nằm trên header hoặc body, nhưng tốt hơn là đặt nó trong phần body. -Đầu tiên, chúng ta sẽ tạo một tệp JavaScript có đuôi là `.js`. Tất cả tệp JavaScript đều có đuôi là `.js`. Tạo một tệp có tên là `Introduction.js` bên trong thư mục vừa nảy bạn đã tạo và viết code sau và nhúng tệp .js này vào cuối phần body. - -```js -console.log('Chào bạn đến với 30DaysOfJavaScript') -``` - -Nhúng External scripts trong thẻ _head_: - -```html - - - - 30DaysOfJavaScript:External script - - - - -``` - -Nhúng External scripts trong thẻ _body_: - -```html - - - - 30DaysOfJavaScript:External script - - - - - - - -``` - -Mở console trình duyệt để xem kết quả của `console.log()`. - -### Nhúng nhiều External Scripts - -Chúng ta cũng có thể nhúng nhiều tệp JavaScript bên ngoài trong một trang web. -Tạo tệp `helloworld.js` trong thư mục 30DaysOfJS và viết theo code bên dưới. - -```js -console.log('Hello, World!') -``` - -```html - - - - Multiple External Scripts - - - - - - -``` - -_Tệp main.js của bạn phải nằm bên dưới tất cả các script khác_. Điều rất quan trọng là phải nhớ điều này. - -![Nhiều Script](../images/multiple_script.png) - -## Giới thiệu các kiểu các dữ liệu - -Trong JavaScript và các ngôn ngữ lập trình khác, có nhiều kiểu dữ liệu khác nhau. Sau đây là các kiểu dữ liệu nguyên thủy của JavaScript: _String, Number, Boolean, undefined, Null_, và _Symbol_. - -### Numbers (số) - -- Số nguyên: Số nguyên (âm, 0 và dương) - Ví dụ: - ... -3, -2, -1, 0, 1, 2, 3 ... -- Số thập phân - Ví dụ - ... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ... - -### Strings (Chuỗi) - -Tập hợp một hoặc nhiều ký tự nằm giữa hai nháy đơn, dấu nháy kép hoặc gạch chéo. - -**Ví dụ:** - -```js -'a' -'Asabeneh' -"Asabeneh" -'Việt Nam' -'JavaScript là ngôn ngữ lập trình tuyệt nhất' -'Tôi thích chia sẻ' -'Tôi hy vọng bạn đang tận hưởng ngày đầu tiên' -`Chúng ta cũng có thể tạo một chuỗi bằng cách sử dụng một gạch chéo` -'Một chuỗi có thể chỉ nhỏ bằng một ký tự hoặc lớn bằng nhiều trang' -'Bất kỳ loại dữ liệu nào dưới dấu nháy đơn, dấu nháy kép hoặc gạch chéo đều là một chuỗi' -``` - -### Booleans - -Giá trị boolean là `True` hoặc `False`. Mọi phép so sánh đều trả về giá trị boolean, đúng hoặc sai. - -Kiểu dữ liệu boolean là giá trị `true` hoặc `false`. - -**Ví dụ:** - -```js -true // nếu đèn sáng, giá trị là true -false // nếu đèn tắt, giá trị là false -``` - -### Undefined - -Trong JavaScript, nếu chúng ta không gán giá trị cho một biến thì giá trị đó không được xác định. Ngoài ra, nếu một hàm không trả về bất cứ thứ gì, nó sẽ trả về không xác định. - -```js -let firstName -console.log(firstName) // undefined, bởi vì nó chưa được gán cho một giá trị nào -``` - -### Null - -Null trong JavaScript có nghĩa là một biến rỗng. - -```js -let emptyValue = null -``` - -## Xác định kiểu dữ liệu - -Để kiểm tra kiểu dữ liệu của một biến, chúng ta sử dụng **typeof**. Xem ví dụ bên dưới. - -```js -console.log(typeof 'Asabeneh') // string -console.log(typeof 5) // number -console.log(typeof true) // boolean -console.log(typeof null) // object type -console.log(typeof undefined) // undefined -``` - -## Comments lần nữa - -Hãy nhớ rằng comment trong JavaScript cũng tương tự như các ngôn ngữ lập trình khác. Comment rất quan trọng trong việc làm cho code của bạn dễ đọc hơn. -Có hai cách comment: - -- _Comment 1 dòng_ -- _Comment nhiều dòng_ - -```js -// comment chính nó là một comment 1 dòng -// let firstName = 'Asabeneh'; comment 1 dòng -// let lastName = 'Yetayeh'; comment 1 dòng -``` - -Comment nhiều dòng: - -```js -/* - let location = 'Helsinki'; - let age = 100; - let isMarried = true; - Đây là comment nhiều dòng -*/ -``` - -## Biến - -Biến là _vùng chứa_ của dữ liệu. Các biến được sử dụng để _lưu trữ_ dữ liệu trong vị trí bộ nhớ. Khi một biến được khai báo, một vị trí bộ nhớ được dành riêng. Khi gán giá trị (dữ liệu) cho một biến, không gian bộ nhớ sẽ được lấp đầy bởi dữ liệu đó. Để khai báo một biến, chúng ta sử dụng các từ khóa _var_, _let_, hoặc _const_. - -Đối với một biến chúng ta cần thay đổi dữ liệu sau này, chúng ta sử dụng _let_. Nếu dữ liệu của biến đó không cần thay đổi thì chúng ta sử dụng _const_. Ví dụ, PI, tên quốc gia, trọng lực, các đối tượng này không thay đổi dữ liệu thì dùng _const_. Chúng ta sẽ không sử dụng `var` trong thử thách này và tôi không khuyên bạn nên sử dụng nó. Đây là cách dễ bị lỗi khi khai báo biến, nó có rất nhiều lỗ hổng. Chúng ta sẽ nói chi tiết hơn về `var`, `let` và `const` trong các phần khác. Còn bây giờ, lời giải thích trên là đủ. - -Tên biến JavaScript hợp lệ phải tuân theo các quy tắc sau: - -- Tên biến JavaScript không được bắt đầu bằng một số. -- Tên biến JavaScript không được có ký tự đặc biệt ngoại trừ ký tự $ và dấu gạch dưới _. -- Tên biến JavaScript tuân theo quy ước camelCase. -- Tên biến JavaScript không được có khoảng trắng giữa các từ. - -Sau đây là các ví dụ về các biến JavaScript hợp lệ. - -```js -firstName -lastName -country -city -capitalCity -age -isMarried - -first_name -last_name -is_married -capital_city - -num1 -num_1 -_num_1 -$num1 -year2020 -year_2020 -``` - -Hai biến đầu tiên bên trên tuân theo quy ước camelCase về khai báo trong JavaScript. Trong tài liệu này, chúng tôi sẽ sử dụng các biến camelCase (camelWithOneHump). Chúng ta sử dụng CamelCase (CamelWithTwoHump) để khai báo các lớp, chúng ta sẽ thảo luận về các lớp và đối tượng trong phần khác. - -Ví dụ về các biến không hợp lệ: - -```js - first-name - 1_num - num_#_1 -``` - -Chúng ta hãy khai báo các biến với các kiểu dữ liệu khác nhau. Để khai báo 1 biến, sử dụng từ khoá _let_ hoặc _const_ trước tên biến. Theo sau tên biến, chúng ta viết một dấu bằng (toán tử gán) và một giá trị (dữ liệu được gán). - -```js -// Cú pháp -let tenBien = giatri -``` - -Tên biến là tên lưu trữ các dữ liệu có giá trị khác nhau. Xem bên dưới để biết các ví dụ chi tiết. - -**Ví dụ về khai báo biến** - -```js -// Khai báo biến với các kiểu dữ liệu các nhau -let firstName = 'Đạt' // tên của 1 người -let lastName = 'Ngô Quốc' // họ của 1 người -let country = 'Việt Nam' // quốc gia -let city = 'Hà Nội' // thủ đô -let age = 19 // tuổi -let isMarried = false // đã cưới hay chưa - -console.log(firstName, lastName, country, city, age, isMarried) -``` - -```sh -Đạt Ngô Quốc Việt Nam Hà Nội 19 false -``` - -```js -// Khai báo biến với kiểu dữ liệu số -let age = 100 // tuổi -const gravity = 9.81 // trọng lực trái đất m/s2 -const boilingPoint = 100 // độ sôi của nước, nhiệt độ tính bằng °C -const PI = 3.14 // số PI -console.log(gravity, boilingPoint, PI) -``` - -```sh -9.81 100 3.14 -``` - -```js -// Bạn cũngc có thể khai báo biến trên 1 dòng phân cách bằng dấu phẩy, tuy nhiên, tôi khuyên bạn nên sử dụng một dòng riêng biệt để làm cho code dễ đọc hơn -let name = 'Ngô Quốc Đạt', job = 'developer', live = 'Việt Nam' -console.log(name, job, live) -``` - -```sh -Ngô Quốc Đạt developer Việt Nam -``` - -Khi bạn chạy tệp _index.html_ trong thư mục 01-Day bạn sẽ thấy như này: - -![Ngày 1](../images/day_1.png) - -🌕 Bạn thật tuyệt! Bạn vừa hoàn thành thử thách ngày 1 và bạn đang trên đường vươn tới sự vĩ đại. Bây giờ hãy thực hiện một số bài tập cho não và cơ bắp của bạn. - -# 💻 Ngày 1: Bài tập - -1. Viết 1 dòng comment nói là, _comment làm code dễ đọc hơn_ -2. Viết 1 dòng comment khác nói là, _Chào mừng bạn đến với 30DaysOfJavaScript_ -3. Viết comment nhiều dòng nói là, _comment làm code dễ đọc hơn, dễ sử dụng lại_ _và chi tiết_ -4. Tạo tệp `variable.js` và khai báo các biến và gán các kiểu dữ liệu `string`, `boolean`, `undefined` và `null`. -5. Tạo tệp `datatypes.js` và sử dụng **_typeof_** để kiểm tra các kiểu dữ liệu khác nhau. Kiểm tra kiểu dữ liệu của từng biến. -6. Khai báo 4 biến không gán giá trị -7. Khai báo 4 biến có gán giá trị -8. Khai báo các biến để lưu trữ họ, tên, tình trạng hôn nhân, quốc gia và tuổi của bạn trong nhiều dòng -9. Khai báo các biến để lưu trữ họ, tên, tình trạng hôn nhân, quốc gia và tuổi của bạn trong một dòng duy nhất -10. Khai báo 2 biến _myAge_ và _yourAge_ và gán giá trị cho nó, và xuất nó ra trên console của trình duyệt. - -```sh -I am 25 years old. -You are 30 years old. -``` - -🎉 CHÚC MỪNG ! 🎉 - -[Ngày 2 >>](./02_Day_Data_types/02_day_data_types.md) diff --git a/data/countries.js b/data/countries.js deleted file mode 100644 index e57b005..0000000 --- a/data/countries.js +++ /dev/null @@ -1,195 +0,0 @@ -const countries = [ - 'Afghanistan', - 'Albania', - 'Algeria', - 'Andorra', - 'Angola', - 'Antigua and Barbuda', - 'Argentina', - 'Armenia', - 'Australia', - 'Austria', - 'Azerbaijan', - 'Bahamas', - 'Bahrain', - 'Bangladesh', - 'Barbados', - 'Belarus', - 'Belgium', - 'Belize', - 'Benin', - 'Bhutan', - 'Bolivia', - 'Bosnia and Herzegovina', - 'Botswana', - 'Brazil', - 'Brunei', - 'Bulgaria', - 'Burkina Faso', - 'Burundi', - 'Cambodia', - 'Cameroon', - 'Canada', - 'Cape Verde', - 'Central African Republic', - 'Chad', - 'Chile', - 'China', - 'Colombi', - 'Comoros', - 'Congo (Brazzaville)', - 'Congo', - 'Costa Rica', - "Cote d'Ivoire", - 'Croatia', - 'Cuba', - 'Cyprus', - 'Czech Republic', - 'Denmark', - 'Djibouti', - 'Dominica', - 'Dominican Republic', - 'East Timor (Timor Timur)', - 'Ecuador', - 'Egypt', - 'El Salvador', - 'Equatorial Guinea', - 'Eritrea', - 'Estonia', - 'Ethiopia', - 'Fiji', - 'Finland', - 'France', - 'Gabon', - 'Gambia, The', - 'Georgia', - 'Germany', - 'Ghana', - 'Greece', - 'Grenada', - 'Guatemala', - 'Guinea', - 'Guinea-Bissau', - 'Guyana', - 'Haiti', - 'Honduras', - 'Hungary', - 'Iceland', - 'India', - 'Indonesia', - 'Iran', - 'Iraq', - 'Ireland', - 'Israel', - 'Italy', - 'Jamaica', - 'Japan', - 'Jordan', - 'Kazakhstan', - 'Kenya', - 'Kiribati', - 'Korea, North', - 'Korea, South', - 'Kuwait', - 'Kyrgyzstan', - 'Laos', - 'Latvia', - 'Lebanon', - 'Lesotho', - 'Liberia', - 'Libya', - 'Liechtenstein', - 'Lithuania', - 'Luxembourg', - 'Macedonia', - 'Madagascar', - 'Malawi', - 'Malaysia', - 'Maldives', - 'Mali', - 'Malta', - 'Marshall Islands', - 'Mauritania', - 'Mauritius', - 'Mexico', - 'Micronesia', - 'Moldova', - 'Monaco', - 'Mongolia', - 'Morocco', - 'Mozambique', - 'Myanmar', - 'Namibia', - 'Nauru', - 'Nepal', - 'Netherlands', - 'New Zealand', - 'Nicaragua', - 'Niger', - 'Nigeria', - 'Norway', - 'Oman', - 'Pakistan', - 'Palau', - 'Panama', - 'Papua New Guinea', - 'Paraguay', - 'Peru', - 'Philippines', - 'Poland', - 'Portugal', - 'Qatar', - 'Romania', - 'Russia', - 'Rwanda', - 'Saint Kitts and Nevis', - 'Saint Lucia', - 'Saint Vincent', - 'Samoa', - 'San Marino', - 'Sao Tome and Principe', - 'Saudi Arabia', - 'Senegal', - 'Serbia and Montenegro', - 'Seychelles', - 'Sierra Leone', - 'Singapore', - 'Slovakia', - 'Slovenia', - 'Solomon Islands', - 'Somalia', - 'South Africa', - 'Spain', - 'Sri Lanka', - 'Sudan', - 'Suriname', - 'Swaziland', - 'Sweden', - 'Switzerland', - 'Syria', - 'Taiwan', - 'Tajikistan', - 'Tanzania', - 'Thailand', - 'Togo', - 'Tonga', - 'Trinidad and Tobago', - 'Tunisia', - 'Turkey', - 'Turkmenistan', - 'Tuvalu', - 'Uganda', - 'Ukraine', - 'United Arab Emirates', - 'United Kingdom', - 'United States', - 'Uruguay', - 'Uzbekistan', - 'Vanuatu', - 'Vatican City', - 'Venezuela', - 'Vietnam', - 'Yemen', - 'Zambia', - 'Zimbabwe' -] diff --git a/data/countries_data.js b/data/countries_data.js deleted file mode 100644 index 138aea4..0000000 --- a/data/countries_data.js +++ /dev/null @@ -1,2864 +0,0 @@ -const countries_data = [ - { - "name": "Afghanistan", - "capital": "Kabul", - "languages": [ - "Pashto", - "Uzbek", - "Turkmen" - ], - "population": 40218234, - "flag": "https://upload.wikimedia.org/wikipedia/commons/5/5c/Flag_of_the_Taliban.svg", - "region": "Asia", - "area": 652230 - }, - { - "name": "Åland Islands", - "capital": "Mariehamn", - "languages": [ - "Swedish" - ], - "population": 28875, - "flag": "https://flagcdn.com/ax.svg", - "region": "Europe", - "area": 1580 - }, - { - "name": "Albania", - "capital": "Tirana", - "languages": [ - "Albanian" - ], - "population": 2837743, - "flag": "https://flagcdn.com/al.svg", - "region": "Europe", - "area": 28748 - }, - { - "name": "Algeria", - "capital": "Algiers", - "languages": [ - "Arabic" - ], - "population": 43851043, - "flag": "https://flagcdn.com/dz.svg", - "region": "Africa", - "area": 2381741 - }, - { - "name": "American Samoa", - "capital": "Pago Pago", - "languages": [ - "English", - "Samoan" - ], - "population": 55197, - "flag": "https://flagcdn.com/as.svg", - "region": "Oceania", - "area": 199 - }, - { - "name": "Andorra", - "capital": "Andorra la Vella", - "languages": [ - "Catalan" - ], - "population": 77265, - "flag": "https://flagcdn.com/ad.svg", - "region": "Europe", - "area": 468 - }, - { - "name": "Angola", - "capital": "Luanda", - "languages": [ - "Portuguese" - ], - "population": 32866268, - "flag": "https://flagcdn.com/ao.svg", - "region": "Africa", - "area": 1246700 - }, - { - "name": "Anguilla", - "capital": "The Valley", - "languages": [ - "English" - ], - "population": 13452, - "flag": "https://flagcdn.com/ai.svg", - "region": "Americas", - "area": 91 - }, - { - "name": "Antarctica", - "languages": [ - "English", - "Russian" - ], - "population": 1000, - "flag": "https://flagcdn.com/aq.svg", - "region": "Polar", - "area": 14000000 - }, - { - "name": "Antigua and Barbuda", - "capital": "Saint John's", - "languages": [ - "English" - ], - "population": 97928, - "flag": "https://flagcdn.com/ag.svg", - "region": "Americas", - "area": 442 - }, - { - "name": "Argentina", - "capital": "Buenos Aires", - "languages": [ - "Spanish", - "Guaraní" - ], - "population": 45376763, - "flag": "https://flagcdn.com/ar.svg", - "region": "Americas", - "area": 2780400 - }, - { - "name": "Armenia", - "capital": "Yerevan", - "languages": [ - "Armenian" - ], - "population": 2963234, - "flag": "https://flagcdn.com/am.svg", - "region": "Asia", - "area": 29743 - }, - { - "name": "Aruba", - "capital": "Oranjestad", - "languages": [ - "Dutch", - "(Eastern) Punjabi" - ], - "population": 106766, - "flag": "https://flagcdn.com/aw.svg", - "region": "Americas", - "area": 180 - }, - { - "name": "Australia", - "capital": "Canberra", - "languages": [ - "English" - ], - "population": 25687041, - "flag": "https://flagcdn.com/au.svg", - "region": "Oceania", - "area": 7692024 - }, - { - "name": "Austria", - "capital": "Vienna", - "languages": [ - "German" - ], - "population": 8917205, - "flag": "https://flagcdn.com/at.svg", - "region": "Europe", - "area": 83871 - }, - { - "name": "Azerbaijan", - "capital": "Baku", - "languages": [ - "Azerbaijani" - ], - "population": 10110116, - "flag": "https://flagcdn.com/az.svg", - "region": "Asia", - "area": 86600 - }, - { - "name": "Bahamas", - "capital": "Nassau", - "languages": [ - "English" - ], - "population": 393248, - "flag": "https://flagcdn.com/bs.svg", - "region": "Americas", - "area": 13943 - }, - { - "name": "Bahrain", - "capital": "Manama", - "languages": [ - "Arabic" - ], - "population": 1701583, - "flag": "https://flagcdn.com/bh.svg", - "region": "Asia", - "area": 765 - }, - { - "name": "Bangladesh", - "capital": "Dhaka", - "languages": [ - "Bengali" - ], - "population": 164689383, - "flag": "https://flagcdn.com/bd.svg", - "region": "Asia", - "area": 147570 - }, - { - "name": "Barbados", - "capital": "Bridgetown", - "languages": [ - "English" - ], - "population": 287371, - "flag": "https://flagcdn.com/bb.svg", - "region": "Americas", - "area": 430 - }, - { - "name": "Belarus", - "capital": "Minsk", - "languages": [ - "Belarusian", - "Russian" - ], - "population": 9398861, - "flag": "https://flagcdn.com/by.svg", - "region": "Europe", - "area": 207600 - }, - { - "name": "Belgium", - "capital": "Brussels", - "languages": [ - "Dutch", - "French", - "German" - ], - "population": 11555997, - "flag": "https://flagcdn.com/be.svg", - "region": "Europe", - "area": 30528 - }, - { - "name": "Belize", - "capital": "Belmopan", - "languages": [ - "English", - "Spanish" - ], - "population": 397621, - "flag": "https://flagcdn.com/bz.svg", - "region": "Americas", - "area": 22966 - }, - { - "name": "Benin", - "capital": "Porto-Novo", - "languages": [ - "French" - ], - "population": 12123198, - "flag": "https://flagcdn.com/bj.svg", - "region": "Africa", - "area": 112622 - }, - { - "name": "Bermuda", - "capital": "Hamilton", - "languages": [ - "English" - ], - "population": 63903, - "flag": "https://flagcdn.com/bm.svg", - "region": "Americas", - "area": 54 - }, - { - "name": "Bhutan", - "capital": "Thimphu", - "languages": [ - "Dzongkha" - ], - "population": 771612, - "flag": "https://flagcdn.com/bt.svg", - "region": "Asia", - "area": 38394 - }, - { - "name": "Bolivia (Plurinational State of)", - "capital": "Sucre", - "languages": [ - "Spanish", - "Aymara", - "Quechua" - ], - "population": 11673029, - "flag": "https://flagcdn.com/bo.svg", - "region": "Americas", - "area": 1098581 - }, - { - "name": "Bonaire, Sint Eustatius and Saba", - "capital": "Kralendijk", - "languages": [ - "Dutch" - ], - "population": 17408, - "flag": "https://flagcdn.com/bq.svg", - "region": "Americas", - "area": 294 - }, - { - "name": "Bosnia and Herzegovina", - "capital": "Sarajevo", - "languages": [ - "Bosnian", - "Croatian", - "Serbian" - ], - "population": 3280815, - "flag": "https://flagcdn.com/ba.svg", - "region": "Europe", - "area": 51209 - }, - { - "name": "Botswana", - "capital": "Gaborone", - "languages": [ - "English", - "Tswana" - ], - "population": 2351625, - "flag": "https://flagcdn.com/bw.svg", - "region": "Africa", - "area": 582000 - }, - { - "name": "Bouvet Island", - "languages": [ - "Norwegian", - "Norwegian Bokmål", - "Norwegian Nynorsk" - ], - "population": 0, - "flag": "https://flagcdn.com/bv.svg", - "region": "Antarctic Ocean", - "area": 49 - }, - { - "name": "Brazil", - "capital": "Brasília", - "languages": [ - "Portuguese" - ], - "population": 212559409, - "flag": "https://flagcdn.com/br.svg", - "region": "Americas", - "area": 8515767 - }, - { - "name": "British Indian Ocean Territory", - "capital": "Diego Garcia", - "languages": [ - "English" - ], - "population": 3000, - "flag": "https://flagcdn.com/io.svg", - "region": "Africa", - "area": 60 - }, - { - "name": "United States Minor Outlying Islands", - "languages": [ - "English" - ], - "population": 300, - "flag": "https://flagcdn.com/um.svg", - "region": "Americas" - }, - { - "name": "Virgin Islands (British)", - "capital": "Road Town", - "languages": [ - "English" - ], - "population": 30237, - "flag": "https://flagcdn.com/vg.svg", - "region": "Americas", - "area": 151 - }, - { - "name": "Virgin Islands (U.S.)", - "capital": "Charlotte Amalie", - "languages": [ - "English" - ], - "population": 106290, - "flag": "https://flagcdn.com/vi.svg", - "region": "Americas", - "area": 346.36 - }, - { - "name": "Brunei Darussalam", - "capital": "Bandar Seri Begawan", - "languages": [ - "Malay" - ], - "population": 437483, - "flag": "https://flagcdn.com/bn.svg", - "region": "Asia", - "area": 5765 - }, - { - "name": "Bulgaria", - "capital": "Sofia", - "languages": [ - "Bulgarian" - ], - "population": 6927288, - "flag": "https://flagcdn.com/bg.svg", - "region": "Europe", - "area": 110879 - }, - { - "name": "Burkina Faso", - "capital": "Ouagadougou", - "languages": [ - "French", - "Fula" - ], - "population": 20903278, - "flag": "https://flagcdn.com/bf.svg", - "region": "Africa", - "area": 272967 - }, - { - "name": "Burundi", - "capital": "Gitega", - "languages": [ - "French", - "Kirundi" - ], - "population": 11890781, - "flag": "https://flagcdn.com/bi.svg", - "region": "Africa", - "area": 27834 - }, - { - "name": "Cambodia", - "capital": "Phnom Penh", - "languages": [ - "Khmer" - ], - "population": 16718971, - "flag": "https://flagcdn.com/kh.svg", - "region": "Asia", - "area": 181035 - }, - { - "name": "Cameroon", - "capital": "Yaoundé", - "languages": [ - "English", - "French" - ], - "population": 26545864, - "flag": "https://flagcdn.com/cm.svg", - "region": "Africa", - "area": 475442 - }, - { - "name": "Canada", - "capital": "Ottawa", - "languages": [ - "English", - "French" - ], - "population": 38005238, - "flag": "https://flagcdn.com/ca.svg", - "region": "Americas", - "area": 9984670 - }, - { - "name": "Cabo Verde", - "capital": "Praia", - "languages": [ - "Portuguese" - ], - "population": 555988, - "flag": "https://flagcdn.com/cv.svg", - "region": "Africa", - "area": 4033 - }, - { - "name": "Cayman Islands", - "capital": "George Town", - "languages": [ - "English" - ], - "population": 65720, - "flag": "https://flagcdn.com/ky.svg", - "region": "Americas", - "area": 264 - }, - { - "name": "Central African Republic", - "capital": "Bangui", - "languages": [ - "French", - "Sango" - ], - "population": 4829764, - "flag": "https://flagcdn.com/cf.svg", - "region": "Africa", - "area": 622984 - }, - { - "name": "Chad", - "capital": "N'Djamena", - "languages": [ - "French", - "Arabic" - ], - "population": 16425859, - "flag": "https://flagcdn.com/td.svg", - "region": "Africa", - "area": 1284000 - }, - { - "name": "Chile", - "capital": "Santiago", - "languages": [ - "Spanish" - ], - "population": 19116209, - "flag": "https://flagcdn.com/cl.svg", - "region": "Americas", - "area": 756102 - }, - { - "name": "China", - "capital": "Beijing", - "languages": [ - "Chinese" - ], - "population": 1402112000, - "flag": "https://flagcdn.com/cn.svg", - "region": "Asia", - "area": 9640011 - }, - { - "name": "Christmas Island", - "capital": "Flying Fish Cove", - "languages": [ - "English" - ], - "population": 2072, - "flag": "https://flagcdn.com/cx.svg", - "region": "Oceania", - "area": 135 - }, - { - "name": "Cocos (Keeling) Islands", - "capital": "West Island", - "languages": [ - "English" - ], - "population": 550, - "flag": "https://flagcdn.com/cc.svg", - "region": "Oceania", - "area": 14 - }, - { - "name": "Colombia", - "capital": "Bogotá", - "languages": [ - "Spanish" - ], - "population": 50882884, - "flag": "https://flagcdn.com/co.svg", - "region": "Americas", - "area": 1141748 - }, - { - "name": "Comoros", - "capital": "Moroni", - "languages": [ - "Arabic", - "French" - ], - "population": 869595, - "flag": "https://flagcdn.com/km.svg", - "region": "Africa", - "area": 1862 - }, - { - "name": "Congo", - "capital": "Brazzaville", - "languages": [ - "French", - "Lingala" - ], - "population": 5518092, - "flag": "https://flagcdn.com/cg.svg", - "region": "Africa", - "area": 342000 - }, - { - "name": "Congo (Democratic Republic of the)", - "capital": "Kinshasa", - "languages": [ - "French", - "Lingala", - "Kongo", - "Swahili", - "Luba-Katanga" - ], - "population": 89561404, - "flag": "https://flagcdn.com/cd.svg", - "region": "Africa", - "area": 2344858 - }, - { - "name": "Cook Islands", - "capital": "Avarua", - "languages": [ - "English", - "Cook Islands Māori" - ], - "population": 18100, - "flag": "https://flagcdn.com/ck.svg", - "region": "Oceania", - "area": 236 - }, - { - "name": "Costa Rica", - "capital": "San José", - "languages": [ - "Spanish" - ], - "population": 5094114, - "flag": "https://flagcdn.com/cr.svg", - "region": "Americas", - "area": 51100 - }, - { - "name": "Croatia", - "capital": "Zagreb", - "languages": [ - "Croatian" - ], - "population": 4047200, - "flag": "https://flagcdn.com/hr.svg", - "region": "Europe", - "area": 56594 - }, - { - "name": "Cuba", - "capital": "Havana", - "languages": [ - "Spanish" - ], - "population": 11326616, - "flag": "https://flagcdn.com/cu.svg", - "region": "Americas", - "area": 109884 - }, - { - "name": "Curaçao", - "capital": "Willemstad", - "languages": [ - "Dutch", - "(Eastern) Punjabi", - "English" - ], - "population": 155014, - "flag": "https://flagcdn.com/cw.svg", - "region": "Americas", - "area": 444 - }, - { - "name": "Cyprus", - "capital": "Nicosia", - "languages": [ - "Greek (modern)", - "Turkish", - "Armenian" - ], - "population": 1207361, - "flag": "https://flagcdn.com/cy.svg", - "region": "Europe", - "area": 9251 - }, - { - "name": "Czech Republic", - "capital": "Prague", - "languages": [ - "Czech", - "Slovak" - ], - "population": 10698896, - "flag": "https://flagcdn.com/cz.svg", - "region": "Europe", - "area": 78865 - }, - { - "name": "Denmark", - "capital": "Copenhagen", - "languages": [ - "Danish" - ], - "population": 5831404, - "flag": "https://flagcdn.com/dk.svg", - "region": "Europe", - "area": 43094 - }, - { - "name": "Djibouti", - "capital": "Djibouti", - "languages": [ - "French", - "Arabic" - ], - "population": 988002, - "flag": "https://flagcdn.com/dj.svg", - "region": "Africa", - "area": 23200 - }, - { - "name": "Dominica", - "capital": "Roseau", - "languages": [ - "English" - ], - "population": 71991, - "flag": "https://flagcdn.com/dm.svg", - "region": "Americas", - "area": 751 - }, - { - "name": "Dominican Republic", - "capital": "Santo Domingo", - "languages": [ - "Spanish" - ], - "population": 10847904, - "flag": "https://flagcdn.com/do.svg", - "region": "Americas", - "area": 48671 - }, - { - "name": "Ecuador", - "capital": "Quito", - "languages": [ - "Spanish" - ], - "population": 17643060, - "flag": "https://flagcdn.com/ec.svg", - "region": "Americas", - "area": 276841 - }, - { - "name": "Egypt", - "capital": "Cairo", - "languages": [ - "Arabic" - ], - "population": 102334403, - "flag": "https://flagcdn.com/eg.svg", - "region": "Africa", - "area": 1002450 - }, - { - "name": "El Salvador", - "capital": "San Salvador", - "languages": [ - "Spanish" - ], - "population": 6486201, - "flag": "https://flagcdn.com/sv.svg", - "region": "Americas", - "area": 21041 - }, - { - "name": "Equatorial Guinea", - "capital": "Malabo", - "languages": [ - "Spanish", - "French", - "Portuguese", - "Fang" - ], - "population": 1402985, - "flag": "https://flagcdn.com/gq.svg", - "region": "Africa", - "area": 28051 - }, - { - "name": "Eritrea", - "capital": "Asmara", - "languages": [ - "Tigrinya", - "Arabic", - "English", - "Tigre", - "Kunama", - "Saho", - "Bilen", - "Nara", - "Afar" - ], - "population": 5352000, - "flag": "https://flagcdn.com/er.svg", - "region": "Africa", - "area": 117600 - }, - { - "name": "Estonia", - "capital": "Tallinn", - "languages": [ - "Estonian" - ], - "population": 1331057, - "flag": "https://flagcdn.com/ee.svg", - "region": "Europe", - "area": 45227 - }, - { - "name": "Ethiopia", - "capital": "Addis Ababa", - "languages": [ - "Amharic" - ], - "population": 114963583, - "flag": "https://flagcdn.com/et.svg", - "region": "Africa", - "area": 1104300 - }, - { - "name": "Falkland Islands (Malvinas)", - "capital": "Stanley", - "languages": [ - "English" - ], - "population": 2563, - "flag": "https://flagcdn.com/fk.svg", - "region": "Americas", - "area": 12173 - }, - { - "name": "Faroe Islands", - "capital": "Tórshavn", - "languages": [ - "Faroese" - ], - "population": 48865, - "flag": "https://flagcdn.com/fo.svg", - "region": "Europe", - "area": 1393 - }, - { - "name": "Fiji", - "capital": "Suva", - "languages": [ - "English", - "Fijian", - "Fiji Hindi", - "Rotuman" - ], - "population": 896444, - "flag": "https://flagcdn.com/fj.svg", - "region": "Oceania", - "area": 18272 - }, - { - "name": "Finland", - "capital": "Helsinki", - "languages": [ - "Finnish", - "Swedish" - ], - "population": 5530719, - "flag": "https://flagcdn.com/fi.svg", - "region": "Europe", - "area": 338424 - }, - { - "name": "France", - "capital": "Paris", - "languages": [ - "French" - ], - "population": 67391582, - "flag": "https://flagcdn.com/fr.svg", - "region": "Europe", - "area": 640679 - }, - { - "name": "French Guiana", - "capital": "Cayenne", - "languages": [ - "French" - ], - "population": 254541, - "flag": "https://flagcdn.com/gf.svg", - "region": "Americas" - }, - { - "name": "French Polynesia", - "capital": "Papeetē", - "languages": [ - "French" - ], - "population": 280904, - "flag": "https://flagcdn.com/pf.svg", - "region": "Oceania", - "area": 4167 - }, - { - "name": "French Southern Territories", - "capital": "Port-aux-Français", - "languages": [ - "French" - ], - "population": 140, - "flag": "https://flagcdn.com/tf.svg", - "region": "Africa", - "area": 7747 - }, - { - "name": "Gabon", - "capital": "Libreville", - "languages": [ - "French" - ], - "population": 2225728, - "flag": "https://flagcdn.com/ga.svg", - "region": "Africa", - "area": 267668 - }, - { - "name": "Gambia", - "capital": "Banjul", - "languages": [ - "English" - ], - "population": 2416664, - "flag": "https://flagcdn.com/gm.svg", - "region": "Africa", - "area": 11295 - }, - { - "name": "Georgia", - "capital": "Tbilisi", - "languages": [ - "Georgian" - ], - "population": 3714000, - "flag": "https://flagcdn.com/ge.svg", - "region": "Asia", - "area": 69700 - }, - { - "name": "Germany", - "capital": "Berlin", - "languages": [ - "German" - ], - "population": 83240525, - "flag": "https://flagcdn.com/de.svg", - "region": "Europe", - "area": 357114 - }, - { - "name": "Ghana", - "capital": "Accra", - "languages": [ - "English" - ], - "population": 31072945, - "flag": "https://flagcdn.com/gh.svg", - "region": "Africa", - "area": 238533 - }, - { - "name": "Gibraltar", - "capital": "Gibraltar", - "languages": [ - "English" - ], - "population": 33691, - "flag": "https://flagcdn.com/gi.svg", - "region": "Europe", - "area": 6 - }, - { - "name": "Greece", - "capital": "Athens", - "languages": [ - "Greek (modern)" - ], - "population": 10715549, - "flag": "https://flagcdn.com/gr.svg", - "region": "Europe", - "area": 131990 - }, - { - "name": "Greenland", - "capital": "Nuuk", - "languages": [ - "Kalaallisut" - ], - "population": 56367, - "flag": "https://flagcdn.com/gl.svg", - "region": "Americas", - "area": 2166086 - }, - { - "name": "Grenada", - "capital": "St. George's", - "languages": [ - "English" - ], - "population": 112519, - "flag": "https://flagcdn.com/gd.svg", - "region": "Americas", - "area": 344 - }, - { - "name": "Guadeloupe", - "capital": "Basse-Terre", - "languages": [ - "French" - ], - "population": 400132, - "flag": "https://flagcdn.com/gp.svg", - "region": "Americas" - }, - { - "name": "Guam", - "capital": "Hagåtña", - "languages": [ - "English", - "Chamorro", - "Spanish" - ], - "population": 168783, - "flag": "https://flagcdn.com/gu.svg", - "region": "Oceania", - "area": 549 - }, - { - "name": "Guatemala", - "capital": "Guatemala City", - "languages": [ - "Spanish" - ], - "population": 16858333, - "flag": "https://flagcdn.com/gt.svg", - "region": "Americas", - "area": 108889 - }, - { - "name": "Guernsey", - "capital": "St. Peter Port", - "languages": [ - "English", - "French" - ], - "population": 62999, - "flag": "https://flagcdn.com/gg.svg", - "region": "Europe", - "area": 78 - }, - { - "name": "Guinea", - "capital": "Conakry", - "languages": [ - "French", - "Fula" - ], - "population": 13132792, - "flag": "https://flagcdn.com/gn.svg", - "region": "Africa", - "area": 245857 - }, - { - "name": "Guinea-Bissau", - "capital": "Bissau", - "languages": [ - "Portuguese" - ], - "population": 1967998, - "flag": "https://flagcdn.com/gw.svg", - "region": "Africa", - "area": 36125 - }, - { - "name": "Guyana", - "capital": "Georgetown", - "languages": [ - "English" - ], - "population": 786559, - "flag": "https://flagcdn.com/gy.svg", - "region": "Americas", - "area": 214969 - }, - { - "name": "Haiti", - "capital": "Port-au-Prince", - "languages": [ - "French", - "Haitian" - ], - "population": 11402533, - "flag": "https://flagcdn.com/ht.svg", - "region": "Americas", - "area": 27750 - }, - { - "name": "Heard Island and McDonald Islands", - "languages": [ - "English" - ], - "population": 0, - "flag": "https://flagcdn.com/hm.svg", - "region": "Antarctic", - "area": 412 - }, - { - "name": "Vatican City", - "capital": "Vatican City", - "languages": [ - "Latin", - "Italian", - "French", - "German" - ], - "population": 451, - "flag": "https://flagcdn.com/va.svg", - "region": "Europe", - "area": 0.44 - }, - { - "name": "Honduras", - "capital": "Tegucigalpa", - "languages": [ - "Spanish" - ], - "population": 9904608, - "flag": "https://flagcdn.com/hn.svg", - "region": "Americas", - "area": 112492 - }, - { - "name": "Hungary", - "capital": "Budapest", - "languages": [ - "Hungarian" - ], - "population": 9749763, - "flag": "https://flagcdn.com/hu.svg", - "region": "Europe", - "area": 93028 - }, - { - "name": "Hong Kong", - "capital": "City of Victoria", - "languages": [ - "English", - "Chinese" - ], - "population": 7481800, - "flag": "https://flagcdn.com/hk.svg", - "region": "Asia", - "area": 1104 - }, - { - "name": "Iceland", - "capital": "Reykjavík", - "languages": [ - "Icelandic" - ], - "population": 366425, - "flag": "https://flagcdn.com/is.svg", - "region": "Europe", - "area": 103000 - }, - { - "name": "India", - "capital": "New Delhi", - "languages": [ - "Hindi", - "English" - ], - "population": 1380004385, - "flag": "https://flagcdn.com/in.svg", - "region": "Asia", - "area": 3287590 - }, - { - "name": "Indonesia", - "capital": "Jakarta", - "languages": [ - "Indonesian" - ], - "population": 273523621, - "flag": "https://flagcdn.com/id.svg", - "region": "Asia", - "area": 1904569 - }, - { - "name": "Ivory Coast", - "capital": "Yamoussoukro", - "languages": [ - "French" - ], - "population": 26378275, - "flag": "https://flagcdn.com/ci.svg", - "region": "Africa", - "area": 322463 - }, - { - "name": "Iran (Islamic Republic of)", - "capital": "Tehran", - "languages": [ - "Persian (Farsi)" - ], - "population": 83992953, - "flag": "https://flagcdn.com/ir.svg", - "region": "Asia", - "area": 1648195 - }, - { - "name": "Iraq", - "capital": "Baghdad", - "languages": [ - "Arabic", - "Kurdish" - ], - "population": 40222503, - "flag": "https://flagcdn.com/iq.svg", - "region": "Asia", - "area": 438317 - }, - { - "name": "Ireland", - "capital": "Dublin", - "languages": [ - "Irish", - "English" - ], - "population": 4994724, - "flag": "https://flagcdn.com/ie.svg", - "region": "Europe", - "area": 70273 - }, - { - "name": "Isle of Man", - "capital": "Douglas", - "languages": [ - "English", - "Manx" - ], - "population": 85032, - "flag": "https://flagcdn.com/im.svg", - "region": "Europe", - "area": 572 - }, - { - "name": "Israel", - "capital": "Jerusalem", - "languages": [ - "Hebrew (modern)", - "Arabic" - ], - "population": 9216900, - "flag": "https://flagcdn.com/il.svg", - "region": "Asia", - "area": 20770 - }, - { - "name": "Italy", - "capital": "Rome", - "languages": [ - "Italian" - ], - "population": 59554023, - "flag": "https://flagcdn.com/it.svg", - "region": "Europe", - "area": 301336 - }, - { - "name": "Jamaica", - "capital": "Kingston", - "languages": [ - "English" - ], - "population": 2961161, - "flag": "https://flagcdn.com/jm.svg", - "region": "Americas", - "area": 10991 - }, - { - "name": "Japan", - "capital": "Tokyo", - "languages": [ - "Japanese" - ], - "population": 125836021, - "flag": "https://flagcdn.com/jp.svg", - "region": "Asia", - "area": 377930 - }, - { - "name": "Jersey", - "capital": "Saint Helier", - "languages": [ - "English", - "French" - ], - "population": 100800, - "flag": "https://flagcdn.com/je.svg", - "region": "Europe", - "area": 116 - }, - { - "name": "Jordan", - "capital": "Amman", - "languages": [ - "Arabic" - ], - "population": 10203140, - "flag": "https://flagcdn.com/jo.svg", - "region": "Asia", - "area": 89342 - }, - { - "name": "Kazakhstan", - "capital": "Nur-Sultan", - "languages": [ - "Kazakh", - "Russian" - ], - "population": 18754440, - "flag": "https://flagcdn.com/kz.svg", - "region": "Asia", - "area": 2724900 - }, - { - "name": "Kenya", - "capital": "Nairobi", - "languages": [ - "English", - "Swahili" - ], - "population": 53771300, - "flag": "https://flagcdn.com/ke.svg", - "region": "Africa", - "area": 580367 - }, - { - "name": "Kiribati", - "capital": "South Tarawa", - "languages": [ - "English" - ], - "population": 119446, - "flag": "https://flagcdn.com/ki.svg", - "region": "Oceania", - "area": 811 - }, - { - "name": "Kuwait", - "capital": "Kuwait City", - "languages": [ - "Arabic" - ], - "population": 4270563, - "flag": "https://flagcdn.com/kw.svg", - "region": "Asia", - "area": 17818 - }, - { - "name": "Kyrgyzstan", - "capital": "Bishkek", - "languages": [ - "Kyrgyz", - "Russian" - ], - "population": 6591600, - "flag": "https://flagcdn.com/kg.svg", - "region": "Asia", - "area": 199951 - }, - { - "name": "Lao People's Democratic Republic", - "capital": "Vientiane", - "languages": [ - "Lao" - ], - "population": 7275556, - "flag": "https://flagcdn.com/la.svg", - "region": "Asia", - "area": 236800 - }, - { - "name": "Latvia", - "capital": "Riga", - "languages": [ - "Latvian" - ], - "population": 1901548, - "flag": "https://flagcdn.com/lv.svg", - "region": "Europe", - "area": 64559 - }, - { - "name": "Lebanon", - "capital": "Beirut", - "languages": [ - "Arabic", - "French" - ], - "population": 6825442, - "flag": "https://flagcdn.com/lb.svg", - "region": "Asia", - "area": 10452 - }, - { - "name": "Lesotho", - "capital": "Maseru", - "languages": [ - "English", - "Southern Sotho" - ], - "population": 2142252, - "flag": "https://flagcdn.com/ls.svg", - "region": "Africa", - "area": 30355 - }, - { - "name": "Liberia", - "capital": "Monrovia", - "languages": [ - "English" - ], - "population": 5057677, - "flag": "https://flagcdn.com/lr.svg", - "region": "Africa", - "area": 111369 - }, - { - "name": "Libya", - "capital": "Tripoli", - "languages": [ - "Arabic" - ], - "population": 6871287, - "flag": "https://flagcdn.com/ly.svg", - "region": "Africa", - "area": 1759540 - }, - { - "name": "Liechtenstein", - "capital": "Vaduz", - "languages": [ - "German" - ], - "population": 38137, - "flag": "https://flagcdn.com/li.svg", - "region": "Europe", - "area": 160 - }, - { - "name": "Lithuania", - "capital": "Vilnius", - "languages": [ - "Lithuanian" - ], - "population": 2794700, - "flag": "https://flagcdn.com/lt.svg", - "region": "Europe", - "area": 65300 - }, - { - "name": "Luxembourg", - "capital": "Luxembourg", - "languages": [ - "French", - "German", - "Luxembourgish" - ], - "population": 632275, - "flag": "https://flagcdn.com/lu.svg", - "region": "Europe", - "area": 2586 - }, - { - "name": "Macao", - "languages": [ - "Chinese", - "Portuguese" - ], - "population": 649342, - "flag": "https://flagcdn.com/mo.svg", - "region": "Asia", - "area": 30 - }, - { - "name": "North Macedonia", - "capital": "Skopje", - "languages": [ - "Macedonian" - ], - "population": 2083380, - "flag": "https://flagcdn.com/mk.svg", - "region": "Europe", - "area": 25713 - }, - { - "name": "Madagascar", - "capital": "Antananarivo", - "languages": [ - "French", - "Malagasy" - ], - "population": 27691019, - "flag": "https://flagcdn.com/mg.svg", - "region": "Africa", - "area": 587041 - }, - { - "name": "Malawi", - "capital": "Lilongwe", - "languages": [ - "English", - "Chichewa" - ], - "population": 19129955, - "flag": "https://flagcdn.com/mw.svg", - "region": "Africa", - "area": 118484 - }, - { - "name": "Malaysia", - "capital": "Kuala Lumpur", - "languages": [ - "Malaysian" - ], - "population": 32365998, - "flag": "https://flagcdn.com/my.svg", - "region": "Asia", - "area": 330803 - }, - { - "name": "Maldives", - "capital": "Malé", - "languages": [ - "Divehi" - ], - "population": 540542, - "flag": "https://flagcdn.com/mv.svg", - "region": "Asia", - "area": 300 - }, - { - "name": "Mali", - "capital": "Bamako", - "languages": [ - "French" - ], - "population": 20250834, - "flag": "https://flagcdn.com/ml.svg", - "region": "Africa", - "area": 1240192 - }, - { - "name": "Malta", - "capital": "Valletta", - "languages": [ - "Maltese", - "English" - ], - "population": 525285, - "flag": "https://flagcdn.com/mt.svg", - "region": "Europe", - "area": 316 - }, - { - "name": "Marshall Islands", - "capital": "Majuro", - "languages": [ - "English", - "Marshallese" - ], - "population": 59194, - "flag": "https://flagcdn.com/mh.svg", - "region": "Oceania", - "area": 181 - }, - { - "name": "Martinique", - "capital": "Fort-de-France", - "languages": [ - "French" - ], - "population": 378243, - "flag": "https://flagcdn.com/mq.svg", - "region": "Americas" - }, - { - "name": "Mauritania", - "capital": "Nouakchott", - "languages": [ - "Arabic" - ], - "population": 4649660, - "flag": "https://flagcdn.com/mr.svg", - "region": "Africa", - "area": 1030700 - }, - { - "name": "Mauritius", - "capital": "Port Louis", - "languages": [ - "English" - ], - "population": 1265740, - "flag": "https://flagcdn.com/mu.svg", - "region": "Africa", - "area": 2040 - }, - { - "name": "Mayotte", - "capital": "Mamoudzou", - "languages": [ - "French" - ], - "population": 226915, - "flag": "https://flagcdn.com/yt.svg", - "region": "Africa" - }, - { - "name": "Mexico", - "capital": "Mexico City", - "languages": [ - "Spanish" - ], - "population": 128932753, - "flag": "https://flagcdn.com/mx.svg", - "region": "Americas", - "area": 1964375 - }, - { - "name": "Micronesia (Federated States of)", - "capital": "Palikir", - "languages": [ - "English" - ], - "population": 115021, - "flag": "https://flagcdn.com/fm.svg", - "region": "Oceania", - "area": 702 - }, - { - "name": "Moldova (Republic of)", - "capital": "Chișinău", - "languages": [ - "Romanian" - ], - "population": 2617820, - "flag": "https://flagcdn.com/md.svg", - "region": "Europe", - "area": 33846 - }, - { - "name": "Monaco", - "capital": "Monaco", - "languages": [ - "French" - ], - "population": 39244, - "flag": "https://flagcdn.com/mc.svg", - "region": "Europe", - "area": 2.02 - }, - { - "name": "Mongolia", - "capital": "Ulan Bator", - "languages": [ - "Mongolian" - ], - "population": 3278292, - "flag": "https://flagcdn.com/mn.svg", - "region": "Asia", - "area": 1564110 - }, - { - "name": "Montenegro", - "capital": "Podgorica", - "languages": [ - "Serbian", - "Bosnian", - "Albanian", - "Croatian" - ], - "population": 621718, - "flag": "https://flagcdn.com/me.svg", - "region": "Europe", - "area": 13812 - }, - { - "name": "Montserrat", - "capital": "Plymouth", - "languages": [ - "English" - ], - "population": 4922, - "flag": "https://flagcdn.com/ms.svg", - "region": "Americas", - "area": 102 - }, - { - "name": "Morocco", - "capital": "Rabat", - "languages": [ - "Arabic" - ], - "population": 36910558, - "flag": "https://flagcdn.com/ma.svg", - "region": "Africa", - "area": 446550 - }, - { - "name": "Mozambique", - "capital": "Maputo", - "languages": [ - "Portuguese" - ], - "population": 31255435, - "flag": "https://flagcdn.com/mz.svg", - "region": "Africa", - "area": 801590 - }, - { - "name": "Myanmar", - "capital": "Naypyidaw", - "languages": [ - "Burmese" - ], - "population": 54409794, - "flag": "https://flagcdn.com/mm.svg", - "region": "Asia", - "area": 676578 - }, - { - "name": "Namibia", - "capital": "Windhoek", - "languages": [ - "English", - "Afrikaans" - ], - "population": 2540916, - "flag": "https://flagcdn.com/na.svg", - "region": "Africa", - "area": 825615 - }, - { - "name": "Nauru", - "capital": "Yaren", - "languages": [ - "English", - "Nauruan" - ], - "population": 10834, - "flag": "https://flagcdn.com/nr.svg", - "region": "Oceania", - "area": 21 - }, - { - "name": "Nepal", - "capital": "Kathmandu", - "languages": [ - "Nepali" - ], - "population": 29136808, - "flag": "https://flagcdn.com/np.svg", - "region": "Asia", - "area": 147181 - }, - { - "name": "Netherlands", - "capital": "Amsterdam", - "languages": [ - "Dutch" - ], - "population": 17441139, - "flag": "https://flagcdn.com/nl.svg", - "region": "Europe", - "area": 41850 - }, - { - "name": "New Caledonia", - "capital": "Nouméa", - "languages": [ - "French" - ], - "population": 271960, - "flag": "https://flagcdn.com/nc.svg", - "region": "Oceania", - "area": 18575 - }, - { - "name": "New Zealand", - "capital": "Wellington", - "languages": [ - "English", - "Māori" - ], - "population": 5084300, - "flag": "https://flagcdn.com/nz.svg", - "region": "Oceania", - "area": 270467 - }, - { - "name": "Nicaragua", - "capital": "Managua", - "languages": [ - "Spanish" - ], - "population": 6624554, - "flag": "https://flagcdn.com/ni.svg", - "region": "Americas", - "area": 130373 - }, - { - "name": "Niger", - "capital": "Niamey", - "languages": [ - "French" - ], - "population": 24206636, - "flag": "https://flagcdn.com/ne.svg", - "region": "Africa", - "area": 1267000 - }, - { - "name": "Nigeria", - "capital": "Abuja", - "languages": [ - "English" - ], - "population": 206139587, - "flag": "https://flagcdn.com/ng.svg", - "region": "Africa", - "area": 923768 - }, - { - "name": "Niue", - "capital": "Alofi", - "languages": [ - "English" - ], - "population": 1470, - "flag": "https://flagcdn.com/nu.svg", - "region": "Oceania", - "area": 260 - }, - { - "name": "Norfolk Island", - "capital": "Kingston", - "languages": [ - "English" - ], - "population": 2302, - "flag": "https://flagcdn.com/nf.svg", - "region": "Oceania", - "area": 36 - }, - { - "name": "Korea (Democratic People's Republic of)", - "capital": "Pyongyang", - "languages": [ - "Korean" - ], - "population": 25778815, - "flag": "https://flagcdn.com/kp.svg", - "region": "Asia", - "area": 120538 - }, - { - "name": "Northern Mariana Islands", - "capital": "Saipan", - "languages": [ - "English", - "Chamorro" - ], - "population": 57557, - "flag": "https://flagcdn.com/mp.svg", - "region": "Oceania", - "area": 464 - }, - { - "name": "Norway", - "capital": "Oslo", - "languages": [ - "Norwegian", - "Norwegian Bokmål", - "Norwegian Nynorsk" - ], - "population": 5379475, - "flag": "https://flagcdn.com/no.svg", - "region": "Europe", - "area": 323802 - }, - { - "name": "Oman", - "capital": "Muscat", - "languages": [ - "Arabic" - ], - "population": 5106622, - "flag": "https://flagcdn.com/om.svg", - "region": "Asia", - "area": 309500 - }, - { - "name": "Pakistan", - "capital": "Islamabad", - "languages": [ - "Urdu", - "English" - ], - "population": 220892331, - "flag": "https://flagcdn.com/pk.svg", - "region": "Asia", - "area": 881912 - }, - { - "name": "Palau", - "capital": "Ngerulmud", - "languages": [ - "English" - ], - "population": 18092, - "flag": "https://flagcdn.com/pw.svg", - "region": "Oceania", - "area": 459 - }, - { - "name": "Palestine, State of", - "capital": "Ramallah", - "languages": [ - "Arabic" - ], - "population": 4803269, - "flag": "https://flagcdn.com/ps.svg", - "region": "Asia" - }, - { - "name": "Panama", - "capital": "Panama City", - "languages": [ - "Spanish" - ], - "population": 4314768, - "flag": "https://flagcdn.com/pa.svg", - "region": "Americas", - "area": 75417 - }, - { - "name": "Papua New Guinea", - "capital": "Port Moresby", - "languages": [ - "English" - ], - "population": 8947027, - "flag": "https://flagcdn.com/pg.svg", - "region": "Oceania", - "area": 462840 - }, - { - "name": "Paraguay", - "capital": "Asunción", - "languages": [ - "Spanish", - "Guaraní" - ], - "population": 7132530, - "flag": "https://flagcdn.com/py.svg", - "region": "Americas", - "area": 406752 - }, - { - "name": "Peru", - "capital": "Lima", - "languages": [ - "Spanish" - ], - "population": 32971846, - "flag": "https://flagcdn.com/pe.svg", - "region": "Americas", - "area": 1285216 - }, - { - "name": "Philippines", - "capital": "Manila", - "languages": [ - "English" - ], - "population": 109581085, - "flag": "https://flagcdn.com/ph.svg", - "region": "Asia", - "area": 342353 - }, - { - "name": "Pitcairn", - "capital": "Adamstown", - "languages": [ - "English" - ], - "population": 56, - "flag": "https://flagcdn.com/pn.svg", - "region": "Oceania", - "area": 47 - }, - { - "name": "Poland", - "capital": "Warsaw", - "languages": [ - "Polish" - ], - "population": 37950802, - "flag": "https://flagcdn.com/pl.svg", - "region": "Europe", - "area": 312679 - }, - { - "name": "Portugal", - "capital": "Lisbon", - "languages": [ - "Portuguese" - ], - "population": 10305564, - "flag": "https://flagcdn.com/pt.svg", - "region": "Europe", - "area": 92090 - }, - { - "name": "Puerto Rico", - "capital": "San Juan", - "languages": [ - "Spanish", - "English" - ], - "population": 3194034, - "flag": "https://flagcdn.com/pr.svg", - "region": "Americas", - "area": 8870 - }, - { - "name": "Qatar", - "capital": "Doha", - "languages": [ - "Arabic" - ], - "population": 2881060, - "flag": "https://flagcdn.com/qa.svg", - "region": "Asia", - "area": 11586 - }, - { - "name": "Republic of Kosovo", - "capital": "Pristina", - "languages": [ - "Albanian", - "Serbian" - ], - "population": 1775378, - "flag": "https://flagcdn.com/xk.svg", - "region": "Europe", - "area": 10908 - }, - { - "name": "Réunion", - "capital": "Saint-Denis", - "languages": [ - "French" - ], - "population": 840974, - "flag": "https://flagcdn.com/re.svg", - "region": "Africa" - }, - { - "name": "Romania", - "capital": "Bucharest", - "languages": [ - "Romanian" - ], - "population": 19286123, - "flag": "https://flagcdn.com/ro.svg", - "region": "Europe", - "area": 238391 - }, - { - "name": "Russian Federation", - "capital": "Moscow", - "languages": [ - "Russian" - ], - "population": 144104080, - "flag": "https://flagcdn.com/ru.svg", - "region": "Europe", - "area": 17124442 - }, - { - "name": "Rwanda", - "capital": "Kigali", - "languages": [ - "Kinyarwanda", - "English", - "French" - ], - "population": 12952209, - "flag": "https://flagcdn.com/rw.svg", - "region": "Africa", - "area": 26338 - }, - { - "name": "Saint Barthélemy", - "capital": "Gustavia", - "languages": [ - "French" - ], - "population": 9417, - "flag": "https://flagcdn.com/bl.svg", - "region": "Americas", - "area": 21 - }, - { - "name": "Saint Helena, Ascension and Tristan da Cunha", - "capital": "Jamestown", - "languages": [ - "English" - ], - "population": 4255, - "flag": "https://flagcdn.com/sh.svg", - "region": "Africa" - }, - { - "name": "Saint Kitts and Nevis", - "capital": "Basseterre", - "languages": [ - "English" - ], - "population": 53192, - "flag": "https://flagcdn.com/kn.svg", - "region": "Americas", - "area": 261 - }, - { - "name": "Saint Lucia", - "capital": "Castries", - "languages": [ - "English" - ], - "population": 183629, - "flag": "https://flagcdn.com/lc.svg", - "region": "Americas", - "area": 616 - }, - { - "name": "Saint Martin (French part)", - "capital": "Marigot", - "languages": [ - "English", - "French", - "Dutch" - ], - "population": 38659, - "flag": "https://flagcdn.com/mf.svg", - "region": "Americas", - "area": 53 - }, - { - "name": "Saint Pierre and Miquelon", - "capital": "Saint-Pierre", - "languages": [ - "French" - ], - "population": 6069, - "flag": "https://flagcdn.com/pm.svg", - "region": "Americas", - "area": 242 - }, - { - "name": "Saint Vincent and the Grenadines", - "capital": "Kingstown", - "languages": [ - "English" - ], - "population": 110947, - "flag": "https://flagcdn.com/vc.svg", - "region": "Americas", - "area": 389 - }, - { - "name": "Samoa", - "capital": "Apia", - "languages": [ - "Samoan", - "English" - ], - "population": 198410, - "flag": "https://flagcdn.com/ws.svg", - "region": "Oceania", - "area": 2842 - }, - { - "name": "San Marino", - "capital": "City of San Marino", - "languages": [ - "Italian" - ], - "population": 33938, - "flag": "https://flagcdn.com/sm.svg", - "region": "Europe", - "area": 61 - }, - { - "name": "Sao Tome and Principe", - "capital": "São Tomé", - "languages": [ - "Portuguese" - ], - "population": 219161, - "flag": "https://flagcdn.com/st.svg", - "region": "Africa", - "area": 964 - }, - { - "name": "Saudi Arabia", - "capital": "Riyadh", - "languages": [ - "Arabic" - ], - "population": 34813867, - "flag": "https://flagcdn.com/sa.svg", - "region": "Asia", - "area": 2149690 - }, - { - "name": "Senegal", - "capital": "Dakar", - "languages": [ - "French" - ], - "population": 16743930, - "flag": "https://flagcdn.com/sn.svg", - "region": "Africa", - "area": 196722 - }, - { - "name": "Serbia", - "capital": "Belgrade", - "languages": [ - "Serbian" - ], - "population": 6908224, - "flag": "https://flagcdn.com/rs.svg", - "region": "Europe", - "area": 88361 - }, - { - "name": "Seychelles", - "capital": "Victoria", - "languages": [ - "French", - "English" - ], - "population": 98462, - "flag": "https://flagcdn.com/sc.svg", - "region": "Africa", - "area": 452 - }, - { - "name": "Sierra Leone", - "capital": "Freetown", - "languages": [ - "English" - ], - "population": 7976985, - "flag": "https://flagcdn.com/sl.svg", - "region": "Africa", - "area": 71740 - }, - { - "name": "Singapore", - "capital": "Singapore", - "languages": [ - "English", - "Malay", - "Tamil", - "Chinese" - ], - "population": 5685807, - "flag": "https://flagcdn.com/sg.svg", - "region": "Asia", - "area": 710 - }, - { - "name": "Sint Maarten (Dutch part)", - "capital": "Philipsburg", - "languages": [ - "Dutch", - "English" - ], - "population": 40812, - "flag": "https://flagcdn.com/sx.svg", - "region": "Americas", - "area": 34 - }, - { - "name": "Slovakia", - "capital": "Bratislava", - "languages": [ - "Slovak" - ], - "population": 5458827, - "flag": "https://flagcdn.com/sk.svg", - "region": "Europe", - "area": 49037 - }, - { - "name": "Slovenia", - "capital": "Ljubljana", - "languages": [ - "Slovene" - ], - "population": 2100126, - "flag": "https://flagcdn.com/si.svg", - "region": "Europe", - "area": 20273 - }, - { - "name": "Solomon Islands", - "capital": "Honiara", - "languages": [ - "English" - ], - "population": 686878, - "flag": "https://flagcdn.com/sb.svg", - "region": "Oceania", - "area": 28896 - }, - { - "name": "Somalia", - "capital": "Mogadishu", - "languages": [ - "Somali", - "Arabic" - ], - "population": 15893219, - "flag": "https://flagcdn.com/so.svg", - "region": "Africa", - "area": 637657 - }, - { - "name": "South Africa", - "capital": "Pretoria", - "languages": [ - "Afrikaans", - "English", - "Southern Ndebele", - "Southern Sotho", - "Swati", - "Tswana", - "Tsonga", - "Venda", - "Xhosa", - "Zulu" - ], - "population": 59308690, - "flag": "https://flagcdn.com/za.svg", - "region": "Africa", - "area": 1221037 - }, - { - "name": "South Georgia and the South Sandwich Islands", - "capital": "King Edward Point", - "languages": [ - "English" - ], - "population": 30, - "flag": "https://flagcdn.com/gs.svg", - "region": "Americas" - }, - { - "name": "Korea (Republic of)", - "capital": "Seoul", - "languages": [ - "Korean" - ], - "population": 51780579, - "flag": "https://flagcdn.com/kr.svg", - "region": "Asia", - "area": 100210 - }, - { - "name": "Spain", - "capital": "Madrid", - "languages": [ - "Spanish" - ], - "population": 47351567, - "flag": "https://flagcdn.com/es.svg", - "region": "Europe", - "area": 505992 - }, - { - "name": "Sri Lanka", - "capital": "Sri Jayawardenepura Kotte", - "languages": [ - "Sinhalese", - "Tamil" - ], - "population": 21919000, - "flag": "https://flagcdn.com/lk.svg", - "region": "Asia", - "area": 65610 - }, - { - "name": "Sudan", - "capital": "Khartoum", - "languages": [ - "Arabic", - "English" - ], - "population": 43849269, - "flag": "https://flagcdn.com/sd.svg", - "region": "Africa", - "area": 1886068 - }, - { - "name": "South Sudan", - "capital": "Juba", - "languages": [ - "English" - ], - "population": 11193729, - "flag": "https://flagcdn.com/ss.svg", - "region": "Africa", - "area": 619745 - }, - { - "name": "Suriname", - "capital": "Paramaribo", - "languages": [ - "Dutch" - ], - "population": 586634, - "flag": "https://flagcdn.com/sr.svg", - "region": "Americas", - "area": 163820 - }, - { - "name": "Svalbard and Jan Mayen", - "capital": "Longyearbyen", - "languages": [ - "Norwegian" - ], - "population": 2562, - "flag": "https://flagcdn.com/sj.svg", - "region": "Europe" - }, - { - "name": "Swaziland", - "capital": "Mbabane", - "languages": [ - "English", - "Swati" - ], - "population": 1160164, - "flag": "https://flagcdn.com/sz.svg", - "region": "Africa", - "area": 17364 - }, - { - "name": "Sweden", - "capital": "Stockholm", - "languages": [ - "Swedish" - ], - "population": 10353442, - "flag": "https://flagcdn.com/se.svg", - "region": "Europe", - "area": 450295 - }, - { - "name": "Switzerland", - "capital": "Bern", - "languages": [ - "German", - "French", - "Italian", - "Romansh" - ], - "population": 8636896, - "flag": "https://flagcdn.com/ch.svg", - "region": "Europe", - "area": 41284 - }, - { - "name": "Syrian Arab Republic", - "capital": "Damascus", - "languages": [ - "Arabic" - ], - "population": 17500657, - "flag": "https://flagcdn.com/sy.svg", - "region": "Asia", - "area": 185180 - }, - { - "name": "Taiwan", - "capital": "Taipei", - "languages": [ - "Chinese" - ], - "population": 23503349, - "flag": "https://flagcdn.com/tw.svg", - "region": "Asia", - "area": 36193 - }, - { - "name": "Tajikistan", - "capital": "Dushanbe", - "languages": [ - "Tajik", - "Russian" - ], - "population": 9537642, - "flag": "https://flagcdn.com/tj.svg", - "region": "Asia", - "area": 143100 - }, - { - "name": "Tanzania, United Republic of", - "capital": "Dodoma", - "languages": [ - "Swahili", - "English" - ], - "population": 59734213, - "flag": "https://flagcdn.com/tz.svg", - "region": "Africa", - "area": 945087 - }, - { - "name": "Thailand", - "capital": "Bangkok", - "languages": [ - "Thai" - ], - "population": 69799978, - "flag": "https://flagcdn.com/th.svg", - "region": "Asia", - "area": 513120 - }, - { - "name": "Timor-Leste", - "capital": "Dili", - "languages": [ - "Portuguese" - ], - "population": 1318442, - "flag": "https://flagcdn.com/tl.svg", - "region": "Asia", - "area": 14874 - }, - { - "name": "Togo", - "capital": "Lomé", - "languages": [ - "French" - ], - "population": 8278737, - "flag": "https://flagcdn.com/tg.svg", - "region": "Africa", - "area": 56785 - }, - { - "name": "Tokelau", - "capital": "Fakaofo", - "languages": [ - "English" - ], - "population": 1411, - "flag": "https://flagcdn.com/tk.svg", - "region": "Oceania", - "area": 12 - }, - { - "name": "Tonga", - "capital": "Nuku'alofa", - "languages": [ - "English", - "Tonga (Tonga Islands)" - ], - "population": 105697, - "flag": "https://flagcdn.com/to.svg", - "region": "Oceania", - "area": 747 - }, - { - "name": "Trinidad and Tobago", - "capital": "Port of Spain", - "languages": [ - "English" - ], - "population": 1399491, - "flag": "https://flagcdn.com/tt.svg", - "region": "Americas", - "area": 5130 - }, - { - "name": "Tunisia", - "capital": "Tunis", - "languages": [ - "Arabic" - ], - "population": 11818618, - "flag": "https://flagcdn.com/tn.svg", - "region": "Africa", - "area": 163610 - }, - { - "name": "Turkey", - "capital": "Ankara", - "languages": [ - "Turkish" - ], - "population": 84339067, - "flag": "https://flagcdn.com/tr.svg", - "region": "Asia", - "area": 783562 - }, - { - "name": "Turkmenistan", - "capital": "Ashgabat", - "languages": [ - "Turkmen", - "Russian" - ], - "population": 6031187, - "flag": "https://flagcdn.com/tm.svg", - "region": "Asia", - "area": 488100 - }, - { - "name": "Turks and Caicos Islands", - "capital": "Cockburn Town", - "languages": [ - "English" - ], - "population": 38718, - "flag": "https://flagcdn.com/tc.svg", - "region": "Americas", - "area": 948 - }, - { - "name": "Tuvalu", - "capital": "Funafuti", - "languages": [ - "English" - ], - "population": 11792, - "flag": "https://flagcdn.com/tv.svg", - "region": "Oceania", - "area": 26 - }, - { - "name": "Uganda", - "capital": "Kampala", - "languages": [ - "English", - "Swahili" - ], - "population": 45741000, - "flag": "https://flagcdn.com/ug.svg", - "region": "Africa", - "area": 241550 - }, - { - "name": "Ukraine", - "capital": "Kyiv", - "languages": [ - "Ukrainian" - ], - "population": 44134693, - "flag": "https://flagcdn.com/ua.svg", - "region": "Europe", - "area": 603700 - }, - { - "name": "United Arab Emirates", - "capital": "Abu Dhabi", - "languages": [ - "Arabic" - ], - "population": 9890400, - "flag": "https://flagcdn.com/ae.svg", - "region": "Asia", - "area": 83600 - }, - { - "name": "United Kingdom of Great Britain and Northern Ireland", - "capital": "London", - "languages": [ - "English" - ], - "population": 67215293, - "flag": "https://flagcdn.com/gb.svg", - "region": "Europe", - "area": 242900 - }, - { - "name": "United States of America", - "capital": "Washington, D.C.", - "languages": [ - "English" - ], - "population": 329484123, - "flag": "https://flagcdn.com/us.svg", - "region": "Americas", - "area": 9629091 - }, - { - "name": "Uruguay", - "capital": "Montevideo", - "languages": [ - "Spanish" - ], - "population": 3473727, - "flag": "https://flagcdn.com/uy.svg", - "region": "Americas", - "area": 181034 - }, - { - "name": "Uzbekistan", - "capital": "Tashkent", - "languages": [ - "Uzbek", - "Russian" - ], - "population": 34232050, - "flag": "https://flagcdn.com/uz.svg", - "region": "Asia", - "area": 447400 - }, - { - "name": "Vanuatu", - "capital": "Port Vila", - "languages": [ - "Bislama", - "English", - "French" - ], - "population": 307150, - "flag": "https://flagcdn.com/vu.svg", - "region": "Oceania", - "area": 12189 - }, - { - "name": "Venezuela (Bolivarian Republic of)", - "capital": "Caracas", - "languages": [ - "Spanish" - ], - "population": 28435943, - "flag": "https://flagcdn.com/ve.svg", - "region": "Americas", - "area": 916445 - }, - { - "name": "Vietnam", - "capital": "Hanoi", - "languages": [ - "Vietnamese" - ], - "population": 97338583, - "flag": "https://flagcdn.com/vn.svg", - "region": "Asia", - "area": 331212 - }, - { - "name": "Wallis and Futuna", - "capital": "Mata-Utu", - "languages": [ - "French" - ], - "population": 11750, - "flag": "https://flagcdn.com/wf.svg", - "region": "Oceania", - "area": 142 - }, - { - "name": "Western Sahara", - "capital": "El Aaiún", - "languages": [ - "Spanish" - ], - "population": 510713, - "flag": "https://flagcdn.com/eh.svg", - "region": "Africa", - "area": 266000 - }, - { - "name": "Yemen", - "capital": "Sana'a", - "languages": [ - "Arabic" - ], - "population": 29825968, - "flag": "https://flagcdn.com/ye.svg", - "region": "Asia", - "area": 527968 - }, - { - "name": "Zambia", - "capital": "Lusaka", - "languages": [ - "English" - ], - "population": 18383956, - "flag": "https://flagcdn.com/zm.svg", - "region": "Africa", - "area": 752618 - }, - { - "name": "Zimbabwe", - "capital": "Harare", - "languages": [ - "English", - "Shona", - "Northern Ndebele" - ], - "population": 14862927, - "flag": "https://flagcdn.com/zw.svg", - "region": "Africa", - "area": 390757 - } -] \ No newline at end of file diff --git a/data/countries_data_old.js b/data/countries_data_old.js deleted file mode 100644 index 92acddd..0000000 --- a/data/countries_data_old.js +++ /dev/null @@ -1,2013 +0,0 @@ -const countries = [ - { - name: 'Afghanistan', - capital: 'Kabul', - languages: ['Pashto', 'Uzbek', 'Turkmen'], - population: 27657145, - flag: 'https://restcountries.eu/data/afg.svg', - currency: 'Afghan afghani' - }, - { - name: 'Åland Islands', - capital: 'Mariehamn', - languages: ['Swedish'], - population: 28875, - flag: 'https://restcountries.eu/data/ala.svg', - currency: 'Euro' - }, - { - name: 'Albania', - capital: 'Tirana', - languages: ['Albanian'], - population: 2886026, - flag: 'https://restcountries.eu/data/alb.svg', - currency: 'Albanian lek' - }, - { - name: 'Algeria', - capital: 'Algiers', - languages: ['Arabic'], - population: 40400000, - flag: 'https://restcountries.eu/data/dza.svg', - currency: 'Algerian dinar' - }, - { - name: 'American Samoa', - capital: 'Pago Pago', - languages: ['English', 'Samoan'], - population: 57100, - flag: 'https://restcountries.eu/data/asm.svg', - currency: 'United State Dollar' - }, - { - name: 'Andorra', - capital: 'Andorra la Vella', - languages: ['Catalan'], - population: 78014, - flag: 'https://restcountries.eu/data/and.svg', - currency: 'Euro' - }, - { - name: 'Angola', - capital: 'Luanda', - languages: ['Portuguese'], - population: 25868000, - flag: 'https://restcountries.eu/data/ago.svg', - currency: 'Angolan kwanza' - }, - { - name: 'Anguilla', - capital: 'The Valley', - languages: ['English'], - population: 13452, - flag: 'https://restcountries.eu/data/aia.svg', - currency: 'East Caribbean dollar' - }, - { - name: 'Antarctica', - capital: '', - languages: ['English', 'Russian'], - population: 1000, - flag: 'https://restcountries.eu/data/ata.svg', - currency: 'Australian dollar' - }, - { - name: 'Antigua and Barbuda', - capital: "Saint John's", - languages: ['English'], - population: 86295, - flag: 'https://restcountries.eu/data/atg.svg', - currency: 'East Caribbean dollar' - }, - { - name: 'Argentina', - capital: 'Buenos Aires', - languages: ['Spanish', 'Guaraní'], - population: 43590400, - flag: 'https://restcountries.eu/data/arg.svg', - currency: 'Argentine peso' - }, - { - name: 'Armenia', - capital: 'Yerevan', - languages: ['Armenian', 'Russian'], - population: 2994400, - flag: 'https://restcountries.eu/data/arm.svg', - currency: 'Armenian dram' - }, - { - name: 'Aruba', - capital: 'Oranjestad', - languages: ['Dutch', '(Eastern) Punjabi'], - population: 107394, - flag: 'https://restcountries.eu/data/abw.svg', - currency: 'Aruban florin' - }, - { - name: 'Australia', - capital: 'Canberra', - languages: ['English'], - population: 24117360, - flag: 'https://restcountries.eu/data/aus.svg', - currency: 'Australian dollar' - }, - { - name: 'Austria', - capital: 'Vienna', - languages: ['German'], - population: 8725931, - flag: 'https://restcountries.eu/data/aut.svg', - currency: 'Euro' - }, - { - name: 'Azerbaijan', - capital: 'Baku', - languages: ['Azerbaijani'], - population: 9730500, - flag: 'https://restcountries.eu/data/aze.svg', - currency: 'Azerbaijani manat' - }, - { - name: 'Bahamas', - capital: 'Nassau', - languages: ['English'], - population: 378040, - flag: 'https://restcountries.eu/data/bhs.svg', - currency: 'Bahamian dollar' - }, - { - name: 'Bahrain', - capital: 'Manama', - languages: ['Arabic'], - population: 1404900, - flag: 'https://restcountries.eu/data/bhr.svg', - currency: 'Bahraini dinar' - }, - { - name: 'Bangladesh', - capital: 'Dhaka', - languages: ['Bengali'], - population: 161006790, - flag: 'https://restcountries.eu/data/bgd.svg', - currency: 'Bangladeshi taka' - }, - { - name: 'Barbados', - capital: 'Bridgetown', - languages: ['English'], - population: 285000, - flag: 'https://restcountries.eu/data/brb.svg', - currency: 'Barbadian dollar' - }, - { - name: 'Belarus', - capital: 'Minsk', - languages: ['Belarusian', 'Russian'], - population: 9498700, - flag: 'https://restcountries.eu/data/blr.svg', - currency: 'New Belarusian ruble' - }, - { - name: 'Belgium', - capital: 'Brussels', - languages: ['Dutch', 'French', 'German'], - population: 11319511, - flag: 'https://restcountries.eu/data/bel.svg', - currency: 'Euro' - }, - { - name: 'Belize', - capital: 'Belmopan', - languages: ['English', 'Spanish'], - population: 370300, - flag: 'https://restcountries.eu/data/blz.svg', - currency: 'Belize dollar' - }, - { - name: 'Benin', - capital: 'Porto-Novo', - languages: ['French'], - population: 10653654, - flag: 'https://restcountries.eu/data/ben.svg', - currency: 'West African CFA franc' - }, - { - name: 'Bermuda', - capital: 'Hamilton', - languages: ['English'], - population: 61954, - flag: 'https://restcountries.eu/data/bmu.svg', - currency: 'Bermudian dollar' - }, - { - name: 'Bhutan', - capital: 'Thimphu', - languages: ['Dzongkha'], - population: 775620, - flag: 'https://restcountries.eu/data/btn.svg', - currency: 'Bhutanese ngultrum' - }, - { - name: 'Bolivia (Plurinational State of)', - capital: 'Sucre', - languages: ['Spanish', 'Aymara', 'Quechua'], - population: 10985059, - flag: 'https://restcountries.eu/data/bol.svg', - currency: 'Bolivian boliviano' - }, - { - name: 'Bonaire, Sint Eustatius and Saba', - capital: 'Kralendijk', - languages: ['Dutch'], - population: 17408, - flag: 'https://restcountries.eu/data/bes.svg', - currency: 'United States dollar' - }, - { - name: 'Bosnia and Herzegovina', - capital: 'Sarajevo', - languages: ['Bosnian', 'Croatian', 'Serbian'], - population: 3531159, - flag: 'https://restcountries.eu/data/bih.svg', - currency: 'Bosnia and Herzegovina convertible mark' - }, - { - name: 'Botswana', - capital: 'Gaborone', - languages: ['English', 'Tswana'], - population: 2141206, - flag: 'https://restcountries.eu/data/bwa.svg', - currency: 'Botswana pula' - }, - { - name: 'Bouvet Island', - capital: '', - languages: ['Norwegian', 'Norwegian Bokmål', 'Norwegian Nynorsk'], - population: 0, - flag: 'https://restcountries.eu/data/bvt.svg', - currency: 'Norwegian krone' - }, - { - name: 'Brazil', - capital: 'Brasília', - languages: ['Portuguese'], - population: 206135893, - flag: 'https://restcountries.eu/data/bra.svg', - currency: 'Brazilian real' - }, - { - name: 'British Indian Ocean Territory', - capital: 'Diego Garcia', - languages: ['English'], - population: 3000, - flag: 'https://restcountries.eu/data/iot.svg', - currency: 'United States dollar' - }, - { - name: 'United States Minor Outlying Islands', - capital: '', - languages: ['English'], - population: 300, - flag: 'https://restcountries.eu/data/umi.svg', - currency: 'United States Dollar' - }, - { - name: 'Virgin Islands (British)', - capital: 'Road Town', - languages: ['English'], - population: 28514, - flag: 'https://restcountries.eu/data/vgb.svg', - currency: '[D]' - }, - { - name: 'Virgin Islands (U.S.)', - capital: 'Charlotte Amalie', - languages: ['English'], - population: 114743, - flag: 'https://restcountries.eu/data/vir.svg', - currency: 'United States dollar' - }, - { - name: 'Brunei Darussalam', - capital: 'Bandar Seri Begawan', - languages: ['Malay'], - population: 411900, - flag: 'https://restcountries.eu/data/brn.svg', - currency: 'Brunei dollar' - }, - { - name: 'Bulgaria', - capital: 'Sofia', - languages: ['Bulgarian'], - population: 7153784, - flag: 'https://restcountries.eu/data/bgr.svg', - currency: 'Bulgarian lev' - }, - { - name: 'Burkina Faso', - capital: 'Ouagadougou', - languages: ['French', 'Fula'], - population: 19034397, - flag: 'https://restcountries.eu/data/bfa.svg', - currency: 'West African CFA franc' - }, - { - name: 'Burundi', - capital: 'Bujumbura', - languages: ['French', 'Kirundi'], - population: 10114505, - flag: 'https://restcountries.eu/data/bdi.svg', - currency: 'Burundian franc' - }, - { - name: 'Cambodia', - capital: 'Phnom Penh', - languages: ['Khmer'], - population: 15626444, - flag: 'https://restcountries.eu/data/khm.svg', - currency: 'Cambodian riel' - }, - { - name: 'Cameroon', - capital: 'Yaoundé', - languages: ['English', 'French'], - population: 22709892, - flag: 'https://restcountries.eu/data/cmr.svg', - currency: 'Central African CFA franc' - }, - { - name: 'Canada', - capital: 'Ottawa', - languages: ['English', 'French'], - population: 36155487, - flag: 'https://restcountries.eu/data/can.svg', - currency: 'Canadian dollar' - }, - { - name: 'Cabo Verde', - capital: 'Praia', - languages: ['Portuguese'], - population: 531239, - flag: 'https://restcountries.eu/data/cpv.svg', - currency: 'Cape Verdean escudo' - }, - { - name: 'Cayman Islands', - capital: 'George Town', - languages: ['English'], - population: 58238, - flag: 'https://restcountries.eu/data/cym.svg', - currency: 'Cayman Islands dollar' - }, - { - name: 'Central African Republic', - capital: 'Bangui', - languages: ['French', 'Sango'], - population: 4998000, - flag: 'https://restcountries.eu/data/caf.svg', - currency: 'Central African CFA franc' - }, - { - name: 'Chad', - capital: "N'Djamena", - languages: ['French', 'Arabic'], - population: 14497000, - flag: 'https://restcountries.eu/data/tcd.svg', - currency: 'Central African CFA franc' - }, - { - name: 'Chile', - capital: 'Santiago', - languages: ['Spanish'], - population: 18191900, - flag: 'https://restcountries.eu/data/chl.svg', - currency: 'Chilean peso' - }, - { - name: 'China', - capital: 'Beijing', - languages: ['Chinese'], - population: 1377422166, - flag: 'https://restcountries.eu/data/chn.svg', - currency: 'Chinese yuan' - }, - { - name: 'Christmas Island', - capital: 'Flying Fish Cove', - languages: ['English'], - population: 2072, - flag: 'https://restcountries.eu/data/cxr.svg', - currency: 'Australian dollar' - }, - { - name: 'Cocos (Keeling) Islands', - capital: 'West Island', - languages: ['English'], - population: 550, - flag: 'https://restcountries.eu/data/cck.svg', - currency: 'Australian dollar' - }, - { - name: 'Colombia', - capital: 'Bogotá', - languages: ['Spanish'], - population: 48759958, - flag: 'https://restcountries.eu/data/col.svg', - currency: 'Colombian peso' - }, - { - name: 'Comoros', - capital: 'Moroni', - languages: ['Arabic', 'French'], - population: 806153, - flag: 'https://restcountries.eu/data/com.svg', - currency: 'Comorian franc' - }, - { - name: 'Congo', - capital: 'Brazzaville', - languages: ['French', 'Lingala'], - population: 4741000, - flag: 'https://restcountries.eu/data/cog.svg', - currency: 'Central African CFA franc' - }, - { - name: 'Congo (Democratic Republic of the)', - capital: 'Kinshasa', - languages: ['French', 'Lingala', 'Kongo', 'Swahili', 'Luba-Katanga'], - population: 85026000, - flag: 'https://restcountries.eu/data/cod.svg', - currency: 'Congolese franc' - }, - { - name: 'Cook Islands', - capital: 'Avarua', - languages: ['English'], - population: 18100, - flag: 'https://restcountries.eu/data/cok.svg', - currency: 'New Zealand dollar' - }, - { - name: 'Costa Rica', - capital: 'San José', - languages: ['Spanish'], - population: 4890379, - flag: 'https://restcountries.eu/data/cri.svg', - currency: 'Costa Rican colón' - }, - { - name: 'Croatia', - capital: 'Zagreb', - languages: ['Croatian'], - population: 4190669, - flag: 'https://restcountries.eu/data/hrv.svg', - currency: 'Croatian kuna' - }, - { - name: 'Cuba', - capital: 'Havana', - languages: ['Spanish'], - population: 11239004, - flag: 'https://restcountries.eu/data/cub.svg', - currency: 'Cuban convertible peso' - }, - { - name: 'Curaçao', - capital: 'Willemstad', - languages: ['Dutch', '(Eastern) Punjabi', 'English'], - population: 154843, - flag: 'https://restcountries.eu/data/cuw.svg', - currency: 'Netherlands Antillean guilder' - }, - { - name: 'Cyprus', - capital: 'Nicosia', - languages: ['Greek (modern)', 'Turkish', 'Armenian'], - population: 847000, - flag: 'https://restcountries.eu/data/cyp.svg', - currency: 'Euro' - }, - { - name: 'Czech Republic', - capital: 'Prague', - languages: ['Czech', 'Slovak'], - population: 10558524, - flag: 'https://restcountries.eu/data/cze.svg', - currency: 'Czech koruna' - }, - { - name: 'Denmark', - capital: 'Copenhagen', - languages: ['Danish'], - population: 5717014, - flag: 'https://restcountries.eu/data/dnk.svg', - currency: 'Danish krone' - }, - { - name: 'Djibouti', - capital: 'Djibouti', - languages: ['French', 'Arabic'], - population: 900000, - flag: 'https://restcountries.eu/data/dji.svg', - currency: 'Djiboutian franc' - }, - { - name: 'Dominica', - capital: 'Roseau', - languages: ['English'], - population: 71293, - flag: 'https://restcountries.eu/data/dma.svg', - currency: 'East Caribbean dollar' - }, - { - name: 'Dominican Republic', - capital: 'Santo Domingo', - languages: ['Spanish'], - population: 10075045, - flag: 'https://restcountries.eu/data/dom.svg', - currency: 'Dominican peso' - }, - { - name: 'Ecuador', - capital: 'Quito', - languages: ['Spanish'], - population: 16545799, - flag: 'https://restcountries.eu/data/ecu.svg', - currency: 'United States dollar' - }, - { - name: 'Egypt', - capital: 'Cairo', - languages: ['Arabic'], - population: 91290000, - flag: 'https://restcountries.eu/data/egy.svg', - currency: 'Egyptian pound' - }, - { - name: 'El Salvador', - capital: 'San Salvador', - languages: ['Spanish'], - population: 6520675, - flag: 'https://restcountries.eu/data/slv.svg', - currency: 'United States dollar' - }, - { - name: 'Equatorial Guinea', - capital: 'Malabo', - languages: ['Spanish', 'French'], - population: 1222442, - flag: 'https://restcountries.eu/data/gnq.svg', - currency: 'Central African CFA franc' - }, - { - name: 'Eritrea', - capital: 'Asmara', - languages: ['Tigrinya', 'Arabic', 'English'], - population: 5352000, - flag: 'https://restcountries.eu/data/eri.svg', - currency: 'Eritrean nakfa' - }, - { - name: 'Estonia', - capital: 'Tallinn', - languages: ['Estonian'], - population: 1315944, - flag: 'https://restcountries.eu/data/est.svg', - currency: 'Euro' - }, - { - name: 'Ethiopia', - capital: 'Addis Ababa', - languages: ['Amharic'], - population: 92206005, - flag: 'https://restcountries.eu/data/eth.svg', - currency: 'Ethiopian birr' - }, - { - name: 'Falkland Islands (Malvinas)', - capital: 'Stanley', - languages: ['English'], - population: 2563, - flag: 'https://restcountries.eu/data/flk.svg', - currency: 'Falkland Islands pound' - }, - { - name: 'Faroe Islands', - capital: 'Tórshavn', - languages: ['Faroese'], - population: 49376, - flag: 'https://restcountries.eu/data/fro.svg', - currency: 'Danish krone' - }, - { - name: 'Fiji', - capital: 'Suva', - languages: ['English', 'Fijian', 'Hindi', 'Urdu'], - population: 867000, - flag: 'https://restcountries.eu/data/fji.svg', - currency: 'Fijian dollar' - }, - { - name: 'Finland', - capital: 'Helsinki', - languages: ['Finnish', 'Swedish'], - population: 5491817, - flag: 'https://restcountries.eu/data/fin.svg', - currency: 'Euro' - }, - { - name: 'France', - capital: 'Paris', - languages: ['French'], - population: 66710000, - flag: 'https://restcountries.eu/data/fra.svg', - currency: 'Euro' - }, - { - name: 'French Guiana', - capital: 'Cayenne', - languages: ['French'], - population: 254541, - flag: 'https://restcountries.eu/data/guf.svg', - currency: 'Euro' - }, - { - name: 'French Polynesia', - capital: 'Papeetē', - languages: ['French'], - population: 271800, - flag: 'https://restcountries.eu/data/pyf.svg', - currency: 'CFP franc' - }, - { - name: 'French Southern Territories', - capital: 'Port-aux-Français', - languages: ['French'], - population: 140, - flag: 'https://restcountries.eu/data/atf.svg', - currency: 'Euro' - }, - { - name: 'Gabon', - capital: 'Libreville', - languages: ['French'], - population: 1802278, - flag: 'https://restcountries.eu/data/gab.svg', - currency: 'Central African CFA franc' - }, - { - name: 'Gambia', - capital: 'Banjul', - languages: ['English'], - population: 1882450, - flag: 'https://restcountries.eu/data/gmb.svg', - currency: 'Gambian dalasi' - }, - { - name: 'Georgia', - capital: 'Tbilisi', - languages: ['Georgian'], - population: 3720400, - flag: 'https://restcountries.eu/data/geo.svg', - currency: 'Georgian Lari' - }, - { - name: 'Germany', - capital: 'Berlin', - languages: ['German'], - population: 81770900, - flag: 'https://restcountries.eu/data/deu.svg', - currency: 'Euro' - }, - { - name: 'Ghana', - capital: 'Accra', - languages: ['English'], - population: 27670174, - flag: 'https://restcountries.eu/data/gha.svg', - currency: 'Ghanaian cedi' - }, - { - name: 'Gibraltar', - capital: 'Gibraltar', - languages: ['English'], - population: 33140, - flag: 'https://restcountries.eu/data/gib.svg', - currency: 'Gibraltar pound' - }, - { - name: 'Greece', - capital: 'Athens', - languages: ['Greek (modern)'], - population: 10858018, - flag: 'https://restcountries.eu/data/grc.svg', - currency: 'Euro' - }, - { - name: 'Greenland', - capital: 'Nuuk', - languages: ['Kalaallisut'], - population: 55847, - flag: 'https://restcountries.eu/data/grl.svg', - currency: 'Danish krone' - }, - { - name: 'Grenada', - capital: "St. George's", - languages: ['English'], - population: 103328, - flag: 'https://restcountries.eu/data/grd.svg', - currency: 'East Caribbean dollar' - }, - { - name: 'Guadeloupe', - capital: 'Basse-Terre', - languages: ['French'], - population: 400132, - flag: 'https://restcountries.eu/data/glp.svg', - currency: 'Euro' - }, - { - name: 'Guam', - capital: 'Hagåtña', - languages: ['English', 'Chamorro', 'Spanish'], - population: 184200, - flag: 'https://restcountries.eu/data/gum.svg', - currency: 'United States dollar' - }, - { - name: 'Guatemala', - capital: 'Guatemala City', - languages: ['Spanish'], - population: 16176133, - flag: 'https://restcountries.eu/data/gtm.svg', - currency: 'Guatemalan quetzal' - }, - { - name: 'Guernsey', - capital: 'St. Peter Port', - languages: ['English', 'French'], - population: 62999, - flag: 'https://restcountries.eu/data/ggy.svg', - currency: 'British pound' - }, - { - name: 'Guinea', - capital: 'Conakry', - languages: ['French', 'Fula'], - population: 12947000, - flag: 'https://restcountries.eu/data/gin.svg', - currency: 'Guinean franc' - }, - { - name: 'Guinea-Bissau', - capital: 'Bissau', - languages: ['Portuguese'], - population: 1547777, - flag: 'https://restcountries.eu/data/gnb.svg', - currency: 'West African CFA franc' - }, - { - name: 'Guyana', - capital: 'Georgetown', - languages: ['English'], - population: 746900, - flag: 'https://restcountries.eu/data/guy.svg', - currency: 'Guyanese dollar' - }, - { - name: 'Haiti', - capital: 'Port-au-Prince', - languages: ['French', 'Haitian'], - population: 11078033, - flag: 'https://restcountries.eu/data/hti.svg', - currency: 'Haitian gourde' - }, - { - name: 'Heard Island and McDonald Islands', - capital: '', - languages: ['English'], - population: 0, - flag: 'https://restcountries.eu/data/hmd.svg', - currency: 'Australian dollar' - }, - { - name: 'Holy See', - capital: 'Rome', - languages: ['Latin', 'Italian', 'French', 'German'], - population: 451, - flag: 'https://restcountries.eu/data/vat.svg', - currency: 'Euro' - }, - { - name: 'Honduras', - capital: 'Tegucigalpa', - languages: ['Spanish'], - population: 8576532, - flag: 'https://restcountries.eu/data/hnd.svg', - currency: 'Honduran lempira' - }, - { - name: 'Hong Kong', - capital: 'City of Victoria', - languages: ['English', 'Chinese'], - population: 7324300, - flag: 'https://restcountries.eu/data/hkg.svg', - currency: 'Hong Kong dollar' - }, - { - name: 'Hungary', - capital: 'Budapest', - languages: ['Hungarian'], - population: 9823000, - flag: 'https://restcountries.eu/data/hun.svg', - currency: 'Hungarian forint' - }, - { - name: 'Iceland', - capital: 'Reykjavík', - languages: ['Icelandic'], - population: 334300, - flag: 'https://restcountries.eu/data/isl.svg', - currency: 'Icelandic króna' - }, - { - name: 'India', - capital: 'New Delhi', - languages: ['Hindi', 'English'], - population: 1295210000, - flag: 'https://restcountries.eu/data/ind.svg', - currency: 'Indian rupee' - }, - { - name: 'Indonesia', - capital: 'Jakarta', - languages: ['Indonesian'], - population: 258705000, - flag: 'https://restcountries.eu/data/idn.svg', - currency: 'Indonesian rupiah' - }, - { - name: "Côte d'Ivoire", - capital: 'Yamoussoukro', - languages: ['French'], - population: 22671331, - flag: 'https://restcountries.eu/data/civ.svg', - currency: 'West African CFA franc' - }, - { - name: 'Iran (Islamic Republic of)', - capital: 'Tehran', - languages: ['Persian (Farsi)'], - population: 79369900, - flag: 'https://restcountries.eu/data/irn.svg', - currency: 'Iranian rial' - }, - { - name: 'Iraq', - capital: 'Baghdad', - languages: ['Arabic', 'Kurdish'], - population: 37883543, - flag: 'https://restcountries.eu/data/irq.svg', - currency: 'Iraqi dinar' - }, - { - name: 'Ireland', - capital: 'Dublin', - languages: ['Irish', 'English'], - population: 6378000, - flag: 'https://restcountries.eu/data/irl.svg', - currency: 'Euro' - }, - { - name: 'Isle of Man', - capital: 'Douglas', - languages: ['English', 'Manx'], - population: 84497, - flag: 'https://restcountries.eu/data/imn.svg', - currency: 'British pound' - }, - { - name: 'Israel', - capital: 'Jerusalem', - languages: ['Hebrew (modern)', 'Arabic'], - population: 8527400, - flag: 'https://restcountries.eu/data/isr.svg', - currency: 'Israeli new shekel' - }, - { - name: 'Italy', - capital: 'Rome', - languages: ['Italian'], - population: 60665551, - flag: 'https://restcountries.eu/data/ita.svg', - currency: 'Euro' - }, - { - name: 'Jamaica', - capital: 'Kingston', - languages: ['English'], - population: 2723246, - flag: 'https://restcountries.eu/data/jam.svg', - currency: 'Jamaican dollar' - }, - { - name: 'Japan', - capital: 'Tokyo', - languages: ['Japanese'], - population: 126960000, - flag: 'https://restcountries.eu/data/jpn.svg', - currency: 'Japanese yen' - }, - { - name: 'Jersey', - capital: 'Saint Helier', - languages: ['English', 'French'], - population: 100800, - flag: 'https://restcountries.eu/data/jey.svg', - currency: 'British pound' - }, - { - name: 'Jordan', - capital: 'Amman', - languages: ['Arabic'], - population: 9531712, - flag: 'https://restcountries.eu/data/jor.svg', - currency: 'Jordanian dinar' - }, - { - name: 'Kazakhstan', - capital: 'Astana', - languages: ['Kazakh', 'Russian'], - population: 17753200, - flag: 'https://restcountries.eu/data/kaz.svg', - currency: 'Kazakhstani tenge' - }, - { - name: 'Kenya', - capital: 'Nairobi', - languages: ['English', 'Swahili'], - population: 47251000, - flag: 'https://restcountries.eu/data/ken.svg', - currency: 'Kenyan shilling' - }, - { - name: 'Kiribati', - capital: 'South Tarawa', - languages: ['English'], - population: 113400, - flag: 'https://restcountries.eu/data/kir.svg', - currency: 'Australian dollar' - }, - { - name: 'Kuwait', - capital: 'Kuwait City', - languages: ['Arabic'], - population: 4183658, - flag: 'https://restcountries.eu/data/kwt.svg', - currency: 'Kuwaiti dinar' - }, - { - name: 'Kyrgyzstan', - capital: 'Bishkek', - languages: ['Kyrgyz', 'Russian'], - population: 6047800, - flag: 'https://restcountries.eu/data/kgz.svg', - currency: 'Kyrgyzstani som' - }, - { - name: "Lao People's Democratic Republic", - capital: 'Vientiane', - languages: ['Lao'], - population: 6492400, - flag: 'https://restcountries.eu/data/lao.svg', - currency: 'Lao kip' - }, - { - name: 'Latvia', - capital: 'Riga', - languages: ['Latvian'], - population: 1961600, - flag: 'https://restcountries.eu/data/lva.svg', - currency: 'Euro' - }, - { - name: 'Lebanon', - capital: 'Beirut', - languages: ['Arabic', 'French'], - population: 5988000, - flag: 'https://restcountries.eu/data/lbn.svg', - currency: 'Lebanese pound' - }, - { - name: 'Lesotho', - capital: 'Maseru', - languages: ['English', 'Southern Sotho'], - population: 1894194, - flag: 'https://restcountries.eu/data/lso.svg', - currency: 'Lesotho loti' - }, - { - name: 'Liberia', - capital: 'Monrovia', - languages: ['English'], - population: 4615000, - flag: 'https://restcountries.eu/data/lbr.svg', - currency: 'Liberian dollar' - }, - { - name: 'Libya', - capital: 'Tripoli', - languages: ['Arabic'], - population: 6385000, - flag: 'https://restcountries.eu/data/lby.svg', - currency: 'Libyan dinar' - }, - { - name: 'Liechtenstein', - capital: 'Vaduz', - languages: ['German'], - population: 37623, - flag: 'https://restcountries.eu/data/lie.svg', - currency: 'Swiss franc' - }, - { - name: 'Lithuania', - capital: 'Vilnius', - languages: ['Lithuanian'], - population: 2872294, - flag: 'https://restcountries.eu/data/ltu.svg', - currency: 'Euro' - }, - { - name: 'Luxembourg', - capital: 'Luxembourg', - languages: ['French', 'German', 'Luxembourgish'], - population: 576200, - flag: 'https://restcountries.eu/data/lux.svg', - currency: 'Euro' - }, - { - name: 'Macao', - capital: '', - languages: ['Chinese', 'Portuguese'], - population: 649100, - flag: 'https://restcountries.eu/data/mac.svg', - currency: 'Macanese pataca' - }, - { - name: 'Macedonia (the former Yugoslav Republic of)', - capital: 'Skopje', - languages: ['Macedonian'], - population: 2058539, - flag: 'https://restcountries.eu/data/mkd.svg', - currency: 'Macedonian denar' - }, - { - name: 'Madagascar', - capital: 'Antananarivo', - languages: ['French', 'Malagasy'], - population: 22434363, - flag: 'https://restcountries.eu/data/mdg.svg', - currency: 'Malagasy ariary' - }, - { - name: 'Malawi', - capital: 'Lilongwe', - languages: ['English', 'Chichewa'], - population: 16832910, - flag: 'https://restcountries.eu/data/mwi.svg', - currency: 'Malawian kwacha' - }, - { - name: 'Malaysia', - capital: 'Kuala Lumpur', - languages: ['Malaysian'], - population: 31405416, - flag: 'https://restcountries.eu/data/mys.svg', - currency: 'Malaysian ringgit' - }, - { - name: 'Maldives', - capital: 'Malé', - languages: ['Divehi'], - population: 344023, - flag: 'https://restcountries.eu/data/mdv.svg', - currency: 'Maldivian rufiyaa' - }, - { - name: 'Mali', - capital: 'Bamako', - languages: ['French'], - population: 18135000, - flag: 'https://restcountries.eu/data/mli.svg', - currency: 'West African CFA franc' - }, - { - name: 'Malta', - capital: 'Valletta', - languages: ['Maltese', 'English'], - population: 425384, - flag: 'https://restcountries.eu/data/mlt.svg', - currency: 'Euro' - }, - { - name: 'Marshall Islands', - capital: 'Majuro', - languages: ['English', 'Marshallese'], - population: 54880, - flag: 'https://restcountries.eu/data/mhl.svg', - currency: 'United States dollar' - }, - { - name: 'Martinique', - capital: 'Fort-de-France', - languages: ['French'], - population: 378243, - flag: 'https://restcountries.eu/data/mtq.svg', - currency: 'Euro' - }, - { - name: 'Mauritania', - capital: 'Nouakchott', - languages: ['Arabic'], - population: 3718678, - flag: 'https://restcountries.eu/data/mrt.svg', - currency: 'Mauritanian ouguiya' - }, - { - name: 'Mauritius', - capital: 'Port Louis', - languages: ['English'], - population: 1262879, - flag: 'https://restcountries.eu/data/mus.svg', - currency: 'Mauritian rupee' - }, - { - name: 'Mayotte', - capital: 'Mamoudzou', - languages: ['French'], - population: 226915, - flag: 'https://restcountries.eu/data/myt.svg', - currency: 'Euro' - }, - { - name: 'Mexico', - capital: 'Mexico City', - languages: ['Spanish'], - population: 122273473, - flag: 'https://restcountries.eu/data/mex.svg', - currency: 'Mexican peso' - }, - { - name: 'Micronesia (Federated States of)', - capital: 'Palikir', - languages: ['English'], - population: 102800, - flag: 'https://restcountries.eu/data/fsm.svg', - currency: '[D]' - }, - { - name: 'Moldova (Republic of)', - capital: 'Chișinău', - languages: ['Romanian'], - population: 3553100, - flag: 'https://restcountries.eu/data/mda.svg', - currency: 'Moldovan leu' - }, - { - name: 'Monaco', - capital: 'Monaco', - languages: ['French'], - population: 38400, - flag: 'https://restcountries.eu/data/mco.svg', - currency: 'Euro' - }, - { - name: 'Mongolia', - capital: 'Ulan Bator', - languages: ['Mongolian'], - population: 3093100, - flag: 'https://restcountries.eu/data/mng.svg', - currency: 'Mongolian tögrög' - }, - { - name: 'Montenegro', - capital: 'Podgorica', - languages: ['Serbian', 'Bosnian', 'Albanian', 'Croatian'], - population: 621810, - flag: 'https://restcountries.eu/data/mne.svg', - currency: 'Euro' - }, - { - name: 'Montserrat', - capital: 'Plymouth', - languages: ['English'], - population: 4922, - flag: 'https://restcountries.eu/data/msr.svg', - currency: 'East Caribbean dollar' - }, - { - name: 'Morocco', - capital: 'Rabat', - languages: ['Arabic'], - population: 33337529, - flag: 'https://restcountries.eu/data/mar.svg', - currency: 'Moroccan dirham' - }, - { - name: 'Mozambique', - capital: 'Maputo', - languages: ['Portuguese'], - population: 26423700, - flag: 'https://restcountries.eu/data/moz.svg', - currency: 'Mozambican metical' - }, - { - name: 'Myanmar', - capital: 'Naypyidaw', - languages: ['Burmese'], - population: 51419420, - flag: 'https://restcountries.eu/data/mmr.svg', - currency: 'Burmese kyat' - }, - { - name: 'Namibia', - capital: 'Windhoek', - languages: ['English', 'Afrikaans'], - population: 2324388, - flag: 'https://restcountries.eu/data/nam.svg', - currency: 'Namibian dollar' - }, - { - name: 'Nauru', - capital: 'Yaren', - languages: ['English', 'Nauruan'], - population: 10084, - flag: 'https://restcountries.eu/data/nru.svg', - currency: 'Australian dollar' - }, - { - name: 'Nepal', - capital: 'Kathmandu', - languages: ['Nepali'], - population: 28431500, - flag: 'https://restcountries.eu/data/npl.svg', - currency: 'Nepalese rupee' - }, - { - name: 'Netherlands', - capital: 'Amsterdam', - languages: ['Dutch'], - population: 17019800, - flag: 'https://restcountries.eu/data/nld.svg', - currency: 'Euro' - }, - { - name: 'New Caledonia', - capital: 'Nouméa', - languages: ['French'], - population: 268767, - flag: 'https://restcountries.eu/data/ncl.svg', - currency: 'CFP franc' - }, - { - name: 'New Zealand', - capital: 'Wellington', - languages: ['English', 'Māori'], - population: 4697854, - flag: 'https://restcountries.eu/data/nzl.svg', - currency: 'New Zealand dollar' - }, - { - name: 'Nicaragua', - capital: 'Managua', - languages: ['Spanish'], - population: 6262703, - flag: 'https://restcountries.eu/data/nic.svg', - currency: 'Nicaraguan córdoba' - }, - { - name: 'Niger', - capital: 'Niamey', - languages: ['French'], - population: 20715000, - flag: 'https://restcountries.eu/data/ner.svg', - currency: 'West African CFA franc' - }, - { - name: 'Nigeria', - capital: 'Abuja', - languages: ['English'], - population: 186988000, - flag: 'https://restcountries.eu/data/nga.svg', - currency: 'Nigerian naira' - }, - { - name: 'Niue', - capital: 'Alofi', - languages: ['English'], - population: 1470, - flag: 'https://restcountries.eu/data/niu.svg', - currency: 'New Zealand dollar' - }, - { - name: 'Norfolk Island', - capital: 'Kingston', - languages: ['English'], - population: 2302, - flag: 'https://restcountries.eu/data/nfk.svg', - currency: 'Australian dollar' - }, - { - name: "Korea (Democratic People's Republic of)", - capital: 'Pyongyang', - languages: ['Korean'], - population: 25281000, - flag: 'https://restcountries.eu/data/prk.svg', - currency: 'North Korean won' - }, - { - name: 'Northern Mariana Islands', - capital: 'Saipan', - languages: ['English', 'Chamorro'], - population: 56940, - flag: 'https://restcountries.eu/data/mnp.svg', - currency: 'United States dollar' - }, - { - name: 'Norway', - capital: 'Oslo', - languages: ['Norwegian', 'Norwegian Bokmål', 'Norwegian Nynorsk'], - population: 5223256, - flag: 'https://restcountries.eu/data/nor.svg', - currency: 'Norwegian krone' - }, - { - name: 'Oman', - capital: 'Muscat', - languages: ['Arabic'], - population: 4420133, - flag: 'https://restcountries.eu/data/omn.svg', - currency: 'Omani rial' - }, - { - name: 'Pakistan', - capital: 'Islamabad', - languages: ['English', 'Urdu'], - population: 194125062, - flag: 'https://restcountries.eu/data/pak.svg', - currency: 'Pakistani rupee' - }, - { - name: 'Palau', - capital: 'Ngerulmud', - languages: ['English'], - population: 17950, - flag: 'https://restcountries.eu/data/plw.svg', - currency: '[E]' - }, - { - name: 'Palestine, State of', - capital: 'Ramallah', - languages: ['Arabic'], - population: 4682467, - flag: 'https://restcountries.eu/data/pse.svg', - currency: 'Israeli new sheqel' - }, - { - name: 'Panama', - capital: 'Panama City', - languages: ['Spanish'], - population: 3814672, - flag: 'https://restcountries.eu/data/pan.svg', - currency: 'Panamanian balboa' - }, - { - name: 'Papua New Guinea', - capital: 'Port Moresby', - languages: ['English'], - population: 8083700, - flag: 'https://restcountries.eu/data/png.svg', - currency: 'Papua New Guinean kina' - }, - { - name: 'Paraguay', - capital: 'Asunción', - languages: ['Spanish', 'Guaraní'], - population: 6854536, - flag: 'https://restcountries.eu/data/pry.svg', - currency: 'Paraguayan guaraní' - }, - { - name: 'Peru', - capital: 'Lima', - languages: ['Spanish'], - population: 31488700, - flag: 'https://restcountries.eu/data/per.svg', - currency: 'Peruvian sol' - }, - { - name: 'Philippines', - capital: 'Manila', - languages: ['English'], - population: 103279800, - flag: 'https://restcountries.eu/data/phl.svg', - currency: 'Philippine peso' - }, - { - name: 'Pitcairn', - capital: 'Adamstown', - languages: ['English'], - population: 56, - flag: 'https://restcountries.eu/data/pcn.svg', - currency: 'New Zealand dollar' - }, - { - name: 'Poland', - capital: 'Warsaw', - languages: ['Polish'], - population: 38437239, - flag: 'https://restcountries.eu/data/pol.svg', - currency: 'Polish złoty' - }, - { - name: 'Portugal', - capital: 'Lisbon', - languages: ['Portuguese'], - population: 10374822, - flag: 'https://restcountries.eu/data/prt.svg', - currency: 'Euro' - }, - { - name: 'Puerto Rico', - capital: 'San Juan', - languages: ['Spanish', 'English'], - population: 3474182, - flag: 'https://restcountries.eu/data/pri.svg', - currency: 'United States dollar' - }, - { - name: 'Qatar', - capital: 'Doha', - languages: ['Arabic'], - population: 2587564, - flag: 'https://restcountries.eu/data/qat.svg', - currency: 'Qatari riyal' - }, - { - name: 'Republic of Kosovo', - capital: 'Pristina', - languages: ['Albanian', 'Serbian'], - population: 1733842, - flag: 'https://restcountries.eu/data/kos.svg', - currency: 'Euro' - }, - { - name: 'Réunion', - capital: 'Saint-Denis', - languages: ['French'], - population: 840974, - flag: 'https://restcountries.eu/data/reu.svg', - currency: 'Euro' - }, - { - name: 'Romania', - capital: 'Bucharest', - languages: ['Romanian'], - population: 19861408, - flag: 'https://restcountries.eu/data/rou.svg', - currency: 'Romanian leu' - }, - { - name: 'Russian Federation', - capital: 'Moscow', - languages: ['Russian'], - population: 146599183, - flag: 'https://restcountries.eu/data/rus.svg', - currency: 'Russian ruble' - }, - { - name: 'Rwanda', - capital: 'Kigali', - languages: ['Kinyarwanda', 'English', 'French'], - population: 11553188, - flag: 'https://restcountries.eu/data/rwa.svg', - currency: 'Rwandan franc' - }, - { - name: 'Saint Barthélemy', - capital: 'Gustavia', - languages: ['French'], - population: 9417, - flag: 'https://restcountries.eu/data/blm.svg', - currency: 'Euro' - }, - { - name: 'Saint Helena, Ascension and Tristan da Cunha', - capital: 'Jamestown', - languages: ['English'], - population: 4255, - flag: 'https://restcountries.eu/data/shn.svg', - currency: 'Saint Helena pound' - }, - { - name: 'Saint Kitts and Nevis', - capital: 'Basseterre', - languages: ['English'], - population: 46204, - flag: 'https://restcountries.eu/data/kna.svg', - currency: 'East Caribbean dollar' - }, - { - name: 'Saint Lucia', - capital: 'Castries', - languages: ['English'], - population: 186000, - flag: 'https://restcountries.eu/data/lca.svg', - currency: 'East Caribbean dollar' - }, - { - name: 'Saint Martin (French part)', - capital: 'Marigot', - languages: ['English', 'French', 'Dutch'], - population: 36979, - flag: 'https://restcountries.eu/data/maf.svg', - currency: 'Euro' - }, - { - name: 'Saint Pierre and Miquelon', - capital: 'Saint-Pierre', - languages: ['French'], - population: 6069, - flag: 'https://restcountries.eu/data/spm.svg', - currency: 'Euro' - }, - { - name: 'Saint Vincent and the Grenadines', - capital: 'Kingstown', - languages: ['English'], - population: 109991, - flag: 'https://restcountries.eu/data/vct.svg', - currency: 'East Caribbean dollar' - }, - { - name: 'Samoa', - capital: 'Apia', - languages: ['Samoan', 'English'], - population: 194899, - flag: 'https://restcountries.eu/data/wsm.svg', - currency: 'Samoan tālā' - }, - { - name: 'San Marino', - capital: 'City of San Marino', - languages: ['Italian'], - population: 33005, - flag: 'https://restcountries.eu/data/smr.svg', - currency: 'Euro' - }, - { - name: 'Sao Tome and Principe', - capital: 'São Tomé', - languages: ['Portuguese'], - population: 187356, - flag: 'https://restcountries.eu/data/stp.svg', - currency: 'São Tomé and Príncipe dobra' - }, - { - name: 'Saudi Arabia', - capital: 'Riyadh', - languages: ['Arabic'], - population: 32248200, - flag: 'https://restcountries.eu/data/sau.svg', - currency: 'Saudi riyal' - }, - { - name: 'Senegal', - capital: 'Dakar', - languages: ['French'], - population: 14799859, - flag: 'https://restcountries.eu/data/sen.svg', - currency: 'West African CFA franc' - }, - { - name: 'Serbia', - capital: 'Belgrade', - languages: ['Serbian'], - population: 7076372, - flag: 'https://restcountries.eu/data/srb.svg', - currency: 'Serbian dinar' - }, - { - name: 'Seychelles', - capital: 'Victoria', - languages: ['French', 'English'], - population: 91400, - flag: 'https://restcountries.eu/data/syc.svg', - currency: 'Seychellois rupee' - }, - { - name: 'Sierra Leone', - capital: 'Freetown', - languages: ['English'], - population: 7075641, - flag: 'https://restcountries.eu/data/sle.svg', - currency: 'Sierra Leonean leone' - }, - { - name: 'Singapore', - capital: 'Singapore', - languages: ['English', 'Malay', 'Tamil', 'Chinese'], - population: 5535000, - flag: 'https://restcountries.eu/data/sgp.svg', - currency: 'Brunei dollar' - }, - { - name: 'Sint Maarten (Dutch part)', - capital: 'Philipsburg', - languages: ['Dutch', 'English'], - population: 38247, - flag: 'https://restcountries.eu/data/sxm.svg', - currency: 'Netherlands Antillean guilder' - }, - { - name: 'Slovakia', - capital: 'Bratislava', - languages: ['Slovak'], - population: 5426252, - flag: 'https://restcountries.eu/data/svk.svg', - currency: 'Euro' - }, - { - name: 'Slovenia', - capital: 'Ljubljana', - languages: ['Slovene'], - population: 2064188, - flag: 'https://restcountries.eu/data/svn.svg', - currency: 'Euro' - }, - { - name: 'Solomon Islands', - capital: 'Honiara', - languages: ['English'], - population: 642000, - flag: 'https://restcountries.eu/data/slb.svg', - currency: 'Solomon Islands dollar' - }, - { - name: 'Somalia', - capital: 'Mogadishu', - languages: ['Somali', 'Arabic'], - population: 11079000, - flag: 'https://restcountries.eu/data/som.svg', - currency: 'Somali shilling' - }, - { - name: 'South Africa', - capital: 'Pretoria', - languages: [ - 'Afrikaans', - 'English', - 'Southern Ndebele', - 'Southern Sotho', - 'Swati', - 'Tswana', - 'Tsonga', - 'Venda', - 'Xhosa', - 'Zulu' - ], - population: 55653654, - flag: 'https://restcountries.eu/data/zaf.svg', - currency: 'South African rand' - }, - { - name: 'South Georgia and the South Sandwich Islands', - capital: 'King Edward Point', - languages: ['English'], - population: 30, - flag: 'https://restcountries.eu/data/sgs.svg', - currency: 'British pound' - }, - { - name: 'Korea (Republic of)', - capital: 'Seoul', - languages: ['Korean'], - population: 50801405, - flag: 'https://restcountries.eu/data/kor.svg', - currency: 'South Korean won' - }, - { - name: 'South Sudan', - capital: 'Juba', - languages: ['English'], - population: 12131000, - flag: 'https://restcountries.eu/data/ssd.svg', - currency: 'South Sudanese pound' - }, - { - name: 'Spain', - capital: 'Madrid', - languages: ['Spanish'], - population: 46438422, - flag: 'https://restcountries.eu/data/esp.svg', - currency: 'Euro' - }, - { - name: 'Sri Lanka', - capital: 'Colombo', - languages: ['Sinhalese', 'Tamil'], - population: 20966000, - flag: 'https://restcountries.eu/data/lka.svg', - currency: 'Sri Lankan rupee' - }, - { - name: 'Sudan', - capital: 'Khartoum', - languages: ['Arabic', 'English'], - population: 39598700, - flag: 'https://restcountries.eu/data/sdn.svg', - currency: 'Sudanese pound' - }, - { - name: 'Suriname', - capital: 'Paramaribo', - languages: ['Dutch'], - population: 541638, - flag: 'https://restcountries.eu/data/sur.svg', - currency: 'Surinamese dollar' - }, - { - name: 'Svalbard and Jan Mayen', - capital: 'Longyearbyen', - languages: ['Norwegian'], - population: 2562, - flag: 'https://restcountries.eu/data/sjm.svg', - currency: 'Norwegian krone' - }, - { - name: 'Swaziland', - capital: 'Lobamba', - languages: ['English', 'Swati'], - population: 1132657, - flag: 'https://restcountries.eu/data/swz.svg', - currency: 'Swazi lilangeni' - }, - { - name: 'Sweden', - capital: 'Stockholm', - languages: ['Swedish'], - population: 9894888, - flag: 'https://restcountries.eu/data/swe.svg', - currency: 'Swedish krona' - }, - { - name: 'Switzerland', - capital: 'Bern', - languages: ['German', 'French', 'Italian'], - population: 8341600, - flag: 'https://restcountries.eu/data/che.svg', - currency: 'Swiss franc' - }, - { - name: 'Syrian Arab Republic', - capital: 'Damascus', - languages: ['Arabic'], - population: 18564000, - flag: 'https://restcountries.eu/data/syr.svg', - currency: 'Syrian pound' - }, - { - name: 'Taiwan', - capital: 'Taipei', - languages: ['Chinese'], - population: 23503349, - flag: 'https://restcountries.eu/data/twn.svg', - currency: 'New Taiwan dollar' - }, - { - name: 'Tajikistan', - capital: 'Dushanbe', - languages: ['Tajik', 'Russian'], - population: 8593600, - flag: 'https://restcountries.eu/data/tjk.svg', - currency: 'Tajikistani somoni' - }, - { - name: 'Tanzania, United Republic of', - capital: 'Dodoma', - languages: ['Swahili', 'English'], - population: 55155000, - flag: 'https://restcountries.eu/data/tza.svg', - currency: 'Tanzanian shilling' - }, - { - name: 'Thailand', - capital: 'Bangkok', - languages: ['Thai'], - population: 65327652, - flag: 'https://restcountries.eu/data/tha.svg', - currency: 'Thai baht' - }, - { - name: 'Timor-Leste', - capital: 'Dili', - languages: ['Portuguese'], - population: 1167242, - flag: 'https://restcountries.eu/data/tls.svg', - currency: 'United States dollar' - }, - { - name: 'Togo', - capital: 'Lomé', - languages: ['French'], - population: 7143000, - flag: 'https://restcountries.eu/data/tgo.svg', - currency: 'West African CFA franc' - }, - { - name: 'Tokelau', - capital: 'Fakaofo', - languages: ['English'], - population: 1411, - flag: 'https://restcountries.eu/data/tkl.svg', - currency: 'New Zealand dollar' - }, - { - name: 'Tonga', - capital: "Nuku'alofa", - languages: ['English', 'Tonga (Tonga Islands)'], - population: 103252, - flag: 'https://restcountries.eu/data/ton.svg', - currency: 'Tongan paʻanga' - }, - { - name: 'Trinidad and Tobago', - capital: 'Port of Spain', - languages: ['English'], - population: 1349667, - flag: 'https://restcountries.eu/data/tto.svg', - currency: 'Trinidad and Tobago dollar' - }, - { - name: 'Tunisia', - capital: 'Tunis', - languages: ['Arabic'], - population: 11154400, - flag: 'https://restcountries.eu/data/tun.svg', - currency: 'Tunisian dinar' - }, - { - name: 'Turkey', - capital: 'Ankara', - languages: ['Turkish'], - population: 78741053, - flag: 'https://restcountries.eu/data/tur.svg', - currency: 'Turkish lira' - }, - { - name: 'Turkmenistan', - capital: 'Ashgabat', - languages: ['Turkmen', 'Russian'], - population: 4751120, - flag: 'https://restcountries.eu/data/tkm.svg', - currency: 'Turkmenistan manat' - }, - { - name: 'Turks and Caicos Islands', - capital: 'Cockburn Town', - languages: ['English'], - population: 31458, - flag: 'https://restcountries.eu/data/tca.svg', - currency: 'United States dollar' - }, - { - name: 'Tuvalu', - capital: 'Funafuti', - languages: ['English'], - population: 10640, - flag: 'https://restcountries.eu/data/tuv.svg', - currency: 'Australian dollar' - }, - { - name: 'Uganda', - capital: 'Kampala', - languages: ['English', 'Swahili'], - population: 33860700, - flag: 'https://restcountries.eu/data/uga.svg', - currency: 'Ugandan shilling' - }, - { - name: 'Ukraine', - capital: 'Kiev', - languages: ['Ukrainian'], - population: 42692393, - flag: 'https://restcountries.eu/data/ukr.svg', - currency: 'Ukrainian hryvnia' - }, - { - name: 'United Arab Emirates', - capital: 'Abu Dhabi', - languages: ['Arabic'], - population: 9856000, - flag: 'https://restcountries.eu/data/are.svg', - currency: 'United Arab Emirates dirham' - }, - { - name: 'United Kingdom of Great Britain and Northern Ireland', - capital: 'London', - languages: ['English'], - population: 65110000, - flag: 'https://restcountries.eu/data/gbr.svg', - currency: 'British pound' - }, - { - name: 'United States of America', - capital: 'Washington, D.C.', - languages: ['English'], - population: 323947000, - flag: 'https://restcountries.eu/data/usa.svg', - currency: 'United States dollar' - }, - { - name: 'Uruguay', - capital: 'Montevideo', - languages: ['Spanish'], - population: 3480222, - flag: 'https://restcountries.eu/data/ury.svg', - currency: 'Uruguayan peso' - }, - { - name: 'Uzbekistan', - capital: 'Tashkent', - languages: ['Uzbek', 'Russian'], - population: 31576400, - flag: 'https://restcountries.eu/data/uzb.svg', - currency: "Uzbekistani so'm" - }, - { - name: 'Vanuatu', - capital: 'Port Vila', - languages: ['Bislama', 'English', 'French'], - population: 277500, - flag: 'https://restcountries.eu/data/vut.svg', - currency: 'Vanuatu vatu' - }, - { - name: 'Venezuela (Bolivarian Republic of)', - capital: 'Caracas', - languages: ['Spanish'], - population: 31028700, - flag: 'https://restcountries.eu/data/ven.svg', - currency: 'Venezuelan bolívar' - }, - { - name: 'Viet Nam', - capital: 'Hanoi', - languages: ['Vietnamese'], - population: 92700000, - flag: 'https://restcountries.eu/data/vnm.svg', - currency: 'Vietnamese đồng' - }, - { - name: 'Wallis and Futuna', - capital: 'Mata-Utu', - languages: ['French'], - population: 11750, - flag: 'https://restcountries.eu/data/wlf.svg', - currency: 'CFP franc' - }, - { - name: 'Western Sahara', - capital: 'El Aaiún', - languages: ['Spanish'], - population: 510713, - flag: 'https://restcountries.eu/data/esh.svg', - currency: 'Moroccan dirham' - }, - { - name: 'Yemen', - capital: "Sana'a", - languages: ['Arabic'], - population: 27478000, - flag: 'https://restcountries.eu/data/yem.svg', - currency: 'Yemeni rial' - }, - { - name: 'Zambia', - capital: 'Lusaka', - languages: ['English'], - population: 15933883, - flag: 'https://restcountries.eu/data/zmb.svg', - currency: 'Zambian kwacha' - }, - { - name: 'Zimbabwe', - capital: 'Harare', - languages: ['English', 'Shona', 'Northern Ndebele'], - population: 14240168, - flag: 'https://restcountries.eu/data/zwe.svg', - currency: 'Botswana pula' - } -] diff --git a/images/30DaysOfJavaScript.png b/images/30DaysOfJavaScript.png deleted file mode 100644 index 4142286..0000000 Binary files a/images/30DaysOfJavaScript.png and /dev/null differ diff --git a/images/adding_project_to_vscode.png b/images/adding_project_to_vscode.png deleted file mode 100644 index 1935860..0000000 Binary files a/images/adding_project_to_vscode.png and /dev/null differ diff --git a/images/arithmetic.png b/images/arithmetic.png deleted file mode 100644 index 9830916..0000000 Binary files a/images/arithmetic.png and /dev/null differ diff --git a/images/array_index.png b/images/array_index.png deleted file mode 100644 index 355324e..0000000 Binary files a/images/array_index.png and /dev/null differ diff --git a/images/assignment_operators.png b/images/assignment_operators.png deleted file mode 100644 index 99d51d2..0000000 Binary files a/images/assignment_operators.png and /dev/null differ diff --git a/images/banners/Day -1 – 31.png b/images/banners/Day -1 – 31.png deleted file mode 100644 index d9a9639..0000000 Binary files a/images/banners/Day -1 – 31.png and /dev/null differ diff --git a/images/banners/day_1_1.png b/images/banners/day_1_1.png deleted file mode 100644 index dd583c7..0000000 Binary files a/images/banners/day_1_1.png and /dev/null differ diff --git a/images/banners/day_1_10.png b/images/banners/day_1_10.png deleted file mode 100644 index e063dec..0000000 Binary files a/images/banners/day_1_10.png and /dev/null differ diff --git a/images/banners/day_1_11.png b/images/banners/day_1_11.png deleted file mode 100644 index 0c2d60b..0000000 Binary files a/images/banners/day_1_11.png and /dev/null differ diff --git a/images/banners/day_1_12.png b/images/banners/day_1_12.png deleted file mode 100644 index 232ac85..0000000 Binary files a/images/banners/day_1_12.png and /dev/null differ diff --git a/images/banners/day_1_13.png b/images/banners/day_1_13.png deleted file mode 100644 index 488f522..0000000 Binary files a/images/banners/day_1_13.png and /dev/null differ diff --git a/images/banners/day_1_14.png b/images/banners/day_1_14.png deleted file mode 100644 index 4c5a568..0000000 Binary files a/images/banners/day_1_14.png and /dev/null differ diff --git a/images/banners/day_1_15.png b/images/banners/day_1_15.png deleted file mode 100644 index e3013f6..0000000 Binary files a/images/banners/day_1_15.png and /dev/null differ diff --git a/images/banners/day_1_16.png b/images/banners/day_1_16.png deleted file mode 100644 index d116060..0000000 Binary files a/images/banners/day_1_16.png and /dev/null differ diff --git a/images/banners/day_1_17.png b/images/banners/day_1_17.png deleted file mode 100644 index 69cf7ae..0000000 Binary files a/images/banners/day_1_17.png and /dev/null differ diff --git a/images/banners/day_1_18.png b/images/banners/day_1_18.png deleted file mode 100644 index 8b69340..0000000 Binary files a/images/banners/day_1_18.png and /dev/null differ diff --git a/images/banners/day_1_19.png b/images/banners/day_1_19.png deleted file mode 100644 index 2a785c9..0000000 Binary files a/images/banners/day_1_19.png and /dev/null differ diff --git a/images/banners/day_1_2.png b/images/banners/day_1_2.png deleted file mode 100644 index 0f6eefb..0000000 Binary files a/images/banners/day_1_2.png and /dev/null differ diff --git a/images/banners/day_1_20.png b/images/banners/day_1_20.png deleted file mode 100644 index befe1fc..0000000 Binary files a/images/banners/day_1_20.png and /dev/null differ diff --git a/images/banners/day_1_21.png b/images/banners/day_1_21.png deleted file mode 100644 index 634d1eb..0000000 Binary files a/images/banners/day_1_21.png and /dev/null differ diff --git a/images/banners/day_1_22.png b/images/banners/day_1_22.png deleted file mode 100644 index 81e33d9..0000000 Binary files a/images/banners/day_1_22.png and /dev/null differ diff --git a/images/banners/day_1_23.png b/images/banners/day_1_23.png deleted file mode 100644 index ceb0321..0000000 Binary files a/images/banners/day_1_23.png and /dev/null differ diff --git a/images/banners/day_1_24.png b/images/banners/day_1_24.png deleted file mode 100644 index 9c8ec46..0000000 Binary files a/images/banners/day_1_24.png and /dev/null differ diff --git a/images/banners/day_1_25.png b/images/banners/day_1_25.png deleted file mode 100644 index 60a211e..0000000 Binary files a/images/banners/day_1_25.png and /dev/null differ diff --git a/images/banners/day_1_26.png b/images/banners/day_1_26.png deleted file mode 100644 index f187f2c..0000000 Binary files a/images/banners/day_1_26.png and /dev/null differ diff --git a/images/banners/day_1_27.png b/images/banners/day_1_27.png deleted file mode 100644 index 8637069..0000000 Binary files a/images/banners/day_1_27.png and /dev/null differ diff --git a/images/banners/day_1_28.png b/images/banners/day_1_28.png deleted file mode 100644 index 1858aca..0000000 Binary files a/images/banners/day_1_28.png and /dev/null differ diff --git a/images/banners/day_1_29.png b/images/banners/day_1_29.png deleted file mode 100644 index 959ee36..0000000 Binary files a/images/banners/day_1_29.png and /dev/null differ diff --git a/images/banners/day_1_3.png b/images/banners/day_1_3.png deleted file mode 100644 index 1268d2c..0000000 Binary files a/images/banners/day_1_3.png and /dev/null differ diff --git a/images/banners/day_1_30.png b/images/banners/day_1_30.png deleted file mode 100644 index 18a77c4..0000000 Binary files a/images/banners/day_1_30.png and /dev/null differ diff --git a/images/banners/day_1_4.png b/images/banners/day_1_4.png deleted file mode 100644 index d5262c6..0000000 Binary files a/images/banners/day_1_4.png and /dev/null differ diff --git a/images/banners/day_1_5.png b/images/banners/day_1_5.png deleted file mode 100644 index 21bc08c..0000000 Binary files a/images/banners/day_1_5.png and /dev/null differ diff --git a/images/banners/day_1_6.png b/images/banners/day_1_6.png deleted file mode 100644 index dbea5fd..0000000 Binary files a/images/banners/day_1_6.png and /dev/null differ diff --git a/images/banners/day_1_7.png b/images/banners/day_1_7.png deleted file mode 100644 index eff8dac..0000000 Binary files a/images/banners/day_1_7.png and /dev/null differ diff --git a/images/banners/day_1_8.png b/images/banners/day_1_8.png deleted file mode 100644 index ddf9007..0000000 Binary files a/images/banners/day_1_8.png and /dev/null differ diff --git a/images/banners/day_1_9.png b/images/banners/day_1_9.png deleted file mode 100644 index 1cf688b..0000000 Binary files a/images/banners/day_1_9.png and /dev/null differ diff --git a/images/become_patreon.png b/images/become_patreon.png deleted file mode 100644 index 7de852e..0000000 Binary files a/images/become_patreon.png and /dev/null differ diff --git a/images/comparison_operators.png b/images/comparison_operators.png deleted file mode 100644 index 26ccb91..0000000 Binary files a/images/comparison_operators.png and /dev/null differ diff --git a/images/console_log_multipl_arguments.png b/images/console_log_multipl_arguments.png deleted file mode 100644 index f324a90..0000000 Binary files a/images/console_log_multipl_arguments.png and /dev/null differ diff --git a/images/date_time_object.png b/images/date_time_object.png deleted file mode 100644 index c5297c7..0000000 Binary files a/images/date_time_object.png and /dev/null differ diff --git a/images/day_1.png b/images/day_1.png deleted file mode 100644 index 7daf57f..0000000 Binary files a/images/day_1.png and /dev/null differ diff --git a/images/day_1_1.png b/images/day_1_1.png deleted file mode 100644 index dd583c7..0000000 Binary files a/images/day_1_1.png and /dev/null differ diff --git a/images/download_node.png b/images/download_node.png deleted file mode 100644 index f290b20..0000000 Binary files a/images/download_node.png and /dev/null differ diff --git a/images/google_chrome.png b/images/google_chrome.png deleted file mode 100644 index af06acd..0000000 Binary files a/images/google_chrome.png and /dev/null differ diff --git a/images/install_node.png b/images/install_node.png deleted file mode 100644 index e5aecf1..0000000 Binary files a/images/install_node.png and /dev/null differ diff --git a/images/js_code_on_chrome_console.png b/images/js_code_on_chrome_console.png deleted file mode 100644 index 7d6002c..0000000 Binary files a/images/js_code_on_chrome_console.png and /dev/null differ diff --git a/images/js_code_vscode.png b/images/js_code_vscode.png deleted file mode 100644 index 6e1a661..0000000 Binary files a/images/js_code_vscode.png and /dev/null differ diff --git a/images/launched_on_new_tab.png b/images/launched_on_new_tab.png deleted file mode 100644 index ed377dc..0000000 Binary files a/images/launched_on_new_tab.png and /dev/null differ diff --git a/images/local_storage.png b/images/local_storage.png deleted file mode 100644 index 0876852..0000000 Binary files a/images/local_storage.png and /dev/null differ diff --git a/images/multiple_script.png b/images/multiple_script.png deleted file mode 100644 index caa067f..0000000 Binary files a/images/multiple_script.png and /dev/null differ diff --git a/images/opening_chrome_console_shortcut.png b/images/opening_chrome_console_shortcut.png deleted file mode 100644 index eace03f..0000000 Binary files a/images/opening_chrome_console_shortcut.png and /dev/null differ diff --git a/images/opening_developer_tool.png b/images/opening_developer_tool.png deleted file mode 100644 index 6eb33dd..0000000 Binary files a/images/opening_developer_tool.png and /dev/null differ diff --git a/images/opening_project_on_vscode.png b/images/opening_project_on_vscode.png deleted file mode 100644 index 908c8fd..0000000 Binary files a/images/opening_project_on_vscode.png and /dev/null differ diff --git a/images/paypal_lg.png b/images/paypal_lg.png deleted file mode 100644 index cc2a45a..0000000 Binary files a/images/paypal_lg.png and /dev/null differ diff --git a/images/projects/congratulations.gif b/images/projects/congratulations.gif deleted file mode 100644 index cddd6c4..0000000 Binary files a/images/projects/congratulations.gif and /dev/null differ diff --git a/images/projects/dom_min_project_30DaysOfJavaScript_color_changing_day_9.1.gif b/images/projects/dom_min_project_30DaysOfJavaScript_color_changing_day_9.1.gif deleted file mode 100644 index c8d2f2b..0000000 Binary files a/images/projects/dom_min_project_30DaysOfJavaScript_color_changing_day_9.1.gif and /dev/null differ diff --git a/images/projects/dom_min_project_bar_graph_day_5.1.gif b/images/projects/dom_min_project_bar_graph_day_5.1.gif deleted file mode 100644 index a7d7962..0000000 Binary files a/images/projects/dom_min_project_bar_graph_day_5.1.gif and /dev/null differ diff --git a/images/projects/dom_min_project_bar_graph_day_5.1.png b/images/projects/dom_min_project_bar_graph_day_5.1.png deleted file mode 100644 index 0b6ccf7..0000000 Binary files a/images/projects/dom_min_project_bar_graph_day_5.1.png and /dev/null differ diff --git a/images/projects/dom_min_project_challenge_info_day_1.1.gif b/images/projects/dom_min_project_challenge_info_day_1.1.gif deleted file mode 100644 index 0551771..0000000 Binary files a/images/projects/dom_min_project_challenge_info_day_1.1.gif and /dev/null differ diff --git a/images/projects/dom_min_project_challenge_info_day_1.1.png b/images/projects/dom_min_project_challenge_info_day_1.1.png deleted file mode 100644 index 01a8d4f..0000000 Binary files a/images/projects/dom_min_project_challenge_info_day_1.1.png and /dev/null differ diff --git a/images/projects/dom_min_project_countries_aray_day_2.2.png b/images/projects/dom_min_project_countries_aray_day_2.2.png deleted file mode 100644 index ca0e344..0000000 Binary files a/images/projects/dom_min_project_countries_aray_day_2.2.png and /dev/null differ diff --git a/images/projects/dom_min_project_day_7.1.gif b/images/projects/dom_min_project_day_7.1.gif deleted file mode 100644 index 51bdadb..0000000 Binary files a/images/projects/dom_min_project_day_7.1.gif and /dev/null differ diff --git a/images/projects/dom_min_project_day_number_generators_2.1.png b/images/projects/dom_min_project_day_number_generators_2.1.png deleted file mode 100644 index d69a6c2..0000000 Binary files a/images/projects/dom_min_project_day_number_generators_2.1.png and /dev/null differ diff --git a/images/projects/dom_min_project_keycode_day_3.2.gif b/images/projects/dom_min_project_keycode_day_3.2.gif deleted file mode 100644 index 7c75c14..0000000 Binary files a/images/projects/dom_min_project_keycode_day_3.2.gif and /dev/null differ diff --git a/images/projects/dom_min_project_number_generator_day_3.1.gif b/images/projects/dom_min_project_number_generator_day_3.1.gif deleted file mode 100644 index 59a8dd0..0000000 Binary files a/images/projects/dom_min_project_number_generator_day_3.1.gif and /dev/null differ diff --git a/images/projects/dom_min_project_solar_system_day_4.1.gif b/images/projects/dom_min_project_solar_system_day_4.1.gif deleted file mode 100644 index d88b04b..0000000 Binary files a/images/projects/dom_min_project_solar_system_day_4.1.gif and /dev/null differ diff --git a/images/projects/dom_min_project_solar_system_day_4.1.mkv b/images/projects/dom_min_project_solar_system_day_4.1.mkv deleted file mode 100644 index 1ed941c..0000000 Binary files a/images/projects/dom_min_project_solar_system_day_4.1.mkv and /dev/null differ diff --git a/images/projects/dom_min_project_solar_system_day_4.1.mp4 b/images/projects/dom_min_project_solar_system_day_4.1.mp4 deleted file mode 100644 index 69ce936..0000000 Binary files a/images/projects/dom_min_project_solar_system_day_4.1.mp4 and /dev/null differ diff --git a/images/projects/dom_mini_project_challenge_info_day_2.3.gif b/images/projects/dom_mini_project_challenge_info_day_2.3.gif deleted file mode 100644 index 571ea6f..0000000 Binary files a/images/projects/dom_mini_project_challenge_info_day_2.3.gif and /dev/null differ diff --git a/images/projects/dom_mini_project_challenge_info_day_2.3.png b/images/projects/dom_mini_project_challenge_info_day_2.3.png deleted file mode 100644 index 3387bea..0000000 Binary files a/images/projects/dom_mini_project_challenge_info_day_2.3.png and /dev/null differ diff --git a/images/projects/dom_mini_project_countries_day_6.1.gif b/images/projects/dom_mini_project_countries_day_6.1.gif deleted file mode 100644 index 8a8f09a..0000000 Binary files a/images/projects/dom_mini_project_countries_day_6.1.gif and /dev/null differ diff --git a/images/projects/dom_mini_project_countries_object_day_10.1.gif b/images/projects/dom_mini_project_countries_object_day_10.1.gif deleted file mode 100644 index 03b1e35..0000000 Binary files a/images/projects/dom_mini_project_countries_object_day_10.1.gif and /dev/null differ diff --git a/images/projects/dom_mini_project_form_validation_day_10.2.1.png b/images/projects/dom_mini_project_form_validation_day_10.2.1.png deleted file mode 100644 index 9d2c2b3..0000000 Binary files a/images/projects/dom_mini_project_form_validation_day_10.2.1.png and /dev/null differ diff --git a/images/projects/dom_mini_project_form_validation_day_10.2.png b/images/projects/dom_mini_project_form_validation_day_10.2.png deleted file mode 100644 index ca7cdd5..0000000 Binary files a/images/projects/dom_mini_project_form_validation_day_10.2.png and /dev/null differ diff --git a/images/projects/dom_mini_project_leaderboard_day_8.1.gif b/images/projects/dom_mini_project_leaderboard_day_8.1.gif deleted file mode 100644 index 789d0cb..0000000 Binary files a/images/projects/dom_mini_project_leaderboard_day_8.1.gif and /dev/null differ diff --git a/images/projects/dom_mini_project_leaderboard_day_8.1.png b/images/projects/dom_mini_project_leaderboard_day_8.1.png deleted file mode 100644 index 2956fa0..0000000 Binary files a/images/projects/dom_mini_project_leaderboard_day_8.1.png and /dev/null differ diff --git a/images/projects/dom_mini_project_slider_day_7.1.gif b/images/projects/dom_mini_project_slider_day_7.1.gif deleted file mode 100644 index 51bdadb..0000000 Binary files a/images/projects/dom_mini_project_slider_day_7.1.gif and /dev/null differ diff --git a/images/raising_syntax_error.png b/images/raising_syntax_error.png deleted file mode 100644 index 81f6245..0000000 Binary files a/images/raising_syntax_error.png and /dev/null differ diff --git a/images/regex.png b/images/regex.png deleted file mode 100644 index c7116b4..0000000 Binary files a/images/regex.png and /dev/null differ diff --git a/images/running_script.png b/images/running_script.png deleted file mode 100644 index deac13d..0000000 Binary files a/images/running_script.png and /dev/null differ diff --git a/images/scripts_on_vscode.png b/images/scripts_on_vscode.png deleted file mode 100644 index f6257be..0000000 Binary files a/images/scripts_on_vscode.png and /dev/null differ diff --git a/images/string_indexes.png b/images/string_indexes.png deleted file mode 100644 index cc2f638..0000000 Binary files a/images/string_indexes.png and /dev/null differ diff --git a/images/vsc_live_server.png b/images/vsc_live_server.png deleted file mode 100644 index 75509f2..0000000 Binary files a/images/vsc_live_server.png and /dev/null differ diff --git a/images/vscode.png b/images/vscode.png deleted file mode 100644 index 724fc10..0000000 Binary files a/images/vscode.png and /dev/null differ diff --git a/images/vscode_ui.png b/images/vscode_ui.png deleted file mode 100644 index 7210a08..0000000 Binary files a/images/vscode_ui.png and /dev/null differ diff --git a/images/web_storage.png b/images/web_storage.png deleted file mode 100644 index 46f9311..0000000 Binary files a/images/web_storage.png and /dev/null differ diff --git a/index.html b/index.html deleted file mode 100644 index 14e41c3..0000000 --- a/index.html +++ /dev/null @@ -1,128 +0,0 @@ - - - - - Document Object Model:30 Days Of JavaScript - - - - - - -
-

Asabeneh Yetayeh challenges in 2020

-

30DaysOfJavaScript Challenge

-

- -
- - - - - \ No newline at end of file diff --git a/readMe.md b/readMe.md deleted file mode 100644 index 8fc639c..0000000 --- a/readMe.md +++ /dev/null @@ -1,678 +0,0 @@ -# 30 Days Of JavaScript - -| # Day | Topics | -| ----- | :-------------------------------------------------------------------------------------------------------------------------------------------------: | -| 01 | [Introduction](./readMe.md) | -| 02 | [Data Types](./02_Day_Data_types/02_day_data_types.md) | -| 03 | [Booleans, Operators, Date](./03_Day_Booleans_operators_date/03_booleans_operators_date.md) | -| 04 | [Conditionals](./04_Day_Conditionals/04_day_conditionals.md) | -| 05 | [Arrays](./05_Day_Arrays/05_day_arrays.md) | -| 06 | [Loops](./06_Day_Loops/06_day_loops.md) | -| 07 | [Functions](./07_Day_Functions/07_day_functions.md) | -| 08 | [Objects](./08_Day_Objects/08_day_objects.md) | -| 09 | [Higher Order Functions](./09_Day_Higher_order_functions/09_day_higher_order_functions.md) | -| 10 | [Sets and Maps](./10_Day_Sets_and_Maps/10_day_Sets_and_Maps.md) | -| 11 | [Destructuring and Spreading](./11_Day_Destructuring_and_spreading/11_day_destructuring_and_spreading.md) | -| 12 | [Regular Expressions](./12_Day_Regular_expressions/12_day_regular_expressions.md) | -| 13 | [Console Object Methods](./13_Day_Console_object_methods/13_day_console_object_methods.md) | -| 14 | [Error Handling](./14_Day_Error_handling/14_day_error_handling.md) | -| 15 | [Classes](./15_Day_Classes/15_day_classes.md) | -| 16 | [JSON](./16_Day_JSON/16_day_json.md) | -| 17 | [Web Storages](./17_Day_Web_storages/17_day_web_storages.md) | -| 18 | [Promises](./18_Day_Promises/18_day_promises.md) | -| 19 | [Closure](./19_Day_Closures/19_day_closures.md) | -| 20 | [Writing Clean Code](./20_Day_Writing_clean_codes/20_day_writing_clean_codes.md) | -| 21 | [DOM](./21_Day_DOM/21_day_dom.md) | -| 22 | [Manipulating DOM Object](./22_Day_Manipulating_DOM_object/22_day_manipulating_DOM_object.md) | -| 23 | [Event Listeners](./23_Day_Event_listeners/23_day_event_listeners.md) | -| 24 | [Mini Project: Solar System](./24_Day_Project_solar_system/24_day_project_solar_system.md) | -| 25 | [Mini Project: World Countries Data Visualization 1](./25_Day_World_countries_data_visualization_1/25_day_world_countries_data_visualization_1.md) | -| 26 | [Mini Project: World Countries Data Visualization 2](./26_Day_World_countries_data_visualization_2/26_day_world_countries_data_visualization_2.md) | -| 27 | [Mini Project: Portfolio](./27_Day_Mini_project_portfolio/27_day_mini_project_portfolio.md) | -| 28 | [Mini Project: Leaderboard](./28_Day_Mini_project_leaderboard/28_day_mini_project_leaderboard.md) | -| 29 | [Mini Project: Animating characters](./29_Day_Mini_project_animating_characters/29_day_mini_project_animating_characters.md) | -| 30 | [Final Projects](./30_Day_Mini_project_final/30_day_mini_project_final.md) | - -🧡🧡🧡 HAPPY CODING 🧡🧡🧡 - -
-Support the author to create more educational materials
-Paypal Logo -
- -
-

30 Days Of JavaScript: Introduction

- - - - - Twitter Follow - - -Author: -Asabeneh Yetayeh
- January, 2020 -
- -
- -🇬🇧 [English](./readMe.md) -🇪🇸 [Spanish](./Spanish/readme.md) -🇮🇹 [Italian](./Italian/readMe.md) -🇷🇺 [Russian](./RU/README.md) -🇹🇷 [Turkish](./Turkish/readMe.md) -🇦🇿 [Azerbaijan](./Azerbaijani/readMe.md) -🇰🇷 [Korean](./Korea/README.md) -🇻🇳 [Vietnamese](./Vietnamese/README.md) -🇵🇱 [Polish](./Polish/readMe.md) - - -
- -
- - -[Day 2 >>](./02_Day_Data_types/02_day_data_types.md) - -![Thirty Days Of JavaScript](./images/day_1_1.png) - -- [30 Days Of JavaScript](#30-days-of-javascript) -- [📔 Day 1](#-day-1) - - [Introduction](#introduction) - - [Requirements](#requirements) - - [Setup](#setup) - - [Install Node.js](#install-nodejs) - - [Browser](#browser) - - [Installing Google Chrome](#installing-google-chrome) - - [Opening Google Chrome Console](#opening-google-chrome-console) - - [Writing Code on Browser Console](#writing-code-on-browser-console) - - [Console.log](#consolelog) - - [Console.log with Multiple Arguments](#consolelog-with-multiple-arguments) - - [Comments](#comments) - - [Syntax](#syntax) - - [Arithmetics](#arithmetics) - - [Code Editor](#code-editor) - - [Installing Visual Studio Code](#installing-visual-studio-code) - - [How to Use Visual Studio Code](#how-to-use-visual-studio-code) - - [Adding JavaScript to a Web Page](#adding-javascript-to-a-web-page) - - [Inline Script](#inline-script) - - [Internal Script](#internal-script) - - [External Script](#external-script) - - [Multiple External Scripts](#multiple-external-scripts) - - [Introduction to Data types](#introduction-to-data-types) - - [Numbers](#numbers) - - [Strings](#strings) - - [Booleans](#booleans) - - [Undefined](#undefined) - - [Null](#null) - - [Checking Data Types](#checking-data-types) - - [Comments Again](#comments-again) - - [Variables](#variables) -- [💻 Day 1: Exercises](#-day-1-exercises) - -# 📔 Day 1 - -## Introduction - -**Congratulations** on deciding to participate in 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 concept of programming. In the end of the challenge you will get a 30DaysOfJavaScript programming challenge completion certificate. In case you need help or if you would like to help others you may join the [telegram group](https://t.me/ThirtyDaysOfJavaScript). - -**A 30DaysOfJavaScript** challenge is a guide for both beginners and advanced JavaScript developers. Welcome to JavaScript. JavaScript is the language of the web. I enjoy using and teaching JavaScript and I hope you will do so too. - -In this step by step JavaScript challenge, you will learn JavaScript, the most popular programming language in the history of mankind. -JavaScript is used **_to add interactivity to websites, to develop mobile apps, desktop applications, games_** and nowadays JavaScript can be used for **_machine learning_** and **_AI_**. -**_JavaScript (JS)_** has increased in popularity in recent years and has been the leading -programming language for six 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. A computer -3. Internet -4. A browser -5. A code editor - -## Setup - -I believe you have the motivation and a strong desire to be a developer, a computer and Internet. If you have those, then you have everything to get started. - -### Install Node.js - -You may not need Node.js right now but you may need it for later. Install [node.js](https://nodejs.org/en/). - -![Node download](images/download_node.png) - -After downloading double click and install - -![Install node](images/install_node.png) - -We can check if node is installed on our local machine by opening our device terminal or command prompt. - -```sh -asabeneh $ node -v -v12.14.0 -``` - -When making this tutorial I was using Node version 12.14.0, but now the recommended version of Node.js for download is v14.17.6, by the time you use this material you may have a higher Node.js version. - -### 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 console either by clicking three dots at the top right corner of the browser, selecting _More tools -> Developer tools_ or using a keyboard shortcut. I prefer using shortcuts. - -![Opening chrome](images/opening_developer_tool.png) - -To open the Chrome console using a keyboard shortcut. - -```sh -Mac -Command+Option+J - -Windows/Linux: -Ctl+Shift+J -``` - -![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. The Console is the place where your JavaScript code goes. The Google Console V8 engine changes your JavaScript code to machine code. -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 - -Windows: -Ctl+Shift+I -``` - -##### Console.log - -To write our first JavaScript code, we used a built-in 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()`** function can take multiple parameters separated by commas. The syntax looks like as follows:**`console.log(param1, param2, param3)`** - -![console log multiple arguments](./images/console_log_multipl_arguments.png) - -```js -console.log('Hello', 'World', '!') -console.log('HAPPY', 'NEW', 'YEAR', 2020) -console.log('Welcome', 'to', 30, 'Days', 'Of', 'JavaScript') -``` - -As you can see from the snippet code above, _`console.log()`_ can take multiple arguments. - -Congratulations! You wrote your first JavaScript code using _`console.log()`_. - -##### Comments - -We can 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. In JavaScript, any text line starting with // in JavaScript is a comment, and anything enclosed like this `//` is also a comment. - -**Example: Single Line Comment** - -```js -// This is the first comment -// This is the second comment -// I am a single line comment -``` - -**Example: Multiline Comment** - -```js -/* -This is a multiline comment - Multiline comments can take multiple lines - JavaScript is the language of the web - */ -``` - -##### Syntax - -Programming languages are similar to human languages. English or many other language uses words, phrases, sentences, compound sentences and other more to convey a meaningful message. The English meaning of syntax is _the arrangement of words and phrases to create well-formed sentences in a language_. The technical definition of syntax is the structure of statements in a computer language. Programming languages have syntax. JavaScript is a programming language and like other programming languages it has its own syntax. 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 syntax errors. Actually, the syntax is very informative. It informs what type of mistake was 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!') -``` - -So far, we saw how to display text using the _`console.log()`_. If we are printing text or string using _`console.log()`_, the text has to be inside the single quotes, double quotes, or a 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. -In addition to the text, we can also do mathematical calculations using JavaScript. Let us do the following simple calculations. -It is possible to write JavaScript code on Google Chrome console can directly without the **_`console.log()`_** function. However, it is included in this introduction because most of this challenge would be taking place in a text editor where the usage of the function would be mandatory. You can play around directly with instructions on the console. - -![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) // Exponentiation 3 ** 2 == 3 * 3 -``` - -### 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 of JavaScript challenge, we will be using Visual Studio Code. - -#### Installing Visual Studio Code - -Visual Studio Code is a very popular open-source text editor. I would recommend to [download Visual Studio Code](https://code.visualstudio.com/), but if you are in favor of other editors, feel free to follow with what you have. - -![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 its 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) - -![Vscode add project](./images/adding_project_to_vscode.png) - -![Vscode open project](./images/opening_project_on_vscode.png) - -![script file](images/scripts_on_vscode.png) - -![Installing Live Server](images/vsc_live_server.png) - -![running script](./images/running_script.png) - -![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_** -- **_External script_** -- **_Multiple External scripts_** - -The following sections show different ways of adding JavaScript code to your web page. - -### Inline Script - -Create a project folder on your desktop or in any location, name it 30DaysOfJS and create an **_`index.html`_** file in the project folder. Then paste the following code and open it in a browser, for example [Chrome](https://www.google.com/chrome/). - -```html - - - - 30DaysOfScript:Inline Script - - - - - -``` - -Now, you just wrote your first inline script. We can create a pop up alert message using the _`alert()`_ built-in 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. - -```html - - - - 30DaysOfScript:Internal Script - - - - -``` - -This is how we write an internal script most of the time. Writing the JavaScript code in the body section is the most preferred option. Open the browser console to see the output from the `console.log()`. - -```html - - - - 30DaysOfScript:Internal Script - - - - - - -``` - -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. All files ending with .js extension are JavaScript files. Create a file named 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') -``` - -External scripts in the _head_: - -```html - - - - 30DaysOfJavaScript:External script - - - - -``` - -External scripts in the _body_: - -```html - - - - 30DaysOfJavaScript:External script - - - - - - - -``` - -Open the browser console to see the output of the `console.log()`. - -### Multiple External Scripts - -We can also link multiple external JavaScript files to a web page. -Create a `helloworld.js` file inside the 30DaysOfJS folder and write the following code. - -```js -console.log('Hello, World!') -``` - -```html - - - - Multiple External Scripts - - - - - - -``` - -_Your main.js file should be below all other scripts_. It is very important to remember this. - -![Multiple Script](./images/multiple_script.png) - -## Introduction to Data types - -In JavaScript and also other programming languages, there are different types of data types. The following are JavaScript primitive data types: _String, Number, Boolean, undefined, Null_, and _Symbol_. - -### Numbers - -- Integers: Integer (negative, zero and positive) numbers - Example: - ... -3, -2, -1, 0, 1, 2, 3 ... -- Float-point numbers: Decimal number - Example - ... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ... - -### Strings - -A collection of one or more characters between two single quotes, double quotes, or backticks. - -**Example:** - -```js -'a' -'Asabeneh' -"Asabeneh" -'Finland' -'JavaScript is a beautiful programming language' -'I love teaching' -'I hope you are enjoying the first day' -`We can also create a string using a backtick` -'A string could be just as small as one character or as big as many pages' -'Any data type under a single quote, double quote or backtick is a string' -``` - -### Booleans - -A boolean value is either True or False. Any comparisons returns a boolean value, which is either true or false. - -A boolean data type is either a true or false value. - -**Example:** - -```js -true // if the light is on, the value is true -false // if the light is off, the value is false -``` - -### Undefined - -In JavaScript, if we don't assign a value to a variable, the value is undefined. In addition to that, if a function is not returning anything, it returns undefined. - -```js -let firstName -console.log(firstName) // undefined, because it is not assigned to a value yet -``` - -### Null - -Null in JavaScript means an empty value. - -```js -let emptyValue = null -``` - -## Checking Data Types - -To check the data type of a certain variable, we use the **typeof** operator. See the following example. - -```js -console.log(typeof 'Asabeneh') // string -console.log(typeof 5) // number -console.log(typeof true) // boolean -console.log(typeof null) // object type -console.log(typeof undefined) // undefined -``` - -## Comments Again - -Remember that commenting in JavaScript is similar to other programming languages. Comments are important in making your code more readable. -There are two ways of commenting: - -- _Single line commenting_ -- _Multiline commenting_ - -```js -// commenting the code itself with a single comment -// let firstName = 'Asabeneh'; single line comment -// let lastName = 'Yetayeh'; single line comment -``` - -Multiline commenting: - -```js -/* - let location = 'Helsinki'; - let age = 100; - let isMarried = true; - This is a Multiple line comment -*/ -``` - -## Variables - -Variables are _containers_ of data. Variables are used to _store_ data in a memory location. When a variable is declared, a memory location is reserved. When a variable is assigned to a value (data), the memory space will be filled with that data. To declare a variable, we use _var_, _let_, or _const_ keywords. - -For a variable that changes at a different time, we use _let_. If the data does not change at all, we use _const_. For example, PI, country name, gravity do not change, and we can use _const_. We will not use var in this challenge and I don't recommend you to use it. It is error prone way of declaring variable it has lots of leak. We will talk more about var, let, and const in detail in other sections (scope). For now, the above explanation is enough. - -A valid JavaScript variable name must follow the following rules: - -- A JavaScript variable name should not begin with a number. -- A JavaScript variable name does not allow special characters except dollar sign and underscore. -- A JavaScript variable name follows a camelCase convention. -- A JavaScript variable name should not have space between words. - -The following are examples of valid JavaScript variables. - -```js -firstName -lastName -country -city -capitalCity -age -isMarried - -first_name -last_name -is_married -capital_city - -num1 -num_1 -_num_1 -$num1 -year2020 -year_2020 -``` - -The first and second variables on the list follows the camelCase convention of declaring in JavaScript. In this material, we will use camelCase variables(camelWithOneHump). We use CamelCase(CamelWithTwoHump) to declare classes, we will discuss about classes and objects in other section. - -Example of invalid variables: - -```js - first-name - 1_num - num_#_1 -``` - -Let us declare variables with different data types. To declare a variable, we need to use _let_ or _const_ keyword before the variable name. Following the variable name, we write an equal sign (assignment operator), and a value(assigned data). - -```js -// Syntax -let nameOfVariable = value -``` - -The nameOfVriable is the name that stores different data of value. See below for detail examples. - -**Examples of declared variables** - -```js -// Declaring different variables of different data types -let firstName = 'Asabeneh' // first name of a person -let lastName = 'Yetayeh' // last name of a person -let country = 'Finland' // country -let city = 'Helsinki' // capital city -let age = 100 // age in years -let isMarried = true - -console.log(firstName, lastName, country, city, age, isMarried) -``` - -```sh -Asabeneh Yetayeh Finland Helsinki 100 true -``` - -```js -// Declaring variables with number values -let age = 100 // age in years -const gravity = 9.81 // earth gravity in m/s2 -const boilingPoint = 100 // water boiling point, temperature in °C -const PI = 3.14 // geometrical constant -console.log(gravity, boilingPoint, PI) -``` - -```sh -9.81 100 3.14 -``` - -```js -// Variables can also be declaring in one line separated by comma, however I recommend to use a seperate line to make code more readble -let name = 'Asabeneh', job = 'teacher', live = 'Finland' -console.log(name, job, live) -``` - -```sh -Asabeneh teacher Finland -``` - -When you run _index.html_ file in the 01-Day folder you should get this: - -![Day one](./images/day_1.png) - -🌕 You are amazing! You have just completed day 1 challenge and you are on your way to greatness. Now do some exercises for your brain and muscle. - -# 💻 Day 1: Exercises - -1. Write a single line comment which says, _comments can make code readable_ -2. Write another single comment which says, _Welcome to 30DaysOfJavaScript_ -3. Write a multiline comment which says, _comments can make code readable, easy to reuse_ - _and informative_ - -4. Create a variable.js file and declare variables and assign string, boolean, undefined and null data types -5. Create datatypes.js file and use the JavaScript **_typeof_** operator to check different data types. Check the data type of each variable -6. Declare four variables without assigning values -7. Declare four variables with assigned values -8. Declare variables to store your first name, last name, marital status, country and age in multiple lines -9. Declare variables to store your first name, last name, marital status, country and age in a single line -10. Declare two variables _myAge_ and _yourAge_ and assign them initial values and log to the browser console. - -```sh -I am 25 years old. -You are 30 years old. -``` - -🎉 CONGRATULATIONS ! 🎉 - -[Day 2 >>](./02_Day_Data_types/02_day_data_types.md)