diff --git a/README.md b/README.md index 0821454..55e946c 100644 --- a/README.md +++ b/README.md @@ -9,15 +9,13 @@ JavaScript tutorial for Beginners JavaScript basics and fundamentals for all ===================== -Description ---------------------- +## Description JavaScript is a `scripting language of the web` that allows you to do/add Interactivity with User-Events, implement Conditions and Validations, Dynamic updates in a Web Page, etc.. In this practical course will learn JavaScript basics-programming fundamentals from scratch. We Will start with what is JavaScript? its uses, history, how to write JavaScript, etc. It will also cover various programming building blocks like variable, functions, array, conditionals, objects, and many more. -Topics (separate with spaces) ---------------------- +## Topics (separate with spaces) -Add topics to categorize your repository and make it more discoverable: +Add topics to categorize your repository and make it more discoverable: - javascript-programming-language - javascript-language-fundamentals @@ -40,77 +38,76 @@ Add topics to categorize your repository and make it more discoverable: - vanilla-javascript - javascript-typescript-es6 -Prerequisites for current course / What you need to know ---------------------- +## Prerequisites for current course / What you need to know To move forward with JavaScript you just need basic knowledge of XHTML/HTML. Here, you will learn how easy it is to add interactivity to a web page using JavaScript. But, before we begin, make sure that you have some working knowledge and/or general understanding of: + - The Internet and the World Wide Web (WWW) [Web Design Development Foundations-Web Technology Fundamentals](https://github.com/dinanathsj29/web-design-development-fundamentals) -- Good working knowledge of HyperText Markup Language (HTML) [HTML5 Essentials](https://github.com/dinanathsj29/html5-essentials) and +- Good working knowledge of HyperText Markup Language (HTML) [HTML5 Essentials](https://github.com/dinanathsj29/html5-essentials) and - Its good to know [CSS3 Fundamentals](https://github.com/dinanathsj29/css3-fundamentals) -Topics include -===================== +# Topics include 1. [Course Introduction](#section-01-course-introduction) - - 01.01. [Welcome](#0101-welcome) - - 01.02. [Who is this for? Audience](#0102-who-is-this-for-audience) + - 01.01. [Welcome](#0101-welcome) + - 01.02. [Who is this for? Audience](#0102-who-is-this-for-audience) 2. [Introducing JavaScript](#section-02-introducing-javascript) - - 02.01. [Importance](#0201-importance) - - 02.02. [What is JavaScript?](#0202-what-is-javascript) - - 02.03. [What is a scripting language?](#0203-what-is-a-scripting-language) - - 02.04. [What can you do with JavaScript?](#0204-what-can-you-do-with-javascript) | [Use of JavaScript?](#0204-use-of-javascript) - - 02.05. [Where does the JavaScript code run?](#0205-where-does-the-javascript-code-run) - - 02.06. [Who are using JavaScript?](#0206-who-are-using-javascript) - - 02.07. [History of JavaScript](#0207-history-of-javascript) - - 02.08. [JavaScript Vs ECMAScript](#0208-javascript-vs-ecmascript) - - 02.09. [Types of Script](#0209-types-of-script) | [Various Scripting languages](#0209-various-scripting-languages) | [Client-Side Scripting Vs Server Side Scripting](#0209-client-side-scripting-vs-server-side-scripting) - - 02.10. [Prerequisites of using HTML and JavaScript](#0210-prerequisites-of-using-html-and-javascript) + - 02.01. [Importance](#0201-importance) + - 02.02. [What is JavaScript?](#0202-what-is-javascript) + - 02.03. [What is a scripting language?](#0203-what-is-a-scripting-language) + - 02.04. [What can you do with JavaScript?](#0204-what-can-you-do-with-javascript) | [Use of JavaScript?](#0204-use-of-javascript) + - 02.05. [Where does the JavaScript code run?](#0205-where-does-the-javascript-code-run) + - 02.06. [Who are using JavaScript?](#0206-who-are-using-javascript) + - 02.07. [History of JavaScript](#0207-history-of-javascript) + - 02.08. [JavaScript Vs ECMAScript](#0208-javascript-vs-ecmascript) + - 02.09. [Types of Script](#0209-types-of-script) | [Various Scripting languages](#0209-various-scripting-languages) | [Client-Side Scripting Vs Server Side Scripting](#0209-client-side-scripting-vs-server-side-scripting) + - 02.10. [Prerequisites of using HTML and JavaScript](#0210-prerequisites-of-using-html-and-javascript) 3. [JavaScript Getting Started](#section-03-javascript-getting-started) - - 03.01. [How to write Javascript?](#0301-how-to-write-javascript) | [JavaScript in HTML](#0301-javascript-in-html) - - 03.02. [Where to write JavaScript in HTML?](#0302-where-to-write-javascript-in-html) | [Where to embed include write put JavaScript in HTML?](#0302-where-to-embed-include-write-put-javascript-in-html) - - 03.03. [JavaScript Code structure](#0303-javascript-code-structure) - - 03.04. [JavaScript Keywords](#0304-javascript-keywords) - - 03.05. [Comments](#0305-Comments) + - 03.01. [How to write Javascript?](#0301-how-to-write-javascript) | [JavaScript in HTML](#0301-javascript-in-html) + - 03.02. [Where to write JavaScript in HTML?](#0302-where-to-write-javascript-in-html) | [Where to embed include write put JavaScript in HTML?](#0302-where-to-embed-include-write-put-javascript-in-html) + - 03.03. [JavaScript Code structure](#0303-javascript-code-structure) + - 03.04. [JavaScript Keywords](#0304-javascript-keywords) + - 03.05. [Comments](#0305-Comments) 4. [JavaScript Language Fundamentals](#section-04-javascript-language-fundamentals) - - 04.01. [Generating Output](#0401-generating-output) + - 04.01. [Generating Output](#0401-generating-output) 5. [Variables](#section-05-variables) - - 05.01. [What is Variable?](#0501-what-is-variable) - - 05.02. [Declaring variable without a value](#0502-declaring-variable-without-a-value) | [Creating a variable without a value](#0502-Creating-a-variable-without-a-value) - - 05.03. [Declaring multiple variables at once](#0503-declaring-multiple-variables-at-once) - - 05.04. [Variable Naming Conventions](#0504-variable-naming-conventions) | [Variable Naming Conventions (Identifiers)](#0504-variable-naming-conventions-identifiers) - - 05.05. [Variable Scope](#0505-variable-scope) - - 05.06. [The let and const keywords ES6](#0506-the-let-and-const-keywords-es6) + - 05.01. [What is Variable?](#0501-what-is-variable) + - 05.02. [Declaring variable without a value](#0502-declaring-variable-without-a-value) | [Creating a variable without a value](#0502-Creating-a-variable-without-a-value) + - 05.03. [Declaring multiple variables at once](#0503-declaring-multiple-variables-at-once) + - 05.04. [Variable Naming Conventions](#0504-variable-naming-conventions) | [Variable Naming Conventions (Identifiers)](#0504-variable-naming-conventions-identifiers) + - 05.05. [Variable Scope](#0505-variable-scope) + - 05.06. [The let and const keywords ES6](#0506-the-let-and-const-keywords-es6) 6. [Data types](#section-06-data-types) - - 06.01. [Data types](#0601-data-types) - - 06.02. [Primitive data type](#0602-primitive-data-type) | [Primitive, Primary or Value data type](#0602-primitive-primary-or-value-data-type) - - 06.03. [Non-primitive data type](#0603-non-primitive-data-type) | [Non-primitive, Reference or Composite data type](#0603-non-primitive-reference-or-composite-data-type) - - 06.04. [JavaScript has Dynamic Types](#0604-javascript-has-dynamic-types) - - 06.05. [The typeof Operator](#0605-the-typeof-operator) - - 06.06. [Type conversion](#0606-type-conversion) | [typeof parseInt parseFloat](#0606-typeof-parseint-parsefloat) - - 06.07. [Type coercion](#0607-type-coercion) + - 06.01. [Data types](#0601-data-types) + - 06.02. [Primitive data type](#0602-primitive-data-type) | [Primitive, Primary or Value data type](#0602-primitive-primary-or-value-data-type) + - 06.03. [Non-primitive data type](#0603-non-primitive-data-type) | [Non-primitive, Reference or Composite data type](#0603-non-primitive-reference-or-composite-data-type) + - 06.04. [JavaScript has Dynamic Types](#0604-javascript-has-dynamic-types) + - 06.05. [The typeof Operator](#0605-the-typeof-operator) + - 06.06. [Type conversion](#0606-type-conversion) | [typeof parseInt parseFloat](#0606-typeof-parseint-parsefloat) + - 06.07. [Type coercion](#0607-type-coercion) 7. [Operators](#section-07-operators) - - 07.01. [What is the Operator?](#0701-what-is-the-operator) - - 07.02. [Arithmetic Operators](#0702-arithmetic-operators) - - 07.03. [Assignment Operators](#0703-assignment-operators) - - 07.04. [Logical Operators](#0704-logical-operators) - - 07.05. [Comparison Operators](#0705-comparison-operators) | [Relational Operators](#0705-relational-operators) - - 07.06. [Conditional Operator](#0706-conditional-perator) | [Ternary Operator](#0706-ternary-operator) - - 07.07. [String Operators](#0707-string-operators) - - 07.08. [Operator precedence](#0708-operator-precedence) + - 07.01. [What is the Operator?](#0701-what-is-the-operator) + - 07.02. [Arithmetic Operators](#0702-arithmetic-operators) + - 07.03. [Assignment Operators](#0703-assignment-operators) + - 07.04. [Logical Operators](#0704-logical-operators) + - 07.05. [Comparison Operators](#0705-comparison-operators) | [Relational Operators](#0705-relational-operators) + - 07.06. [Conditional Operator](#0706-conditional-perator) | [Ternary Operator](#0706-ternary-operator) + - 07.07. [String Operators](#0707-string-operators) + - 07.08. [Operator precedence](#0708-operator-precedence) 8. [Functions](#section-08-functions) - - 08.01. [What is a Function?](#0801-what-is-a-function) - - 08.02. [Types of Function](#0802-types-of-function) - - 08.03. [Different ways to define Function](#0803-different-ways-to-define-function) - - 08.04. [String Methods and Concatenation](#0804-string-methods-and-concatenation) - - 08.05. [Template String](#0805-template-string) | [Template Literals](#0805-template-literals) -9. [Loops](#section-09-loops) | [Loops and Iterations](#section-09-loops-and-iterations) - - 09.01. [The for loop](#0901-the-for-loop) - - 09.02. [The while loop](#0902-the-while-loop) - - 09.03. [The do while loop](#0903-the-do-while-loop) - - 09.04. [The for in loop](#0904-the-for-in-loop) - - 09.05. [The for of loop](#0905-the-for-of-loop) - - 09.06. [Break and Continue statement](#0906-break-and-continue-statement) - - 09.07. [for each loop](#0907-for-each-loop) + - 08.01. [What is a Function?](#0801-what-is-a-function) + - 08.02. [Types of Function](#0802-types-of-function) + - 08.03. [Different ways to define Function](#0803-different-ways-to-define-function) + - 08.04. [String Methods and Concatenation](#0804-string-methods-and-concatenation) + - 08.05. [Template String](#0805-template-string) | [Template Literals](#0805-template-literals) +9. [Loops](#section-09-loops) | [Loops and Iterations](#section-09-loops-and-iterations) + - 09.01. [The for loop](#0901-the-for-loop) + - 09.02. [The while loop](#0902-the-while-loop) + - 09.03. [The do while loop](#0903-the-do-while-loop) + - 09.04. [The for in loop](#0904-the-for-in-loop) + - 09.05. [The for of loop](#0905-the-for-of-loop) + - 09.06. [Break and Continue statement](#0906-break-and-continue-statement) + - 09.07. [for each loop](#0907-for-each-loop) 10. [Conditions - Control Flow](#section-10-conditions) - 10.01. [The if statement](#1001-the-if-statement) | [The if statement and comparison operators](#1001-the-if-statement-and-comparison-operators) - 10.02. [The if else statement](#1002-the-if-else-statement) @@ -122,8 +119,8 @@ Topics include - 11.03. [Create Array by creating an instance of array directly](#1103-create-array-by-creating-an-instance-of-array-directly) - 11.04. [Create Array by using an array constructor](#1104-create-array-by-using-an-array-constructor) - 11.05. [Getting the Length of an Array](#1105-getting-the-length-of-an-array) - - 11.06. [Accessing Looping through an Array Elements](#1106-accessing-looping-through-an-array-elements) | - [Loop through an Array Elements](#1106-loop-through-an-array-elements) + - 11.06. [Accessing Looping through an Array Elements](#1106-accessing-looping-through-an-array-elements) | + [Loop through an Array Elements](#1106-loop-through-an-array-elements) - 11.07. [Adding Editing an Array Elements](#1107-adding-editing-an-array-elements) - 11.08. [Removing Deleting an Array Elements](#1108-removing-deleting-an-array-elements) - 11.09. [Array properties and methods](#1109-array-properties-and-methods) @@ -149,86 +146,79 @@ Topics include - 14.03. [JavaScript DOM Selectors](#1403-javascript-dom-selectors) - 14.04. [JavaScript DOM CSS Styling](#1404-javascript-dom-css-styling) - 14.05. [JavaScript DOM HTML get set attributes](#1405-javaScript-dom-html-get-set-attributes) -15. [What's Next Step?](#section-15-whats-next-step) +15. [DOM (Advanced)](#section-15-dom-advanced) + - 15.01. [Dynamic DOM Manipulation](#1501-dynamic-dom-manipulation) + - 15.02. [Class Manipulation](#1502-class-manipulation) + - 15.03. [Handling Forms and Input Fields](#1503-handling-forms-and-input-fields) +16. [What's Next Step?](#section-16-whats-next-step) -Section 01. Course Introduction -===================== +# Section 01. Course Introduction -01.01. Welcome ---------------------- +## 01.01. Welcome Hi All, I'm **`Dinanath Jayaswal, Senior UI/Web Developer and Adobe Certified Expert Professional`**, I wanna welcome you to JavaScript for Beginners. In this course, I will take you through with the ins and outs of learning JavaScript. This course will help you to learn the fundamentals of programming with JavaScript scripting language, from the basics to advanced topics step-by-step. -01.02. Who is this for? Audience ---------------------- +## 01.02. Who is this for? Audience This course is for any Web Designer, Developer who is interested in dynamic Web Design and Development / Web Programming with JavaScript. Anyone who wants to make a career in Web Development or planning on being a front-end developer must learn JavaScript. -Section 02. Introducing JavaScript -===================== +# Section 02. Introducing JavaScript -02.01. Importance ---------------------- +## 02.01. Importance ### 3 pillars / core Languages/Technologies used for Front End Web Design/Development: 1. **HTML (HyperText Markup Language)** - Markup language, Essential Page Structure/Content, Readable and convey structure to a user, Text Layout Model, page Mark-up, Text, Tags, Data, details for pages, Images, Tables, Anchor Links, Forms - - HTML is an acronym stands for `HyperText Markup Language` which is used for creating `web pages and web applications` - - HTML is not a programming language; it is a markup language that defines the structure of your content ie. document + + - HTML is an acronym stands for `HyperText Markup Language` which is used for creating `web pages and web applications` + - HTML is not a programming language; it is a markup language that defines the structure of your content ie. document 2. **CSS (Cascading Style Sheet)** - Style Sheet language, Page Design / Presentation / Layouts / Styling / Formattings, look and feel, Creative part of Web Pages - - CSS is a stylesheet language that allows you to control the appearance (look and feel) of your webpages + + - CSS is a stylesheet language that allows you to control the appearance (look and feel) of your webpages 3. **`JavaScript (JS) - Scripting language, Dynamic Page Behaviour, Logics, Conditions and Validations, Events (mouse click, hover), Interactivity with User, Dynamic updates in a Web Page`** - - JavaScript is a `scripting language of the web` that allows you to do Interactivity with User-Events, implement Conditions and Validations, Dynamic updates in a Web Page, etc. + - JavaScript is a `scripting language of the web` that allows you to do Interactivity with User-Events, implement Conditions and Validations, Dynamic updates in a Web Page, etc. > **Syntax & Example**: `02.01.js.intro.html` + ```html -
- - - - + + +
` tag
> **Note**:
-JavaScript is the default scripting language in HTML. The old HTML standard attributes like `type="text/javascript"` and `language="javascript"` no longer required in modern browser
+> JavaScript is the default scripting language in HTML. The old HTML standard attributes like `type="text/javascript"` and `language="javascript"` no longer required in modern browser
> **Syntax & Example**: `03.01.js.script.tag.html`
+
```html
+ + + +
- - - -
- - - - - - - + + + + +
``` -03.02. Where to write JavaScript in HTML? ---------------------- -03.02. Where to embed include write put JavaScript in HTML? ---------------------- +## 03.02. Where to write JavaScript in HTML? + +## 03.02. Where to embed include write put JavaScript in HTML? ### JavaScript provides 3 places to write the JavaScript code in our webpage: + 1. Inside the HEAD section 2. Inside the BODY section 3. External JavaScript .js file (separation of concern) @@ -493,17 +473,15 @@ JavaScript is the default scripting language in HTML. The old HTML standard attr - JavaScript programs/code/statements can be placed in the `
` section of an HTML page - As each `` tag blocks the page rendering process until it has fully downloaded and executed the JavaScript code so placing them in the `head section (
element` of the document without any valid reason will significantly impact your website performance -> **Syntax & Example**: `03.02.01.js.head.html` +> **Syntax & Example**: `03.02.01.js.head.html` + ```html
- - - - + + ``` @@ -513,20 +491,18 @@ JavaScript is the default scripting language in HTML. The old HTML standard attr - As blocking nature of `` tag ideally, scripts should be placed at the end of the `body section`, just before the `closing tag`, it will make your web pages load faster since it prevents obstruction of initial page rendering > **Syntax & Example**: `03.02.02.js.body.html` + ```html
```
@@ -536,11 +512,11 @@ JavaScript is the default scripting language in HTML. The old HTML standard attr
- We must have to `extract and separate` our JavaScript behavior code from our HTML markup code
- A simple thumb-rule is if we have a lot of JavaScript code, we can put it into a separate file
- We can use/add/attach an external JavaScript file by using ````
- - One can provide a `full URL (absolute path)` or `relative path` from the current page
+ - ``
+ - One can provide a `full URL (absolute path)` or `relative path` from the current page
- We can create a single external JavaScript file and embed it in many/any HTML page which provide `code re-usability`
-### 03.02.04. Advantages of External JavaScript
+### 03.02.04. Advantages of External JavaScript
- It separates HTML and JavaScript code (separation of concern)
- Code re-usability
@@ -548,32 +524,32 @@ JavaScript is the default scripting language in HTML. The old HTML standard attr
- Web page loads faster /increase the speed of the webpage (Cached JavaScript files)
> **Note**:
-Usually, when an external JavaScript file is downloaded for the first time, it is stored in the browser's cache (like images and style sheets), so it won't need to be get downloaded multiple times from the web server that makes the web pages load faster/quickly.
+> Usually, when an external JavaScript file is downloaded for the first time, it is stored in the browser's cache (like images and style sheets), so it won't need to be get downloaded multiple times from the web server that makes the web pages load faster/quickly.
> **Syntax & Example - `.html file`**: `03.02.03.js.external.html`
+
```html
``` > **Syntax & Example - `.js file`**: `03.02.03.script.js` + ```javascript // external js file // Write all JavaScript code here -alert('welcome to JavaScript written in external file'); -console.log('welcome to JavaScript written in external file'); -document.write('
'); +alert("welcome to JavaScript written in external file"); +console.log("welcome to JavaScript written in external file"); +document.write("
");
```
-03.03. JavaScript Code structure
----------------------
+## 03.03. JavaScript Code structure
+
The syntax of JavaScript is the `set of rules` that define a correctly structured JavaScript program. Let's study some of the building blocks of JavaScript code:
### 03.03.01. JavaScript Statements
@@ -587,10 +563,10 @@ The syntax of JavaScript is the `set of rules` that define a correctly structure
- JavaScript ignores extra line breaks and white spaces
- JavaScript is case sensitive language (VB, Pascal, HTML are case insensitive)
- JavaScript is interpreted not compiled (write and handed over to the web browser)
-- All statement in JavaScript should be terminated by a `Semicolon;`
+- All statement in JavaScript should be terminated by a `Semicolon;`
> **Note**:
-JavaScript statements are composed of: **`Values, Operators, Expressions, Keywords, and Comments`**
+> JavaScript statements are composed of: **`Values, Operators, Expressions, Keywords, and Comments`**
### 03.03.02. Whitespace and Line Breaks
@@ -605,7 +581,7 @@ JavaScript statements are composed of: **`Values, Operators, Expressions, Keywor
- **In most cases, a newline implies a semicolon, But “in most cases” does not mean “always”!**
> **Note**:
-It is a good programming practice to use semicolons; after every statement
+> It is a good programming practice to use semicolons; after every statement
### 03.03.04. Case Sensitivity
@@ -614,7 +590,7 @@ It is a good programming practice to use semicolons; after every statement
- **Example**: `var firstName='Dinanath';` and `var FirstName='Dinanath';` here `firstName & FirstName` are different ie. two different variable
> **Note**:
-Take care/precautions while writing variable and function names in JavaScript
+> Take care/precautions while writing variable and function names in JavaScript
### 03.03.05. JavaScript Code Blocks
@@ -624,13 +600,14 @@ Take care/precautions while writing variable and function names in JavaScript
- An often occurrence of a code block in JavaScript is a JavaScript `function`
> **Syntax & Example**: `03.03.05.script.js`
+
```javascript
// external js file
// Write all JavaScript code here
// define function - block of code to show welcome message
function sayHello() {
- alert('Hello All! Welcome to JavaScript!!');
+ alert("Hello All! Welcome to JavaScript!!");
}
// define function - block of code to show total of two numbers
@@ -638,7 +615,7 @@ function showTotal() {
var num1 = 10;
var num2 = 20;
var total = num1 + num2;
- alert('Total is : ' + total);
+ alert("Total is : " + total);
}
// invoke / run / call a function
@@ -646,25 +623,27 @@ sayHello();
showTotal();
```
-03.04. JavaScript Keywords
----------------------
+## 03.04. JavaScript Keywords
Usually, JavaScript commands/statements start with a `specific keyword` which defines what `action/function` should the browser will perform/do:
-| Keyword | Keyword |Keyword | Keyword |Keyword |
-| ------------------|------------------|------------------|------------------|------------------|
-| break | do ... while | if ... else | try ... catch | const |
-| continue | for | return | var | class |
-| debugger | function | switch | let | import |
-| | | | | |
+| Keyword | Keyword | Keyword | Keyword | Keyword |
+| -------- | ------------ | ----------- | ------------- | ------- |
+| break | do ... while | if ... else | try ... catch | const |
+| continue | for | return | var | class |
+| debugger | function | switch | let | import |
+| | | | | |
### 03.04.01. Reserved Keywords
JavaScript has several reserved keywords. These are the words that you cannot use as identifiers (variable names, function names, and loop labels) in your JavaScript programs. The following list shows the keywords that are reserved in `ECMAScript 6`. It also includes keywords that are `reserved for future` as well as keywords that are `disallowed in strict mode`.
-- arguments, await, break, case, catch, class, const, continue, debugger, default, delete, do, else, enum, eval, export, extends, false, finally, for, function, if, implements, import, in, instanceof, interface, let, new, null, package, private, protected, public, return, static, super, switch, this, throw, true, try, typeof, var, void, while, with, yield,
-03.05. Comments
----------------------
+- arguments, await, break, case, catch, class, const, continue, debugger, default, delete, do, else, enum, eval, export, extends, false, finally, for, function, if, implements, import, in, instanceof, interface, let, new, null, package, private, protected, public, return, static, super, switch, this, throw, true, try, typeof, var, void, while, with, yield,
+
+ 03.05. Comments
+
+---
+
- The comments are a meaningful way to `deliver the message (description to code)` for others/for future reference and to understand/follow the code statements/lines
- Comments are special lines written for other developers as a reference purpose and browser ignores while interpreting
- It is used to add information about the code, warnings or suggestions so that end-user can easily interpret the code (`Why and How of code/program/logic`)
@@ -677,6 +656,7 @@ JavaScript has several reserved keywords. These are the words that you cannot us
### 03.05.01. Types of JavaScript Comments
There are two types of comments in JavaScript:
+
1. Single-line Comments
2. Multi-line Comments
@@ -688,15 +668,16 @@ There are two types of comments in JavaScript:
- Single-line comments do not need closure/closing
> **Syntax & Example**: `03.05.script.js`
+
```javascript
// external js file
// Write all JavaScript code here
// show alert box
-alert('Welcome to JavaScript!');
+alert("Welcome to JavaScript!");
-var firstName = 'Dinanath'; // variable to store firstName
-var lastName = 'Jayaswal'; // variable to store lastName
+var firstName = "Dinanath"; // variable to store firstName
+var lastName = "Jayaswal"; // variable to store lastName
```
#### 03.05.01.02. Multi-line Comments
@@ -704,14 +685,15 @@ var lastName = 'Jayaswal'; // variable to store lastName
- Multi-line comments usually comment out a block of code
- Multi-line comments in JavaScript can comment on bigger parts (a few lines) of code
- Multi-line comments are more convenient as it can be used to comment single as well as multi-line comments
-- Multiline comments start with `forward slash and an asterisk, /* and also end with an asterisk and a forward slash */`: /* multi-line comment */
+- Multiline comments start with `forward slash and an asterisk, /* and also end with an asterisk and a forward slash */`: /_ multi-line comment _/
- Multi-line comments need closing
- Multi-line comments are more often used for `formal documentation`
-> **Syntax & Example**: `03.05.script.js`
+> **Syntax & Example**: `03.05.script.js`
+
```javascript
/* show alert box */
-alert('Welcome to JavaScript!');
+alert("Welcome to JavaScript!");
/* This is a multiline comment.
A code block can be commented on. */
@@ -720,11 +702,10 @@ A code block can be commented on. */
var lastName = 'Jayaswal'; // variable to store lastName */
```
-Section 04. JavaScript Language Fundamentals
-=====================
+# Section 04. JavaScript Language Fundamentals
+
+## 04.01. Generating Output
-04.01. Generating Output
----------------------
- JavaScript does not have any `display or built-in print` functions
- Many times we may need to generate output from your JavaScript code like `see the value of a variable`, or `write a message to browser console` to help you `debug an issue` in your running JavaScript code, and so on
- That is why you have to use the JavaScript output function to generating output `(browser window or browser console dialog boxes, writing output into an HTML element, etc.)`
@@ -734,22 +715,24 @@ Section 04. JavaScript Language Fundamentals
1. Writing into an alert box with `alert() or window.alert()`
2. Writing into browser console with `console.log()`
-3. Writing into the HTML / Browser Window with `document.write()`
+3. Writing into the HTML / Browser Window with `document.write()`
4. Write into an element of HTML / Inserting Output Inside an HTML Element with `innerHTML`
#### 04.01.01. Displaying Output in Alert Dialog Boxes: alert() or window.alert()
-- One can use `alert dialog boxes` to display the message or output data to the user
+
+- One can use `alert dialog boxes` to display the message or output data to the user
- An alert dialog box is created using the `alert() or window.alert()` method
- A small pop-up box appears with a closing button to close alert-box
- This method is great for short and rapid informative messages which can be instantly closed
> **Syntax & Example**: `04.01.01.script.js`
+
```javascript
// external js file
// Write all JavaScript code here
-alert('I am Dinanath Jayaswal');
-window.alert('We are learning JavaScript');
+alert("I am Dinanath Jayaswal");
+window.alert("We are learning JavaScript");
```
#### 04.01.02. Writing Output to Browser Console: console.log()
@@ -759,16 +742,17 @@ window.alert('We are learning JavaScript');
- This is a simple, easy but very powerful method for generating detailed output
> **Syntax & Example**: `04.01.02.script.js`
+
```javascript
// external js file
// Write all JavaScript code here
-console.log('I am Dinanath Jayaswal');
-console.log('We are learning JavaScript');
+console.log("I am Dinanath Jayaswal");
+console.log("We are learning JavaScript");
```
> **Note**:
-Use `F12` key on the keyboard to open the `developer tools` then click on the `console tab`. You can write basic JavaScript statements directly in the browser console panel/tab and get the output.
+> Use `F12` key on the keyboard to open the `developer tools` then click on the `console tab`. You can write basic JavaScript statements directly in the browser console panel/tab and get the output.
#### 04.01.03. Writing Output into the HTML / Browser Window: document.write()
@@ -776,50 +760,52 @@ Use `F12` key on the keyboard to open the `developer tools` then click on the `c
- Programmers do ues document.write() for `testing purposes`
> **Syntax & Example**: `04.01.03.script.js`
+
```javascript
// external js file
// Write all JavaScript code here
-document.write('I am Dinanath Jayaswal');
-document.write('We are learning JavaScript');
+document.write("I am Dinanath Jayaswal");
+document.write("We are learning JavaScript");
```
#### 04.01.04. Inserting Output Inside an HTML Element: innerHTML
- We can write or insert output inside an HTML element using the element's `innerHTML` property
-- First we need to select the element using a method such as `document.getElementById(id)`
+- First we need to select the element using a method such as `document.getElementById(id)`
> **Note**:
-HTML element manipulating is fully dependent on JavaScript DOM manipulation concepts
+> HTML element manipulating is fully dependent on JavaScript DOM manipulation concepts
> **Syntax & Example**: `04.01.04.script.js`
+
```javascript
/// external js file
// Write all JavaScript code here
// Writing text string inside an element
-document.getElementById('mainHeadingText').innerHTML = 'Heading Text change dynamically on run-time';
+document.getElementById("mainHeadingText").innerHTML =
+ "Heading Text change dynamically on run-time";
-var paraText = document.getElementById('mainParaText');
-paraText.innerHTML = 'This Paragraphic text inserted dynamically through innerHTML method.';
+var paraText = document.getElementById("mainParaText");
+paraText.innerHTML =
+ "This Paragraphic text inserted dynamically through innerHTML method.";
```
With JavaScript, we can do many cool and dynamic pieces of stuff (Image Gallery, Games, Forms) but for that one should be familiar with core essentials/building blocks of JavaScript programming language like Variables, Functions, Operators, Loops, Conditional Statements, Array, Objects, Events, DOM (Document Object Model), etc. which will cover in coming lessons.
-Section 05. Variables
-=====================
+# Section 05. Variables
-05.01. What is Variable?
----------------------
+## 05.01. What is Variable?
Variables are one of the most fundamental concepts in JavaScript and other all programming languages of the world.
- A variable is `container to store/hold the data/information`
-- Developers/Programmers use Variable to `store/hold the data/information temporarily` in computer memory
+- Developers/Programmers use Variable to `store/hold the data/information temporarily` in computer memory
- A variable is a kind of data holder where we can store some value for programming or calculation purpose
- A JavaScript variable is simply a `name of the storage location (named containers/named storage)` for data
-- Variables are symbolic names for values
-- Variables are used to store data of different types like a string of text, numbers, boolean values like true/false, an array of data, etc.
+- Variables are symbolic names for values
+- Variables are used to store data of different types like a string of text, numbers, boolean values like true/false, an array of data, etc.
- The data or value stored in the variables can be set, updated, and retrieved whenever needed
- Variables are declared using the keyword `var` keyword
- The `assignment operator (=)` is used to assign value to a variable, like this: `var varName = value;` or `var firstName = 'JavaScript';`
@@ -833,31 +819,32 @@ Variables are one of the most fundamental concepts in JavaScript and other all p
> **Note**:
-In ES6 `'let'` and `'const'` keywords are used to defined variables
+> In ES6 `'let'` and `'const'` keywords are used to defined variables
> **Note**:
-As a best practice of ES6, from now onwards variables must be define with `let` keyword: `let techName = 'JavaScript' ; `
+> As a best practice of ES6, from now onwards variables must be define with `let` keyword: `let techName = 'JavaScript' ; `
> **Syntax & Example**: `05.01.script.js`
+
```javascript
// variables defined to hold different types of data
-var techName = 'JavaScript'; // String literal
+var techName = "JavaScript"; // String literal
var version = 6; // Number literal
var isDone = true; // Boolean literal
-console.log('Learning '+techName+version);
+console.log("Learning " + techName + version);
```
-05.02. Declaring variable without a value
----------------------
-05.02. Creating a variable without a value
----------------------
+## 05.02. Declaring variable without a value
+
+## 05.02. Creating a variable without a value
Variables can also be declared without having any initial values assigned to them. This is useful for variables that are supposed to hold values like user inputs, calculations, status updates, etc.
> **Syntax & Example**: `05.01.script.js`
+
```javascript
// Declaring Variables
var techName;
@@ -865,11 +852,11 @@ var version;
var isDone;
// Assigning value
-techName = 'JavaScript';
+techName = "JavaScript";
version = 6;
isDone = true;
-console.log('Learning '+techName+version);
+console.log("Learning " + techName + version);
// ------------------------------
@@ -877,32 +864,37 @@ console.log('Learning '+techName+version);
var userName;
// Assigning value
-userName = 'Dinanath';
+userName = "Dinanath";
-console.log('Welcome '+userName);
+console.log("Welcome " + userName);
```
-05.03. Declaring multiple variables at once
----------------------
+## 05.03. Declaring multiple variables at once
We can also `declare multiple variables` and set their initial values in a single statement, each variable is `separated by comma`.
> **Syntax & Example**: `05.01.script.js`
+
```javascript
// Declaring multiple variables
-var techName = 'JavaScript', version = 6, isDone = true;
+var techName = "JavaScript",
+ version = 6,
+ isDone = true;
// Declaring multiple variables in multiple lines for readability
-var techName = 'JavaScript',
-version = 6,
-isDone = true;
+var techName = "JavaScript",
+ version = 6,
+ isDone = true;
-console.log('Learning '+techName+version);
+console.log("Learning " + techName + version);
// ------------------------------
// Declaring multiple variables
-var firstName = 'Dinanath', lastName = 'Jayaswal', age = 35, isMarried = 'true';
+var firstName = "Dinanath",
+ lastName = "Jayaswal",
+ age = 35,
+ isMarried = "true";
// Declaring multiple variables in multiple lines for readability
/* var firstName = 'Dinanath',
@@ -910,15 +902,14 @@ lastName = 'Jayaswal',
age = 35,
isMarried = 'true'; */
-console.log('I am ' + firstName + ' ' + lastName);
+console.log("I am " + firstName + " " + lastName);
```
-05.04. Variable Naming Conventions
----------------------
-05.04. Variable Naming Conventions (Identifiers)
----------------------
+## 05.04. Variable Naming Conventions
+
+## 05.04. Variable Naming Conventions (Identifiers)
-All JavaScript variables must be `identified`/referred/defined/named with `unique names`, called as `identifiers`. The naming rules in JavaScript are not much different from any other programming language.
+All JavaScript variables must be `identified`/referred/defined/named with `unique names`, called as `identifiers`. The naming rules in JavaScript are not much different from any other programming language.
- There are some rules while declaring/naming a JavaScript variable (also known as `identifiers`)
- Identifiers are `simply names` in JavaScript
@@ -928,9 +919,9 @@ All JavaScript variables must be `identified`/referred/defined/named with `uniqu
**The basic rules for defining/assigning names for variables (unique identifiers) are:**
- A variable name must `start with a letter, underscore (_), or dollar sign ($)`
- - **Example**: var firstName, var _firstName, var $firstName;
+ - **Example**: var firstName, var \_firstName, var $firstName;
- Names can contain letters, digits, underscores, and dollar signs
- - **Example**: var $num_total1;
+ - **Example**: var $num_total1;
- A variable name `cannot start with a number or special characters`
- **Example**: var 1num_total, var .num_total
- A variable name `cannot contain spaces`
@@ -938,33 +929,36 @@ All JavaScript variables must be `identified`/referred/defined/named with `uniqu
- A variable Names are `case sensitive`
- **Example**: var firstName='Dinanath'; and var FirstName='Dinanath'; here `firstName & FirstName` are different ie. two different variable
- A variable name cannot be a `JavaScript keyword or a JavaScript reserved word`
- - **Example**: var var; var switch; var for; var true;
+ - **Example**: var var; var switch; var for; var true;
- One should Always give `meaningful/descriptive names` to variables
- for naming the variables that contain multiple words, `camelCase` method is commonly used (camelCase is the default method for identifier naming)
> **Note**:
-In the programming world, there have been two most popular methods/mechanism of writing multiple words identifiers: (Underscore, Camel Case)
+> In the programming world, there have been two most popular methods/mechanism of writing multiple words identifiers: (Underscore, Camel Case)
1. **Underscore**: first_name, last_name, date_of_birth, is_passed, native_place
-2. **Camel Case:**: firstName, lastName, dateOfBirth, isPassed, nativePlace OR
: FirstName, LastName, DateOfBirth, IsPassed, NativePlace
+2. **Camel Case:**: firstName, lastName, dateOfBirth, isPassed, nativePlace OR
: FirstName, LastName, DateOfBirth, IsPassed, NativePlace
> **Syntax & Example**: `05.04.script.js`
+
```javascript
// variables defined to hold different types of data
-var _firstName = 'JavaScript';
+var _firstName = "JavaScript";
var $version = 6;
var $num_total1 = 10;
-window.alert('variables details: ' + _firstName + ' ' + $version + ' ' + $num_total1);
+window.alert(
+ "variables details: " + _firstName + " " + $version + " " + $num_total1
+);
// wrong identifiers
// var #name;
```
-05.05. Variable Scope
----------------------
+## 05.05. Variable Scope
The scope of a variable is the region/coverage of your program in which it is defined and exist/available. JavaScript variables have two scopes:
+
1. Local Variables
2. Global Variables
@@ -976,18 +970,19 @@ The scope of a variable is the region/coverage of your program in which it is de
- `Function parameters` are always local to that function
> **Note**:
-In the function body, a `local variable takes precedence` over a global variable with the same name.
+> In the function body, a `local variable takes precedence` over a global variable with the same name.
> **Syntax & Example**: `05.05.01.script.js`
+
```javascript
// global variable
-var globalName = 'Global';
+var globalName = "Global";
window.alert(globalName);
function showName() {
// local variable
- var localName = 'Local';
+ var localName = "Local";
window.alert(localName);
window.alert(globalName); // recall global variable
@@ -1002,80 +997,84 @@ window.alert(localName);
#### 05.05.02. Global Variables
-- A variable `declared outside the function/at the root` or declared `with window object` is known as a global variable
-- A JavaScript global variable is accessible from any function
+- A variable `declared outside the function/at the root` or declared `with window object` is known as a global variable
+- A JavaScript global variable is accessible from any function
- A global variable has a global scope which means it can be defined and accessible anywhere in JavaScript code/program
> **Syntax & Example**: `05.05.02.script.js`
+
```javascript
// global variable
-var globalName = 'Global';
+var globalName = "Global";
window.alert(globalName);
function showName() {
// local variable
- var globalName = 'Local';
+ var globalName = "Local";
window.alert(globalName);
// define global variable with window
window.globalVersion = 29;
- window.alert('global variable from inside function: ' + window.globalVersion);
+ window.alert("global variable from inside function: " + window.globalVersion);
}
// invoke/call/run function
showName();
// access global variable defined inside function
-window.alert('global variable from outside function: ' + window.globalVersion);
+window.alert("global variable from outside function: " + window.globalVersion);
```
-05.06. The let and const keywords ES6
----------------------
+## 05.06. The let and const keywords ES6
+
ES6 introduces two new keywords `let` and `const` for declaring variables. The `var, let and const` keywords are almost the same, just a few differences with the scope.
-- In older programs` var` is used a lot which declares a variable `(function-scoped variables)`, but in a slightly different `old` way, with scope issues
-- Both `let` and `const` keywords declare variables, `scoped at block-level ({})`
+- In older programs` var` is used a lot which declares a variable `(function-scoped variables)`, but in a slightly different `old` way, with scope issues
+- Both `let` and `const` keywords declare variables, `scoped at block-level ({})`
- Block scoping means that a new scope is created `between a pair of curly brackets {}`
### 05.06.01. The let Keyword
`ES6` introduces the new `let` keyword for declaring variables. Prior to ES6, the only way to declare a variable in JavaScript was the var keyword. Let's see what's the difference:
+
- Variables declared with the `var` keyword are `function-scoped` and can be `hoisted` at the top within its scope
- Variables declared with `let` keyword are `block-scoped ({})` and they are not hoisted
> **Syntax & Example**: `05.06.01.script.js`
+
```javascript
// traditional var syntax
-var techName1 = 'JavaScript';
+var techName1 = "JavaScript";
-for(var i = 1; i <= 5; i++) {
- console.log('i : ' + i); // 1,2,3,4,5
- console.log('inside block:' + techName1);
+for (var i = 1; i <= 5; i++) {
+ console.log("i : " + i); // 1,2,3,4,5
+ console.log("inside block:" + techName1);
var version1 = 100;
}
-console.log('outside: ' + i);
-console.log('outside: ' + version1);
+console.log("outside: " + i);
+console.log("outside: " + version1);
// ------------------------------
// ES6 syntax
-let techName2 = 'LiveScript';
+let techName2 = "LiveScript";
-for(let n = 1; n <= 5; n++) {
- console.log('n : ' + n); // 1,2,3,4,5
- console.log('inside block:' + techName2);
+for (let n = 1; n <= 5; n++) {
+ console.log("n : " + n); // 1,2,3,4,5
+ console.log("inside block:" + techName2);
let version2 = 100;
}
console.log(n); // undefined
-console.log('outside: ' + version2); // undefined
+console.log("outside: " + version2); // undefined
```
### 05.06.02. The const Keyword
-`ES6` introduces the new `const` keyword for declaring variables.
+`ES6` introduces the new `const` keyword for declaring variables.
+
- Use `const` to declare a constant `(read-only / unchanging)` variable
- Constants are `read-only`, you `cannot reassign new values` to them
- In Programm/logic when the variable will never change, they can be declared as `const`
@@ -1084,6 +1083,7 @@ console.log('outside: ' + version2); // undefined
- However, you can change `object properties` or `array elements`
> **Syntax & Example**: `05.06.02.script.js`
+
```javascript
// traditional var syntax
var PI1 = 3.14;
@@ -1096,47 +1096,44 @@ console.log(PI1); // 100
// ES6 syntax
const PI2 = 6.28;
-console.log('ES6 syntax const: ' + PI2); // 6.28
+console.log("ES6 syntax const: " + PI2); // 6.28
PI2 = 100; // error
```
-Section 06. Data types
-=====================
+# Section 06. Data types
-06.01. Data types
----------------------
+## 06.01. Data types
A variable in JavaScript can contain `any type of data`. Data types specify what `kind of data` can be stored and manipulated within the variable in a program. In JavaScript, different data types are available to hold different types of values/data. There are `two main categories/types` of data types in JavaScript:
+
1. Primitive (Primary or Value) data type
- - String
- - Number
- - Boolean
- - Undefined
- - Null
- - Symbol (newly introduced in ES6)
-2. Non-primitive (Reference or Composite) data type
- - Array
- - Object
- - Function
-
-06.02. Primitive data type
----------------------
-06.02. Primitive, Primary or Value data type
----------------------
+ - String
+ - Number
+ - Boolean
+ - Undefined
+ - Null
+ - Symbol (newly introduced in ES6)
+2. Non-primitive (Reference or Composite) data type - Array - Object - Function
+
+ 06.02. Primitive data type
+
+---
+
+## 06.02. Primitive, Primary or Value data type
Primitive data types can `hold only one value at a time`. Primitives are `compared by value`. Two values are strictly equal if they have the same value.
There are different types of primitive data types in JavaScript. They are as follows:
-| Data Type | Description |
-| ----------------|-----------------------------------------------------------------------------|
-| String | represent textual data. e.g. "welcome" or 'to javascript' |
-| Number | represents numeric values e.g. 10, 100.29 |
-| Boolean | represents boolean value either false or true |
-| Undefined | represents an undefined value (a variable declared but value not assigned) |
-| Null | represents null i.e. no value at all |
-| | |
+| Data Type | Description |
+| --------- | -------------------------------------------------------------------------- |
+| String | represent textual data. e.g. "welcome" or 'to javascript' |
+| Number | represents numeric values e.g. 10, 100.29 |
+| Boolean | represents boolean value either false or true |
+| Undefined | represents an undefined value (a variable declared but value not assigned) |
+| Null | represents null i.e. no value at all |
+| | |
### 06.02.01. String
@@ -1146,18 +1143,18 @@ There are different types of primitive data types in JavaScript. They are as fol
- **Example**: `06.02.script.js`
```js
-var firstName = "Java";
-var lastName = 'Script';
+var firstName = "Java";
+var lastName = "Script";
```
### 06.02.02. Number
- The number data type simply defined without quotes is used to represent positive or negative numbers with or without a decimal place
- Many mathematical operations can be done on numbers, e.g. `multiplication *, division /, addition +, subtraction`, and so on
-- **Example**:
+- **Example**:
```js
-var age = 25;
+var age = 25;
var id = 1;
```
@@ -1166,10 +1163,10 @@ var id = 1;
- The Boolean data type can hold only two values: `true or false`
- true = ON / yes / correct / 1, false = OFF / no, incorrect / 0
- Boolean data types is often used in `conditional testing` of code
-- **Example**:
+- **Example**:
```js
-var isDone = true;
+var isDone = true;
var isMarried = false;
```
@@ -1179,7 +1176,7 @@ var isMarried = false;
- The undefined data type can only have one value-the special value undefined
- A Variable has been declared, but `not assigned a value`
- A variable `without a value`, The type is also undefined
-- **Example**:
+- **Example**:
```js
var firstName;
@@ -1191,17 +1188,16 @@ var country;
- A null value means that there is no value
- The special value which represents `“ nothing”, “empty” or “value unknown”`
- It is not equivalent to an empty string ('' or ' ', "", " "), it is simply nothing
-- **Example**:
+- **Example**:
```js
var firstName = null;
var id = null;
```
-06.03. Non-primitive data type
----------------------
-06.03. Non-primitive, Reference or Composite data type
----------------------
+## 06.03. Non-primitive data type
+
+## 06.03. Non-primitive, Reference or Composite data type
- Non-primitive/Reference data types can hold `collections of values and more complex entities`
- Non-primitive values are being compared by `reference` instead of value
@@ -1210,38 +1206,38 @@ var id = null;
There are different types of non-primitive data types in JavaScript. They are as follows:
-| Data Type | Description |
-| ----------------|-----------------------------------------------------------------------|
-| Array | represents a group of similar value (multiple values in one variable) |
-| Object | represents an instance through which we can access members (property & value) |
-| Function | represents function (bunch/block of line to execute once) |
-| | |
+| Data Type | Description |
+| --------- | ----------------------------------------------------------------------------- |
+| Array | represents a group of similar value (multiple values in one variable) |
+| Object | represents an instance through which we can access members (property & value) |
+| Function | represents function (bunch/block of line to execute once) |
+| | |
-06.04. JavaScript has Dynamic Types
----------------------
+## 06.04. JavaScript has Dynamic Types
We have two types of programming languages:
+
1. Static languages
- - Declare a variable, the type of the variable is set and it cannot be changed in the future
+ - Declare a variable, the type of the variable is set and it cannot be changed in the future
2. Dynamic languages
- - Variable can change at run time (one variable can store different types of value as per requirement, we again assign any value any time as per logic, requirements)
+ - Variable can change at run time (one variable can store different types of value as per requirement, we again assign any value any time as per logic, requirements)
-- A JavaScript `variable can contain/hold any data ie. any type of data`, A variable at one moment can be a number and at another moment be a string, boolean
+- A JavaScript `variable can contain/hold any data ie. any type of data`, A variable at one moment can be a number and at another moment be a string, boolean
- It simply means that `same variable can be used to hold different data types`
- JavaScript is a dynamic type language, means you don't need to specify a type of the variable because it is dynamically used by JavaScript engine
> **Syntax & Example**: `06.04.script.js`
+
```javascript
-let name = 'JavaScript';
+let name = "JavaScript";
name = false;
name = 100;
alert(name);
-alert(typeof(name));
+alert(typeof name);
```
-06.05. The typeof Operator
----------------------
+## 06.05. The typeof Operator
- The typeof operator returns the `type of the argument`
- It’s useful to process values of different types differently or want to perform a quick data type check
@@ -1249,44 +1245,45 @@ alert(typeof(name));
- It can be used with or without parentheses `(typeof(x)` or `typeof x`
> **Syntax & Example**: `06.05.script.js`
+
```javascript
// use typeof to find data type of variables
// Strings
alert(typeof "Hello"); // "string"
-alert(typeof '12'); // "string"
+alert(typeof "12"); // "string"
// Numbers
-console.log(typeof(100)); // "number"
-console.log(typeof(100.29)); // "number"
+console.log(typeof 100); // "number"
+console.log(typeof 100.29); // "number"
// Booleans
alert(typeof true); // "boolean"
-alert(typeof(1 == 2)); // "boolean"
+alert(typeof (1 == 2)); // "boolean"
// Undefined
console.log(typeof undefined); // "undefined"
var init;
-console.log('type of init: ' + typeof init); // "undefined"
+console.log("type of init: " + typeof init); // "undefined"
// Null
console.log(typeof null); // "object"
var initObject = null;
-console.log('type of initObject: ' + typeof initObject); // "object"
+console.log("type of initObject: " + typeof initObject); // "object"
// Objects
-alert(typeof {name: 'Dinanath', age: 35}); // "object"
+alert(typeof { name: "Dinanath", age: 35 }); // "object"
alert(typeof document); // "object"
alert(typeof window); // "object"
// Arrays
var techArray = [];
-console.log('type of techArray: ' + typeof techArray); // "object"
-console.log(typeof ['JavaScript', 'jQuery', 'Angular']); // "object"
-console.log(typeof ['Dinanath', 35, 'India']); // "object"
+console.log("type of techArray: " + typeof techArray); // "object"
+console.log(typeof ["JavaScript", "jQuery", "Angular"]); // "object"
+console.log(typeof ["Dinanath", 35, "India"]); // "object"
// Functions
-console.log(typeof function(){}); // "function"
+console.log(typeof function () {}); // "function"
console.log(typeof alert); // "function"
console.log(typeof window.alert); // "function"
@@ -1294,16 +1291,16 @@ console.log(typeof window.alert); // "function"
alert(typeof Symbol("dob")); // "symbol"
```
-06.06. Type conversion
----------------------
-06.06. typeof parseInt parseFloat
----------------------
+## 06.06. Type conversion
+
+## 06.06. typeof parseInt parseFloat
- Type conversion is nothing but taking a variable and changing its data type as per needs requirements and logic
- In JavaScript as and when we take an `input in the form, its data type is a string by default`, so do any calculations we need to `parse` to `integer/int or the number`
- Data type conversion can be either implicit (automatic) or explicit (forcefully/manually)
-> **Syntax & Example**:
+> **Syntax & Example**:
+
```javascript
// Number to String conversion
let num1 = 100;
@@ -1331,18 +1328,18 @@ console.log(curDate);
console.log(typeof curDate);
// Array to String conversion
-let numArray = String([1,2,3,4,5]);
+let numArray = String([1, 2, 3, 4, 5]);
console.log(numArray);
console.log(typeof numArray);
// toString() method
-let curString = (1000).toString
-let curString = (true).toString
+let curString = (1000).toString;
+let curString = true.toString;
// String to Number conversion
-let num2 = '100';
+let num2 = "100";
console.log(num2);
console.log(typeof num2);
@@ -1359,55 +1356,57 @@ let boolValue2 = Number(false);
// parseInt() method
-let curNumber = parseInt('100');
-let curNumber = parseFloat('100.41');
+let curNumber = parseInt("100");
+let curNumber = parseFloat("100.41");
```
-06.07. Type coercion
----------------------
+## 06.07. Type coercion
- Type coercion simply refer to the JavaScript ability to convert type automatically (developer does not do it but JavaScript does it for us)
- Type coercion is the process of converting a value from one type to another (such as string to a number, object to boolean, and so on)
- JavaScript engine converts the type as per its rules (implicit ie. automatic conversion of data type)
-> **Syntax & Example**:
+> **Syntax & Example**:
+
```javascript
-const num1 = '20';
+const num1 = "20";
const num1 = 10;
-const sum = (num1) + (num2);
+const sum = num1 + num2;
console.log(sum);
console.log(typeof sum);
```
-Section 07. Operators
-=====================
+# Section 07. Operators
-07.01. What is the Operator?
----------------------
-- We know/use many operators since our initial school days, they are things like addition +, multiplication *, subtraction -, open-close round bracket ( ) or square bracket [ ]
+## 07.01. What is the Operator?
+
+- We know/use many operators since our initial school days, they are things like addition +, multiplication \*, subtraction -, open-close round bracket ( ) or square bracket [ ]
- Operators are symbols/keywords that tell the JavaScript engine to `perform some sort of actions`
- JavaScript operators are symbols that are used to perform operations on operands
- Operators used along with our variables and constants to create
-expressions to implement logic and algorithms
+ expressions to implement logic and algorithms
> **Note**:
-Let us take a simple expression `var sum = 1 + 2`;
-- Here 1 and 2 are called `operands` and
+> Let us take a simple expression `var sum = 1 + 2`;
+
+- Here 1 and 2 are called `operands` and
- `=` & `+` are called the `operator`
- `= is the assignment` operator, `+ is the arithmetic` operator
> **Syntax & Example**: `07.01.script.js`
+
```javascript
-// Lets take a look on simple expression
+// Lets take a look on simple expression
var sum = 1 + 2;
-// Here 1 and 2 are called `operands` and
+// Here 1 and 2 are called `operands` and
// `=` & `+` are called the `operator`
// `= is the assignment` operator, `+ is the arithmetic` operator
```
**JavaScript supports the following types of operators**:
+
1. Arithmetic Operators
2. Assignment Operators
3. Logical Operators
@@ -1416,117 +1415,119 @@ var sum = 1 + 2;
6. String Operators
7. Bitwise Operators
-07.02. Arithmetic Operators
-----------------------
+ 07.02. Arithmetic Operators
+
+---
- Arithmetic operators are used to performing arithmetic operations (just like mathematics - calculations) on numbers/the operands
JavaScript supports the following Arithmetic operators (List of Arithmetic operators):
-| Operators | Description | Example / Result |
-| ----------|---------------------------------------|-------------------------------------------------|
-| + | Addition | 10 + 20 = 30 (Sum of num1 and num2) |
-| - | Subtraction | 20 - 10 = 10 (Difference of num1 and num2) |
-| * | Multiplication | 10 * 20 = 200 (Product of num1 and num2) |
-| / | Division | 20 / 10 = 2 (Quotient of num1 and num2) |
-| % | Modulus (Division Remainder) | 20 % 10 = 0 (Remainder of num1 divided by num2) |
-| ++ | Increment | var num1 = 100; num1++; Now num1 = 11 |
-| -- | Decrement | var num1 = 100; num1--; Now num1 = 9 |
-| ** | Exponentiation (ES2016 / ES6) | 2 ** 2 = 4 ; 2 ** 3 = 8 (Multiply num1 for num2 times) |
-| | | |
+| Operators | Description | Example / Result |
+| --------- | ----------------------------- | ------------------------------------------------------ |
+| + | Addition | 10 + 20 = 30 (Sum of num1 and num2) |
+| - | Subtraction | 20 - 10 = 10 (Difference of num1 and num2) |
+| \* | Multiplication | 10 \* 20 = 200 (Product of num1 and num2) |
+| / | Division | 20 / 10 = 2 (Quotient of num1 and num2) |
+| % | Modulus (Division Remainder) | 20 % 10 = 0 (Remainder of num1 divided by num2) |
+| ++ | Increment | var num1 = 100; num1++; Now num1 = 11 |
+| -- | Decrement | var num1 = 100; num1--; Now num1 = 9 |
+| \*\* | Exponentiation (ES2016 / ES6) | 2 ** 2 = 4 ; 2 ** 3 = 8 (Multiply num1 for num2 times) |
+| | | |
> **Syntax & Example**: `07.02.script.js`
+
```javascript
// Arithmetic operators
var num1 = 10;
var num2 = 4;
-alert('Addition ' + (num1 + num2)); // 14
-alert('Subtraction ' + (num1 - num2)); // 6
-alert('Multiplication ' + num1 * num2); // 40
-alert('Division ' + num1 / num2); // 2.5
-alert('Modulus reminder ' + num1 % num2); // 2
-num1++
-alert('after Increment ' + num1); // 11
-num2--;
-alert('after Decrement ' + num2); // 3
+alert("Addition " + (num1 + num2)); // 14
+alert("Subtraction " + (num1 - num2)); // 6
+alert("Multiplication " + num1 * num2); // 40
+alert("Division " + num1 / num2); // 2.5
+alert("Modulus reminder " + (num1 % num2)); // 2
+num1++;
+alert("after Increment " + num1); // 11
+num2--;
+alert("after Decrement " + num2); // 3
num1 = 10;
num2 = 4;
-alert('Exponentiation ' + (num1 ** num2)); // (10 ** 4) = 10* 10 * 10 * 10 = 10000
+alert("Exponentiation " + num1 ** num2); // (10 ** 4) = 10* 10 * 10 * 10 = 10000
```
-07.03. Assignment Operators
----------------------
+## 07.03. Assignment Operators
- The Assignment operators are used to assign particular values to variables
JavaScript supports the following Assignment operators (List of Assignment operators):
-| Operators | Description | Example / Result |
-| ----------|---------------------------------------|---------------------------------------|
-| = | Simple Assignment | 10 + 20 = 30; / var total = num1 + num2; (assigns a value to the variable) |
-| += | Add and assign | var num1 = 10; num1 += 20; Now num1 = 30 (assigns and adds value to the variable, num1 += 20; is equivalent to num1 = num1 + 20;) |
-| -= | Subtract and assign | var num1 = 10; num1 -= 5; Now num1 = 5 (assigns and subtract value to the variable, num1 -= 5; is equivalent to num1 = num1 - 5;) |
-| *= | Multiply and assign | var num1 = 10; num1 *= 5; Now num1 = 50 (assigns and multiply value to variable, num1 *= 5; is equivalent to num1 = num1 * 5;) |
-| /= | Divide and assign | var num1 = 10; num1 /= 5; Now num1 = 2 (assigns and divide value to the variable, num1 /= 5; is equivalent to num1 = num1 / 5;) |
-| %= | Modulus and assign | var num1 = 10; num1 %= 5; Now num1 = 0 (assigns and Modulus value to the variable, num1 %= 5; is equivalent to num1 = num1 % 5;) |
-| | | |
+| Operators | Description | Example / Result |
+| --------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
+| = | Simple Assignment | 10 + 20 = 30; / var total = num1 + num2; (assigns a value to the variable) |
+| += | Add and assign | var num1 = 10; num1 += 20; Now num1 = 30 (assigns and adds value to the variable, num1 += 20; is equivalent to num1 = num1 + 20;) |
+| -= | Subtract and assign | var num1 = 10; num1 -= 5; Now num1 = 5 (assigns and subtract value to the variable, num1 -= 5; is equivalent to num1 = num1 - 5;) |
+| \*= | Multiply and assign | var num1 = 10; num1 _= 5; Now num1 = 50 (assigns and multiply value to variable, num1 _= 5; is equivalent to num1 = num1 \* 5;) |
+| /= | Divide and assign | var num1 = 10; num1 /= 5; Now num1 = 2 (assigns and divide value to the variable, num1 /= 5; is equivalent to num1 = num1 / 5;) |
+| %= | Modulus and assign | var num1 = 10; num1 %= 5; Now num1 = 0 (assigns and Modulus value to the variable, num1 %= 5; is equivalent to num1 = num1 % 5;) |
+| | | |
> **Syntax & Example**: `07.03.script.js`
+
```javascript
// Assignment operators
var num1 = 10;
-var num2 = 20
+var num2 = 20;
// old methodology
// num1 = num1 + num2;
// console.log(num1); // 30
// new techniques
-num1 += num2;
+num1 += num2;
console.log(num1); // 30
-// num2 -= num1;
+// num2 -= num1;
// console.log(num2); // 10
-// num1 *= num2;
+// num1 *= num2;
// console.log(num1); // 200
-// num2 /= num1;
+// num2 /= num1;
// console.log(num2); // 2
```
-07.04. Logical Operators
----------------------
+## 07.04. Logical Operators
- The Logical operators are used to make decisions based on multiple conditions
- The logical operators are typically used to combine multiple conditional statements and evaluate
JavaScript supports the following Logical operators (List of Logical operators):
-| Operators | Description | Example / Result |
-| ----------------|---------------------------------------|---------------------------------------|
-| && | Logical AND | x && y; (True if both operands like x and y are true) |
-| || | Logical OR | x || y; (True if either x or y is true)|
-| ! | Logical NOT | !x; (True if x is not true) |
-| | | |
+| Operators | Description | Example / Result |
+| ------------ | ----------- | ----------------------------------------------------- |
+| && | Logical AND | x && y; (True if both operands like x and y are true) |
+| || | Logical OR | x || y; (True if either x or y is true) |
+| ! | Logical NOT | !x; (True if x is not true) |
+| | | |
> **Syntax & Example**: `07.04.01.script.js`
+
```javascript
// Logical operators - basic examples
// && (Logical AND) - returns true if both operands are true
-console.log('true && true: ', true && true);
-console.log('true && false: ', true && false);
-console.log('false && true: ', false && true);
+console.log("true && true: ", true && true);
+console.log("true && false: ", true && false);
+console.log("false && true: ", false && true);
// ------------------------------
// || (Logical OR) - returns true if one of the operand is true
-console.log('true || true: ', true || true);
-console.log('true || false: ', true || false);
-console.log('false || true: ', false || true);
+console.log("true || true: ", true || true);
+console.log("true || false: ", true || false);
+console.log("false || true: ", false || true);
// ------------------------------
@@ -1534,11 +1535,13 @@ console.log('false || true: ', false || true);
var isSeniorCitizen = true;
var isYoungGeneration = !isSeniorCitizen;
-console.log('isYoungGeneration: ', isYoungGeneration);
+console.log("isYoungGeneration: ", isYoungGeneration);
```
+
> **Syntax & Example**: `07.04.02.script.js`
+
```javascript
// Logical operators - real world scenario/example
@@ -1549,23 +1552,22 @@ var isEligibleForLoan;
// check eligibility with && Logical AND operator
isEligibleForLoan = isEarningHighIncome && isGoodCibilScore;
-alert('isEligibleForLoan: ' + isEligibleForLoan);
+alert("isEligibleForLoan: " + isEligibleForLoan);
// check eligibility with || Logical OR operator
isEligibleForLoan = isEarningHighIncome || isGoodCibilScore;
-alert('isEligibleForLoan: ' + isEligibleForLoan);
+alert("isEligibleForLoan: " + isEligibleForLoan);
// ! Logical NOT
var isLoanRefused = !isEligibleForLoan;
-alert('isLoanRefused: ' + isLoanRefused);
+alert("isLoanRefused: " + isLoanRefused);
```
-07.05. Comparison (or Relational) Operators
----------------------
-07.05. Comparison Operators
----------------------
-07.05. Relational Operators
----------------------
+## 07.05. Comparison (or Relational) Operators
+
+## 07.05. Comparison Operators
+
+## 07.05. Relational Operators
- The JavaScript comparison operator compares the two operands
- It compares two values in a Boolean fashion
@@ -1573,54 +1575,55 @@ alert('isLoanRefused: ' + isLoanRefused);
JavaScript supports the following Comparison (or Relational) operators (List of Comparison (or Relational) operators):
-| Operators | Description | Example / Result |
-| ----------|---------------------------------------|---------------------------------------|
-| ==
(Loose Equality Operator) | Is equal to / identical | x == y (True if x is equal to y) |
-| ===
(Strict Equality Operator) | Eqaul/identical value and identical type| x === y (True if x is equal to y, and they are of the same type) |
-| != | Not equal to / different | x != y (True if x is not equal to y) |
-| !== | Not identical / different value or different type | x !== y )True if x is not equal to y, or they are not of the same type) |
-| < | Less than | x < y (True if x is less than y)|
-| > | Greater than | x > y (True if x is greater than y)|
-| <= | Less than or equal to | x <= y (True if x is less than or equal to y) |
-| >= | Greater than or equal to | x >= y (True if x is greater than or equal to y)|
-| | | |
+| Operators | Description | Example / Result |
+| ----------------------------------- | ------------------------------------------------- | ----------------------------------------------------------------------- |
+| ==
(Loose Equality Operator) | Is equal to / identical | x == y (True if x is equal to y) |
+| ===
(Strict Equality Operator) | Eqaul/identical value and identical type | x === y (True if x is equal to y, and they are of the same type) |
+| != | Not equal to / different | x != y (True if x is not equal to y) |
+| !== | Not identical / different value or different type | x !== y )True if x is not equal to y, or they are not of the same type) |
+| < | Less than | x < y (True if x is less than y) |
+| > | Greater than | x > y (True if x is greater than y) |
+| <= | Less than or equal to | x <= y (True if x is less than or equal to y) |
+| >= | Greater than or equal to | x >= y (True if x is greater than or equal to y) |
+| | | |
> **Syntax & Example**: `07.05.script.js`
+
```javascript
// Comparison (or Relational) operators
var num1 = 25;
var num2 = 35;
var num3 = "25";
-
-alert(num1 == num3); // true
+
+alert(num1 == num3); // true
alert(num1 === num3); // false
-alert(num1 != num2); // true
+alert(num1 != num2); // true
alert(num1 !== num3); // true
-alert(num1 < num2); // true
-alert(num1 > num2); // false
-alert(num1 <= num2); // true
-alert(num1 >= num2); // false
+alert(num1 < num2); // true
+alert(num1 > num2); // false
+alert(num1 <= num2); // true
+alert(num1 >= num2); // false
```
-07.06. Conditional (? or ternary) Operator
----------------------
-07.06. Conditional Operator
----------------------
-07.06. Ternary Operator
----------------------
+## 07.06. Conditional (? or ternary) Operator
+
+## 07.06. Conditional Operator
+
+## 07.06. Ternary Operator
- Conditional Operator returns a value based on the condition, it is like if-else
-- The conditional (ternary) operator is the only JavaScript operator that takes three operands
+- The conditional (ternary) operator is the only JavaScript operator that takes three operands
- The conditional operator that assigns a value to a variable based on some condition
- This operator is frequently used as a shortcut/short-hand method for the if statement
-- **Syntax**: variablename = (condition) ? TRUE value: FALSE value
+- **Syntax**: variablename = (condition) ? TRUE value: FALSE value
-| Operators | Description | Example / Result |
-| ----------|---------------------------------------|---------------------------------------|
-| ? | Ternary operator | var result = x < y ? 'x is smaller' : 'y is smaller' (short hand method to write if condition) |
-| | | |
+| Operators | Description | Example / Result |
+| --------- | ---------------- | ---------------------------------------------------------------------------------------------- |
+| ? | Ternary operator | var result = x < y ? 'x is smaller' : 'y is smaller' (short hand method to write if condition) |
+| | | |
> **Syntax & Example**: `07.06.script.js`
+
```javascript
// Conditional (? or ternary) Operator
@@ -1628,44 +1631,43 @@ alert(num1 >= num2); // false
var currentAge = 100;
var category;
-category = (currentAge < 18) ? 'Minor' : 'Major';
-alert('AGE category: ' + category);
+category = currentAge < 18 ? "Minor" : "Major";
+alert("AGE category: " + category);
// fees category
var isAuthorisedMember = true;
var fees;
-fees = (isAuthorisedMember == true) ? 5 : 10;
-alert('fees / charges: ' + fees);
+fees = isAuthorisedMember == true ? 5 : 10;
+alert("fees / charges: " + fees);
```
-07.07. String Operators
----------------------
+## 07.07. String Operators
Variables can also have string values, `+ operator` can be used to concatenate strings as well as numbers.
There are two operators which can also be used be for strings:
-| Operators | Description | Example / Result |
-| ----------|---------------------------------------|---------------------------------------|
-| + | Concatenation | string1 + string2 (Concatenation of string1 and string2) |
-| += | Concatenation assignment | string1 += string2 (Appends the str2 to the str1) |
-| | | |
+| Operators | Description | Example / Result |
+| --------- | ------------------------ | -------------------------------------------------------- |
+| + | Concatenation | string1 + string2 (Concatenation of string1 and string2) |
+| += | Concatenation assignment | string1 += string2 (Appends the str2 to the str1) |
+| | | |
> **Syntax & Example**: `07.07.script.js`
+
```javascript
// String Operators
var message1 = "Hello";
var message2 = " World!";
-
+
alert(message1 + message2); // Outputs: Hello World!
-
+
message1 += message2;
alert(message1); // Outputs: Hello World!
```
-07.08. Operator precedence
----------------------
+## 07.08. Operator precedence
- If an expression has more than one operator, the `execution order is defined by their precedence`, or the implicit priority order of operators
- Operator precedence determines/describes the way in which operators are parsed with respect to each other / `order in which operations are performed`
@@ -1673,28 +1675,27 @@ alert(message1); // Outputs: Hello World!
- If many operations have the same precedence (like addition and subtraction), they are `computed from left to right`
> **Syntax & Example**: `07.08.script.js`
+
```javascript
// Operator precedence
-var result1 = 10 + 2 * 5
-alert('10 + 2 * 5 = ' + result1); // answer is 20 NOT 60 (12 * 5 ), actually * or multiplication have higher precedence so the actual calculation is like 10 + ( 2*5 ) = 10 + 10 = 20
+var result1 = 10 + 2 * 5;
+alert("10 + 2 * 5 = " + result1); // answer is 20 NOT 60 (12 * 5 ), actually * or multiplication have higher precedence so the actual calculation is like 10 + ( 2*5 ) = 10 + 10 = 20
-// change precedence with `parentheses ()`
+// change precedence with `parentheses ()`
var result2 = (10 + 2) * 5;
-alert('(10 + 2) * 5 = ' + result2); // (12) * 5 = 60
+alert("(10 + 2) * 5 = " + result2); // (12) * 5 = 60
// same precedence operators
-var result3 = 10 + 5 - 2
-alert('10 + 5 - 2 = ' + result3); // 13 first addition than subtraction
+var result3 = 10 + 5 - 2;
+alert("10 + 5 - 2 = " + result3); // 13 first addition than subtraction
var result4 = 10 + (5 - 2);
-alert('10 + (5 - 2) = ' + result4); // 13 first subtraction ie. ( ) than addition
+alert("10 + (5 - 2) = " + result4); // 13 first subtraction ie. ( ) than addition
```
-Section 08. Functions
-=====================
+# Section 08. Functions
-08.01. What is a Function?
----------------------
+## 08.01. What is a Function?
- A function is basically a `group of statements that perform specific tasks/operations`
- Functions provide a way to `create reusable code packages` which are more portable and easier to debug
@@ -1704,12 +1705,12 @@ Section 08. Functions
- Wrapping up / making smaller chunks of statements / reusable codes together for readability or separation of concern/proper organization is functions – (Grouping of a repetitive task)
- Functions (logical block of code) are one of the most important control structure in any programming language
- In other languages, it might be called `MODULES, SUBROUTINES(SUB-ROUTINES)`
-- There are two steps to utilize function:
- 1. create/define a function with `function` keyword
+- There are two steps to utilize function:
+ 1. create/define a function with `function` keyword
2. call/invoke a function
> **Note**:
-Best Practice - First Define function than call/envoke it!
+> Best Practice - First Define function than call/envoke it!
#### 08.01.01. Here are some advantages of using functions:
@@ -1720,20 +1721,21 @@ Best Practice - First Define function than call/envoke it!
#### 08.01.02. Function Definition / Function Declaration / Creating Function
-- The function declaration starts by using the `function keyword`,
-- followed by a `unique function name`,
-- a list of `parameters in parentheses` i.e. () (that might be empty),
+- The function declaration starts by using the `function keyword`,
+- followed by a `unique function name`,
+- a list of `parameters in parentheses` i.e. () (that might be empty),
- and a statement block surrounded by `curly braces { }`
> **Syntax & Example**: `08.01.script.js`
+
```javascript
//1. define / declare / create function
-function showMessage () {
- //Body of function
+function showMessage() {
+ //Body of function
//code to be executed
- console.log('welcome to JavaScript function');
- alert('welcome to JavaScript function');
+ console.log("welcome to JavaScript function");
+ alert("welcome to JavaScript function");
}
```
@@ -1742,6 +1744,7 @@ function showMessage () {
- Defined function can be invoked/called/run from anywhere in the document, by typing `function name followed by a set of parentheses, like functionName()`
> **Syntax & Example**: `08.01.script.js`
+
```javascript
//2. invoke / call the function
@@ -1760,13 +1763,15 @@ Usually, Function name starts with:
- "checkSomething" – check something and return a boolean, etc.
Examples of function names:
+
- getSum();
- createFields();
- calcAge();
- checkUserType();
-08.02. Types of Function
----------------------
+ 08.02. Types of Function
+
+---
- Regular Function
- Parameterized Function
@@ -1777,15 +1782,16 @@ Examples of function names:
- Simple/Normal function which we use daily to perform some action/task
> **Syntax & Example**: `08.02.01.script.js`
+
```javascript
-var name = 'Dinanath';
+var name = "Dinanath";
//1. define / declare / create function
-function sayHello () {
- //Body of function
+function sayHello() {
+ //Body of function
//code to be executed
- console.log('Hello ' + name);
- alert('Hello ' + name);
+ console.log("Hello " + name);
+ alert("Hello " + name);
}
//2. invoke / call the function
@@ -1798,26 +1804,27 @@ sayHello();
- You can specify parameters when you define your function to accept input values at run time
> **Syntax & Example**: `08.02.02.01.script.js`
+
```javascript
// Parameterized function
//1. define / declare / create function
-function sayHello (name) {
- //Body of function
+function sayHello(name) {
+ //Body of function
//code to be executed
- console.log('Hello ' + name);
- alert('Hello ' + name);
+ console.log("Hello " + name);
+ alert("Hello " + name);
}
//2. invoke / call the function
-sayHello('Dinanath');
+sayHello("Dinanath");
-sayHello('Dino');
+sayHello("Dino");
// ------------------------------
var total;
-function calculateSum (num1, num2) {
+function calculateSum(num1, num2) {
total = num1 + num2;
console.log(total);
}
@@ -1831,27 +1838,28 @@ calculateSum(100, 200);
With ES6, now you can specify default values to the function parameters. This means that if no arguments are provided to the function when it is called these default parameters values will be used.
> **Syntax & Example**: `08.02.02.02.script.js`
+
```javascript
// Parameterized function with default parameters
//1. define / declare / create function
-function sayHello (name = 'User') {
- //Body of function
+function sayHello(name = "User") {
+ //Body of function
//code to be executed
- console.log('Hello ' + name);
- alert('Hello ' + name);
+ console.log("Hello " + name);
+ alert("Hello " + name);
}
//2. invoke / call the function
sayHello();
-sayHello('Amber');
+sayHello("Amber");
// ------------------------------
var total;
-function calculateSum (num1=1, num2=2) {
+function calculateSum(num1 = 1, num2 = 2) {
total = num1 + num2;
console.log(total);
}
@@ -1867,26 +1875,26 @@ calculateSum(100, 200);
- The return statement usually placed as the last line of the function
> **Syntax & Example**: `08.02.03.script.js`
+
```javascript
// Return type function
//1. define / declare / create function
-function getSum (num1, num2) {
- //Body of function
+function getSum(num1, num2) {
+ //Body of function
//code to be executed
var sum = num1 + num2;
- return(sum);
+ return sum;
}
//2. invoke / call the function
-console.log(getSum(10,20));
-console.log(getSum(100,200));
+console.log(getSum(10, 20));
+console.log(getSum(100, 200));
-var total = getSum(50,50);
+var total = getSum(50, 50);
alert(total);
```
-08.03. Different ways to define Function
----------------------
+## 08.03. Different ways to define Function
The syntax that we've used before to create functions is called `function declaration`. There is another syntax for creating a function that is called a `function expression` and `Immediately invoked function expression (IIFE)`
@@ -1899,6 +1907,7 @@ The syntax that we've used before to create functions is called `function declar
- Named function expression
> **Syntax & Example**: `08.03.02.01.script.js`
+
```javascript
// function declaration (Regular / normal function)
function getSum1(num1, num2) {
@@ -1909,21 +1918,22 @@ function getSum1(num1, num2) {
// ------------------------------
// function expression - Anonymus
-var getSum2 = function(num1, num2) {
- var total = num1 + num2;
- return total;
+var getSum2 = function (num1, num2) {
+ var total = num1 + num2;
+ return total;
};
-alert(getSum2(10,20));
+alert(getSum2(10, 20));
// ------------------------------
// assign function to another variable
var sum1 = getSum2;
-alert(sum1(100,200));
+alert(sum1(100, 200));
```
-> **Syntax & Example**:
+> **Syntax & Example**:
+
```javascript
// function expression - named
var getSum2 = function getTotal(num1, num2) {
@@ -1931,13 +1941,13 @@ var getSum2 = function getTotal(num1, num2) {
return total;
};
-alert(getSum2(10,20));
+alert(getSum2(10, 20));
// ------------------------------
// assign function to another variable
var sum1 = getSum2;
-alert(sum1(5,10));
+alert(sum1(5, 10));
```
#### 08.03.03. Immediately invoked function expression (IIFE)
@@ -1946,22 +1956,22 @@ alert(sum1(5,10));
- Declare and run the function at the same time
> **Syntax & Example**: `08.03.03.script.js`
+
```javascript
// Immediately invoked function expression (IIFE)
(function () {
- console.log('Welcome to Immediately invoked function expression (IIFE)');
-}());
+ console.log("Welcome to Immediately invoked function expression (IIFE)");
+})();
-
-(function(userName) {
- console.log('Welcome', userName);
-})('Dinanath');
+(function (userName) {
+ console.log("Welcome", userName);
+})("Dinanath");
```
-08.04. String Methods and Concatenation
----------------------
+## 08.04. String Methods and Concatenation
+
+> **Syntax & Example**:
-> **Syntax & Example**:
```javascript
const firstName = 'Dinanath';
@@ -2011,7 +2021,7 @@ console.log(firstName.charAt(firstName.length - 1));
// replace();
let replaceString = ('Dinanath', 'DJ');
-console.log('My name is:', replaceString);
+console.log('My name is:', replaceString);
// substring();
console.log(firstName.substring(0,4));
@@ -2037,10 +2047,9 @@ console.log(courses.split(','));
```
-08.05. Template String
----------------------
-08.05. Template Literals
----------------------
+## 08.05. Template String
+
+## 08.05. Template Literals
- ES6 new feature `Strings Template` offers a convenient way to work with string concatenation/interpolation
- Template literals provide an easy and clean way to create multi-line strings and perform string interpolation
@@ -2050,7 +2059,8 @@ console.log(courses.split(','));
- It is part of ES6 but compatible with all the modern browsers and its latest versions
-> **Syntax & Example**:
+> **Syntax & Example**:
+
```javascript
//old plain javascript approach
@@ -2058,7 +2068,7 @@ let user = 'Dinanath';
let greetMessage1 = 'Welcome' + ' ' + user + ' ' + 'to JavaScript.';
console.log(greetMessage1);
-
+
console.log('// ------------------------------');
const firstName = 'Dinanath';
@@ -2114,8 +2124,9 @@ Section 09. Loops and Iterations
5. for...of loop (ES6)
6. for...each
-09.01. The for loop
----------------------
+ 09.01. The for loop
+
+---
- The `For` loop is used to run a piece of code a `set amount of times`
- Loops through a block of code until the `counter reach a specified number`
@@ -2124,6 +2135,7 @@ Section 09. Loops and Iterations
- For loop consists of 3 statements (), mostly `i = index` is used for loop initialization
> **Syntax & Example**: `09.01.01.script.js`
+
```javascript
// for loop
@@ -2131,53 +2143,54 @@ Section 09. Loops and Iterations
// Code to be executed
} */
-
/* for(variable definition/index/initialization; condition checking; increment/decrement expression) {
// Code to be executed
} */
-for (let i=1; i<=5; i++) {
- alert('Hello, The current index/num is: ' + i);
- document.write('
'); - console.log('Hello, The current index/num is: ' + i); +for (let i = 1; i <= 5; i++) { + alert("Hello, The current index/num is: " + i); + document.write("
"); + console.log("Hello, The current index/num is: " + i); } ``` ### 09.01.01. The for loop - Reverse order > **Syntax & Example**: `09.01.02.script.js` + ```javascript // for loop - reverse order for (let i = 5; i >= 1; i--) { - alert('Hello, The current index/num is: ' + i); - document.write('
'); - console.log('Hello, The current index/num is: ' + i); + alert("Hello, The current index/num is: " + i); + document.write("
"); + console.log("Hello, The current index/num is: " + i); } ``` ### 09.01.02. The for loop - Find Even or Odd number > **Syntax & Example**: `09.01.03.script.js` + ```javascript // for loop - to find out odd even number for (let i = 1; i <= 10; i++) { if (i % 2 == 0) { - console.log('The current index/num is EVEN : ' + i); + console.log("The current index/num is EVEN : " + i); } /* else { console.log('The current index/num is ODD : ' + i); } */ } ``` -09.02. The while loop ---------------------- +## 09.02. The while loop - Loops through a block of code until the specified condition evaluates to true - In For loop, a variable is part of a loop, but in While loop, we need to declare variable externally > **Syntax & Example**: `09.02.01.script.js` + ```javascript // while loop @@ -2188,22 +2201,22 @@ for (let i = 1; i <= 10; i++) { let i = 1; while (i <= 5) { - alert('Hello, The current index/num is: ' + i); - document.write('
'); - console.log('Hello, The current index/num is: ' + i); + alert("Hello, The current index/num is: " + i); + document.write("
"); + console.log("Hello, The current index/num is: " + i); i++; } ``` -09.03. The do while loop ---------------------- -09.03. The do...while loop ---------------------- +## 09.03. The do while loop + +## 09.03. The do...while loop - The do...while loop is similar to the while loop except that the `condition check happens at the end of the loop` - The do...while loop will always be `executed at least once (before checking if the condition is true)`, even if the condition is false > **Syntax & Example**: `09.03.01.script.js` + ```javascript // do...while loop @@ -2215,24 +2228,23 @@ while(condition);*/ let i = 1; do { - alert('Hello, The current index/num is: ' + i); - document.write('
'); - console.log('Hello, The current index/num is: ' + i); + alert("Hello, The current index/num is: " + i); + document.write("
"); + console.log("Hello, The current index/num is: " + i); i++; -} -while (i <= 5); +} while (i <= 5); ``` -09.04. The for in loop ---------------------- -09.04. The for...in loop ---------------------- +## 09.04. The for in loop + +## 09.04. The for...in loop - The for-in loop is a special type of a loop that `iterates over the properties of an object or the elements of an array` #### 09.04.01. The for...in Loop - array > **Syntax & Example**: `09.04.01.script.js` + ```javascript // for...in loop @@ -2243,17 +2255,18 @@ while (i <= 5); // An array with some elements let arrColors = ["Red", "Green", "Blue", "Cyan", "Magenta", "Yellow", "Black"]; -// Loop through all the elements in the array +// Loop through all the elements in the array for (let color in arrColors) { - alert('Color is: ' + arrColors[color]); - document.write('
'); - console.log('Color is: ' + arrColors[color]); + alert("Color is: " + arrColors[color]); + document.write("
"); + console.log("Color is: " + arrColors[color]); } ``` #### 09.04.02. The for...in Loop - object > **Syntax & Example**: `09.04.02.script.js` + ```javascript // for...in loop @@ -2261,20 +2274,26 @@ for (let color in arrColors) { // Code to be executed }*/ -// An object with some properties -let objEmployee = {'emp_name': 'Dinanath', 'emp_addres': 'Mumbai', 'emp_id': '029', 'emp_age':35}; +// An object with some properties +let objEmployee = { + emp_name: "Dinanath", + emp_addres: "Mumbai", + emp_id: "029", + emp_age: 35, +}; -// Loop through all the properties in the object +// Loop through all the properties in the object for (emp in objEmployee) { - alert('Employee '+ emp + ' is: ' + objEmployee[emp]); - document.write('
'); - console.log('Employee '+ emp + ' is: ' + objEmployee[emp]); + alert("Employee " + emp + " is: " + objEmployee[emp]); + document.write("
"); + console.log("Employee " + emp + " is: " + objEmployee[emp]); } ``` #### 09.04.03. The for...in Loop - Inbuilt JavaScript objects > **Syntax & Example**: `09.04.03.script.js` + ```javascript // for...in loop @@ -2285,21 +2304,21 @@ for (emp in objEmployee) { // Loop through all the properties in the inbuilt object - window, document, navigator for (props in window) { // alert('document object properties ' + props); - document.write('
'); - console.log('document object properties ' + props); + document.write("
"); + console.log("document object properties " + props); } ``` -09.05. The for of loop ---------------------- -09.05. The for...of loop (ES6) ---------------------- +## 09.05. The for of loop + +## 09.05. The for...of loop (ES6) - Loops over `iterable objects such as arrays, strings`, etc. - ES6 introduces a new for-of loop which allows us to iterate over arrays or strings very easily - The code inside the loop is executed for each element of the iterable object > **Syntax & Example**: `09.05.01.script.js` + ```javascript // for...of loop @@ -2308,23 +2327,30 @@ for (props in window) { } */ // Iterating over an array -let arrDays = ["Monday", "TuesDay", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]; +let arrDays = [ + "Monday", + "TuesDay", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + "Sunday", +]; for (let day of arrDays) { console.log(day); - document.write('
'); + document.write("
");
}
// Iterating over string
-let name = 'JavaScript';
+let name = "JavaScript";
for (let letter of name) {
- document.write(letter + ',');
- console.log(letter + ',');
+ document.write(letter + ",");
+ console.log(letter + ",");
}
```
-09.06. Break and Continue statement
----------------------
+## 09.06. Break and Continue statement
- `break` and `continue` keywords/statement can change `how the loop behaves`
- `break` and `continue` keywords can be used in all loops to stop or continue the loop
@@ -2332,11 +2358,20 @@ for (let letter of name) {
- The `continue` statement tells the interpreter to immediately start the next iteration of the loop and skip the remaining code block
> **Syntax & Example**: `09.06.01.script.js`
+
```javascript
// break continue statement
/* break */
-let arrDays = ["Monday", "TuesDay", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
+let arrDays = [
+ "Monday",
+ "TuesDay",
+ "Wednesday",
+ "Thursday",
+ "Friday",
+ "Saturday",
+ "Sunday",
+];
let i = 1;
while (i <= 10) {
@@ -2344,10 +2379,10 @@ while (i <= 10) {
break;
}
console.log(i);
- i++
+ i++;
}
-console.log('// ------------------------------');
+console.log("// ------------------------------");
for (let i = 0; i <= arrDays.length; i++) {
if (i == 3) {
@@ -2356,7 +2391,7 @@ for (let i = 0; i <= arrDays.length; i++) {
console.log(arrDays[i]);
}
-console.log('// ------------------------------');
+console.log("// ------------------------------");
/* continue */
i = 1;
@@ -2366,48 +2401,46 @@ while (i <= 20) {
i++;
continue; // skip rest of the loop body
- i + 100; // non of use
- console.log('just in even num continue'); // non of use
+ i + 100; // non of use
+ console.log("just in even num continue"); // non of use
}
- console.log('Odd Number ', i);
+ console.log("Odd Number ", i);
i++;
}
-console.log('// ------------------------------');
+console.log("// ------------------------------");
for (i = 1; i <= 10; i++) {
if (i === 5) {
continue; // skip rest of the loop body
- console.log('just after 5 continue...'); // non of use
+ console.log("just after 5 continue..."); // non of use
}
console.log(i);
}
-console.log('// ------------------------------');
-
-for(let int = 0; int < 10; int++) {
+console.log("// ------------------------------");
- if(int === 2) {
- console.log('2 is favorite EVEN number');
+for (let int = 0; int < 10; int++) {
+ if (int === 2) {
+ console.log("2 is favorite EVEN number");
continue;
}
- if(int === 5) {
- console.log('at 5 stop the loop');
+ if (int === 5) {
+ console.log("at 5 stop the loop");
break;
}
- console.log('current Number is:', int);
+ console.log("current Number is:", int);
}
-
```
-09.07. for each loop
----------------------
-09.07. for...each loop
----------------------
+## 09.07. for each loop
+
+## 09.07. for...each loop
> **Syntax & Example**: ``
+
```javascript
let arrDays = ["Monday", "TuesDay", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
@@ -2418,10 +2451,9 @@ arrDays.forEach(function(day)){
```
-Section 10. Conditions
-=====================
-Section 10. Conditions - Control Flow
-=====================
+# Section 10. Conditions
+
+# Section 10. Conditions - Control Flow
- Conditional statements are used to perform different action based on different condition
- Conditional statements allow the developer to make correct decisions and perform right actions as per condition
@@ -2435,10 +2467,11 @@ Section 10. Conditions - Control Flow
3. If...else if...else Statement
4. Switch...Case Statement
-10.01. The if statement
----------------------
-10.01. The if statement and comparison operators
----------------------
+ 10.01. The if statement
+
+---
+
+## 10.01. The if statement and comparison operators
- If the conditional statement is the simplest and basic control statement make decisions and execute statements conditionally
- The if statement is used to execute a block of code `only if the specified condition evaluates to true`
@@ -2447,9 +2480,10 @@ Section 10. Conditions - Control Flow
If conditional statements are used to evaluate some kind of condition and do something/perform some actions based on the result
> **Note**:
-Use `if` to specify a block of code to be executed, `if a specified condition is true`
+> Use `if` to specify a block of code to be executed, `if a specified condition is true`
> **Syntax & Example**: `10.01.01.script.js`
+
```javascript
// if conditional statement
@@ -2458,16 +2492,16 @@ Use `if` to specify a block of code to be executed, `if a specified condition is
}
*/
-let user = 'Dinanath';
+let user = "Dinanath";
-if (user == 'Dinanath') {
- console.log('Welcome Dinanath!');
- window.alert('Welcome Dinanath!');
+if (user == "Dinanath") {
+ console.log("Welcome Dinanath!");
+ window.alert("Welcome Dinanath!");
}
-if (user == 'Dinanath') {
- console.log('Welcome Authorised User: ' + user + '!');
- window.alert('Welcome Authorised User: ' + user + '!');
+if (user == "Dinanath") {
+ console.log("Welcome Authorised User: " + user + "!");
+ window.alert("Welcome Authorised User: " + user + "!");
}
// ------------------------------
@@ -2475,29 +2509,28 @@ if (user == 'Dinanath') {
let age = 20;
if (age >= 18) {
- console.log('MAJOR! Eligible for Voting');
- window.alert('MAJOR! Eligible for Voting');
+ console.log("MAJOR! Eligible for Voting");
+ window.alert("MAJOR! Eligible for Voting");
}
// ------------------------------
let currentHours = 10;
-if(currentHours < 12) {
- console.log('Good Morning!');
- window.alert('Good Morning!');
+if (currentHours < 12) {
+ console.log("Good Morning!");
+ window.alert("Good Morning!");
}
-if(currentHours >=6 && currentHours < 12) {
- console.log('Good Morning!');
- window.alert('Good Morning!');
+if (currentHours >= 6 && currentHours < 12) {
+ console.log("Good Morning!");
+ window.alert("Good Morning!");
}
```
-10.02. The if else statement
----------------------
-10.02. The if...else statement
----------------------
+## 10.02. The if else statement
+
+## 10.02. The if...else statement
- The JavaScript `if...else statement` is used to execute the code `weather condition is true or false`
- The developer can enhance the decision-making capabilities by providing an alternative choice through adding an `else` statement to the `if` statement
@@ -2505,9 +2538,10 @@ if(currentHours >=6 && currentHours < 12) {
- If the condition evaluates to true, statements_1 are executed; otherwise, statements_2 are executed
> **Note**:
-Use `else` to specify a block of code to be executed, `if the same condition is false`
+> Use `else` to specify a block of code to be executed, `if the same condition is false`
> **Syntax & Example**: `10.02.01.script.js`
+
```javascript
// if...else conditional statement
@@ -2518,14 +2552,14 @@ else{
// content to be executed if condition is false - statements_2
}*/
-let user = 'Ambar';
+let user = "Ambar";
-if (user == 'Dinanath') {
- console.log('Welcome Dinanath!');
- window.alert('Welcome Dinanath!');
+if (user == "Dinanath") {
+ console.log("Welcome Dinanath!");
+ window.alert("Welcome Dinanath!");
} else {
- console.log('Welcome Guest!');
- window.alert('Welcome Guest!');
+ console.log("Welcome Guest!");
+ window.alert("Welcome Guest!");
}
// ------------------------------
@@ -2533,38 +2567,38 @@ if (user == 'Dinanath') {
let age = 15;
if (age >= 18) {
- console.log('MAJOR! Eligible for Voting');
- window.alert('MAJOR! Eligible for Voting');
+ console.log("MAJOR! Eligible for Voting");
+ window.alert("MAJOR! Eligible for Voting");
} else {
- console.log('MINOR! NOT Eligible for Voting');
- window.alert('MINOR! NOT Eligible for Voting');
+ console.log("MINOR! NOT Eligible for Voting");
+ window.alert("MINOR! NOT Eligible for Voting");
}
// ------------------------------
let currentHours = 10;
-if(currentHours < 12) {
- console.log('Good Morning!');
- window.alert('Good Morning!');
+if (currentHours < 12) {
+ console.log("Good Morning!");
+ window.alert("Good Morning!");
} else {
- console.log('Good Evening!');
- window.alert('Good Evening!');
+ console.log("Good Evening!");
+ window.alert("Good Evening!");
}
```
-10.03. The if else if else statement
----------------------
-10.03. The if...else, if...else statement
----------------------
+## 10.03. The if else if else statement
+
+## 10.03. The if...else, if...else statement
- The `if...else if...else` a special statement that is used to `combine multiple if...else statements`
- It is an advanced form of if...else that allows us to `make a correct decision out of several conditions`
> **Note**:
-Use `else if` to specify a new condition to test, `if the first condition is false`
+> Use `else if` to specify a new condition to test, `if the first condition is false`
> **Syntax & Example**: `10.03.01.script.js`
+
```javascript
// If...else if...else conditional statement
@@ -2580,54 +2614,54 @@ let num1 = 200;
let num2 = 100;
if (num1 == num2) {
- console.log('Both numbers are equal');
-} else if (num1 < num2 ) {
- console.log('Number2 is greater!');
+ console.log("Both numbers are equal");
+} else if (num1 < num2) {
+ console.log("Number2 is greater!");
} else {
- console.log('Number1 is greater!');
+ console.log("Number1 is greater!");
}
// ------------------------------
-let age = 15;
+let age = 15;
if (age >= 60) {
- console.log('SINIOR CIRIZEN!');
+ console.log("SINIOR CIRIZEN!");
} else if (age < 18) {
- console.log('MINOR!');
+ console.log("MINOR!");
} else {
- console.log('MAJOR - Middle Age!');
+ console.log("MAJOR - Middle Age!");
}
// ------------------------------
let currentHours = 15;
-if(currentHours >=6 && currentHours< 12) {
- console.log('Good Morning!');
- window.alert('Good Morning!');
-} else if (currentHours >12 && currentHours <=18) {
- console.log('Good AfterNoon!');
- window.alert('Good AfterNoon!');
+if (currentHours >= 6 && currentHours < 12) {
+ console.log("Good Morning!");
+ window.alert("Good Morning!");
+} else if (currentHours > 12 && currentHours <= 18) {
+ console.log("Good AfterNoon!");
+ window.alert("Good AfterNoon!");
} else {
- console.log('Good Evening!');
- window.alert('Good Evening!');
+ console.log("Good Evening!");
+ window.alert("Good Evening!");
}
```
-10.04. The switch case statement
----------------------
-10.04. The switch...case statement
----------------------
+## 10.04. The switch case statement
+
+## 10.04. The switch...case statement
- The switch...case statement is alternative to an if...else if...else statement, both do almost the same thing
- This matches the `case` and the `value of condition` and if the case matches, the subsequent block is executed and if none of the case matches `default block` is executed
- The JavaScript switch statement is used to execute one code from multiple blocks of expressions
> **Note**:
-Use `switch` to specify many `alternative blocks of code to be executed`
+> Use `switch` to specify many `alternative blocks of code to be executed`
> **Syntax & Example**: `10.04.01.script.js`
+
```javascript
// switch...case conditional statement
@@ -2642,61 +2676,61 @@ Use `switch` to specify many `alternative blocks of code to be executed`
// Code to be executed if variable/expression is different from all values
} */
-let grade = 'B'; // A.B,C, or something
+let grade = "B"; // A.B,C, or something
switch (grade) {
- case 'A':
- console.log('Great Job! - A Grade');
+ case "A":
+ console.log("Great Job! - A Grade");
break;
- case 'B':
- console.log('Good! - B Grade');
+ case "B":
+ console.log("Good! - B Grade");
break;
- case 'C':
- console.log('Congratulations! - Passed');
+ case "C":
+ console.log("Congratulations! - Passed");
break;
default:
- console.log('Sorry! - Failed...Keep trying!');
+ console.log("Sorry! - Failed...Keep trying!");
break;
}
// ------------------------------
-let sweets = ''; //cake, chocolates, biscuits
+let sweets = ""; //cake, chocolates, biscuits
switch (sweets) {
- case 'chocolates':
- console.log('Chubby Chocolates!');
+ case "chocolates":
+ console.log("Chubby Chocolates!");
break;
- case 'cake':
- console.log('Happy BirthDay Cake!');
+ case "cake":
+ console.log("Happy BirthDay Cake!");
break;
- case 'biscuits':
- console.log('Enjoy Biscuits!');
+ case "biscuits":
+ console.log("Enjoy Biscuits!");
break;
default:
- console.log('No Sweets! Try some other sweets!');
+ console.log("No Sweets! Try some other sweets!");
break;
}
// ------------------------------
-const color = 'red';
+const color = "red";
-switch(color) {
- case 'red':
- console.log('The Dark RED');
+switch (color) {
+ case "red":
+ console.log("The Dark RED");
break;
- case 'green':
- console.log('Go Green');
+ case "green":
+ console.log("Go Green");
break;
- case 'blue':
- console.log('Boys are Blue');
+ case "blue":
+ console.log("Boys are Blue");
break;
- case 'yellow':
- console.log('Golden Yellow');
+ case "yellow":
+ console.log("Golden Yellow");
break;
default:
- console.log('Its some other Color, Enter correct color');
+ console.log("Its some other Color, Enter correct color");
break;
}
@@ -2705,39 +2739,36 @@ switch(color) {
let currentDate = new Date();
let currentDay;
-switch(currentDate.getDay()) {
+switch (currentDate.getDay()) {
case 0:
- currentDay = 'Sunday';
+ currentDay = "Sunday";
break;
case 1:
- currentDay = 'Monday';
+ currentDay = "Monday";
break;
case 2:
- currentDay = 'Tuesday';
+ currentDay = "Tuesday";
break;
case 3:
- currentDay = 'Wednesday';
+ currentDay = "Wednesday";
break;
case 4:
- currentDay = 'Thursday';
+ currentDay = "Thursday";
break;
case 5:
- currentDay = 'Friday';
+ currentDay = "Friday";
break;
case 6:
- currentDay = 'Saturday';
+ currentDay = "Saturday";
break;
}
console.log(`Today is ${currentDay}!`);
-
```
-Section 11. Array
-=====================
+# Section 11. Array
-11.01. What is an Array?
----------------------
+## 11.01. What is an Array?
- An Array is a special type of variable/object which `consists of / stores multiple values`
- Arrays are complex variables that allow us to store more than one value or a group of values under a single variable name
@@ -2750,49 +2781,52 @@ Section 11. Array
#### Different ways to create/define an Array
There are 3 main ways to construct an array:
-1. By array literal
+
+1. By array literal
2. By creating an instance of Array directly (using the new keyword)
3. By using an Array constructor (using the new keyword)
-11.02. Create Array by array literal
----------------------
+ 11.02. Create Array by array literal
+
+---
- The simplest way to create an array in JavaScript is enclosing a `comma-separated list of values in square brackets [ ]`
- var myArray = [element0, element1, ..., elementN];
> **Syntax & Example**: `11.02.01.script.js`
+
```javascript
// create array with array literal ie. [] square bracket
// var myArray = [element0, element1, ..., elementN];
-var arrColors = ['Red', 'Green', 'Blue', 'Orange'];
+var arrColors = ["Red", "Green", "Blue", "Orange"];
console.log(arrColors); // show all elements
// ------------------------------
-var arrCities = ['Delhi', 'Mumbai', 'Kolkota','Bengaluru','Chennai'];
+var arrCities = ["Delhi", "Mumbai", "Kolkota", "Bengaluru", "Chennai"];
console.log(arrCities[1]); // show 1st index ie. 2nd positioned element
// ------------------------------
var arrTechnologies = [];
-arrTechnologies[0] = 'Java';
-arrTechnologies[1] = 'Python';
-arrTechnologies[2] = 'C';
+arrTechnologies[0] = "Java";
+arrTechnologies[1] = "Python";
+arrTechnologies[2] = "C";
console.log(arrTechnologies);
-console.log('Total Elements: ' + arrTechnologies.length);
+console.log("Total Elements: " + arrTechnologies.length);
```
-11.03. Create Array by creating an instance of array directly
----------------------
-11.03. Create Array by creating an instance of array directly (using `new` keyword)
----------------------
+## 11.03. Create Array by creating an instance of array directly
+
+## 11.03. Create Array by creating an instance of array directly (using `new` keyword)
- Array instance can be created using the `new` keyword `new Array()`
- var myArray = new Array(); OR var myArray = Array();
> **Syntax & Example**: `11.03.01.script.js`
+
```javascript
// create array with new keyword
@@ -2800,10 +2834,10 @@ console.log('Total Elements: ' + arrTechnologies.length);
var arrColors = new Array();
-arrColors[0] = 'Red'
-arrColors[1] = 'Green'
-arrColors[2] = 'Blue'
-arrColors[3] = 'Orange'
+arrColors[0] = "Red";
+arrColors[1] = "Green";
+arrColors[2] = "Blue";
+arrColors[3] = "Orange";
console.log(arrColors); // show all elements
// read/get array items/elements
@@ -2814,11 +2848,11 @@ for (let i = 0; i < arrColors.length; i++) {
// ------------------------------
var arrCities = Array();
-arrCities[0] = 'Delhi';
-arrCities[1] = 'Mumbai';
-arrCities[2] = 'DeKolkotalhi';
-arrCities[3] = 'Bengaluru';
-arrCities[4] = 'Chennai';
+arrCities[0] = "Delhi";
+arrCities[1] = "Mumbai";
+arrCities[2] = "DeKolkotalhi";
+arrCities[3] = "Bengaluru";
+arrCities[4] = "Chennai";
console.log(arrCities); // show all elements
// ------------------------------
@@ -2827,42 +2861,49 @@ var arrTechnologies = new Array();
// add new array items/elements
for (let i = 0; i <= 5; i++) {
- arrTechnologies[i] = 'JavaScript';
+ arrTechnologies[i] = "JavaScript";
}
console.log(arrTechnologies); // show all elements
```
-11.04. Create Array by using an array constructor
----------------------
-11.04. Create Array by using an array constructor (using `new` keyword)
----------------------
+## 11.04. Create Array by using an array constructor
+
+## 11.04. Create Array by using an array constructor (using `new` keyword)
- Array instance can be created using the `new` keyword `new Array() passing arguments` in constructor so that we don't have to provide value explicitly
- var myArray = new Array(element0, element1, ..., elementN);
> **Syntax & Example**: `11.04.01.script.js`
+
```javascript
// create array with new keyword Array constructor passing parameter
// var myArray = new Array(element0, element1, ..., elementN);
-var arrColors = new Array('Red', 'Green', 'Blue', 'Orange');
+var arrColors = new Array("Red", "Green", "Blue", "Orange");
console.log(arrColors); // show all elements
// ------------------------------
-var arrCities = new Array('Delhi', 'Mumbai', 'Kolkota','Bengaluru','Chennai');
+var arrCities = new Array("Delhi", "Mumbai", "Kolkota", "Bengaluru", "Chennai");
console.log(arrCities); // show all elements
// ------------------------------
-var arrJsFrameworks = new Array('jQuery','Angular','React','Node','Vue','Express','D3');
+var arrJsFrameworks = new Array(
+ "jQuery",
+ "Angular",
+ "React",
+ "Node",
+ "Vue",
+ "Express",
+ "D3"
+);
console.log(arrJsFrameworks); // show all elements
```
-11.05. Getting the Length of an Array
----------------------
+## 11.05. Getting the Length of an Array
- The `length` property returns the `length of an array`, `total number of elements` in an array
- `length` property brings back an `array length - the fixed amount of items` stored in the array
@@ -2871,29 +2912,37 @@ console.log(arrJsFrameworks); // show all elements
- myarray.length
> **Syntax & Example**: `11.05.01.script.js`
+
```javascript
// get/retrieve/find array length
// myarray.length
-var arrColors = new Array('Red', 'Green', 'Blue', 'Orange');
+var arrColors = new Array("Red", "Green", "Blue", "Orange");
console.log(arrColors.length);
// ------------------------------
-var arrCities = new Array('Delhi', 'Mumbai', 'Kolkota','Bengaluru','Chennai');
+var arrCities = new Array("Delhi", "Mumbai", "Kolkota", "Bengaluru", "Chennai");
console.log(arrCities.length);
// ------------------------------
-var arrJsFrameworks = new Array('jQuery','Angular','React','Node','Vue','Express','D3');
+var arrJsFrameworks = new Array(
+ "jQuery",
+ "Angular",
+ "React",
+ "Node",
+ "Vue",
+ "Express",
+ "D3"
+);
console.log(arrJsFrameworks.length);
```
-11.06. Accessing Looping through an Array Elements
----------------------
-11.06. Loop through an Array Elements
----------------------
+## 11.06. Accessing Looping through an Array Elements
+
+## 11.06. Loop through an Array Elements
- Array elements can be accessed by their `index using the square bracket notation ie. [index]`
- Arrays are `zero-indexed` i.e. the first element of an array is at index/position 0
@@ -2903,36 +2952,44 @@ console.log(arrJsFrameworks.length);
- myarray[indexNumber], myarray[0] // get first array element
> **Syntax & Example**: `11.06.01.script.js`
+
```javascript
// access/loop through array element
// myarray[indexNumber], myarray[0]
-var arrColors = new Array('Red', 'Green', 'Blue', 'Orange');
+var arrColors = new Array("Red", "Green", "Blue", "Orange");
console.log(arrColors[0]); // Red
console.log(arrColors[2]); // Blue
// ------------------------------
-var arrCities = new Array('Delhi', 'Mumbai', 'Kolkota', 'Bengaluru', 'Chennai');
+var arrCities = new Array("Delhi", "Mumbai", "Kolkota", "Bengaluru", "Chennai");
console.log(arrCities[1]); // Mumbai
console.log(arrCities[4]); // Chennai
// ------------------------------
-var arrJsFrameworks = new Array('jQuery', 'Angular', 'React', 'Node', 'Vue', 'Express', 'D3');
+var arrJsFrameworks = new Array(
+ "jQuery",
+ "Angular",
+ "React",
+ "Node",
+ "Vue",
+ "Express",
+ "D3"
+);
console.log(arrJsFrameworks[3]); // Node
console.log(arrJsFrameworks[5]); // Express
// Loop through an Array Elements
for (let i = 0; i < arrJsFrameworks.length; i++) {
- document.write('
'); + document.write("
");
}
```
-11.07. Adding Editing an Array Elements
----------------------
+## 11.07. Adding Editing an Array Elements
- One can add/edit an array element by simply specifying `array[index] and value` ie. `myarray[5]='value'`
- If array `index exists it will simply edit` the old value and update the array else it will add an element to the array
@@ -2941,64 +2998,65 @@ for (let i = 0; i < arrJsFrameworks.length; i++) {
- myarray[indexNumber]='value', myarray[2]='value', myarray.push('value'), myarray.unshift('value')
> **Syntax & Example**: `11.07.01.script.js`
+
```javascript
// add/edit array element
// myarray[indexNumber]='value', myarray[2]='value', myarray.push('value'), myarray.unshift('value')
-var arrColors = new Array('Red', 'Green', 'Blue', 'Orange');
+var arrColors = new Array("Red", "Green", "Blue", "Orange");
console.log(arrColors);
-console.log('arrColors.length: ' + arrColors.length);
+console.log("arrColors.length: " + arrColors.length);
// add an element at the end of the array
-arrColors.push('Cyan');
+arrColors.push("Cyan");
console.log(arrColors);
-console.log('arrColors.length: ' + arrColors.length);
+console.log("arrColors.length: " + arrColors.length);
// add multiple elements at the end of the array
-arrColors.push('Magenta','Yellow');
+arrColors.push("Magenta", "Yellow");
console.log(arrColors);
-console.log('arrColors.length: ' + arrColors.length);
+console.log("arrColors.length: " + arrColors.length);
// ------------------------------
// add multiple elements at the start of the array
-arrColors.unshift('Black','White');
+arrColors.unshift("Black", "White");
console.log(arrColors);
-console.log('arrColors.length: ' + arrColors.length);
+console.log("arrColors.length: " + arrColors.length);
// ------------------------------
// edit 1st index ie. 'white' to 'pink'
-arrColors[1] = 'pink';
+arrColors[1] = "pink";
console.log(arrColors);
-console.log('arrColors.length: ' + arrColors.length);
+console.log("arrColors.length: " + arrColors.length);
```
-11.08. Removing Deleting an Array Elements
----------------------
+## 11.08. Removing Deleting an Array Elements
- `pop()` method `remove the last element` from an array
- `shift()` method remove the `first element` from an array
- myarray.pop(), myarray.shift()
> **Note**:
-The `push() and pop() methods runs faster` than unshift() and shift(). Because push() and pop() methods add and remove elements at the end of an array, therefore, the elements do not move. unshift() and shift() add and remove elements at the beginning of the array that requires re-indexing/re-structuring of the whole array.
+> The `push() and pop() methods runs faster` than unshift() and shift(). Because push() and pop() methods add and remove elements at the end of an array, therefore, the elements do not move. unshift() and shift() add and remove elements at the beginning of the array that requires re-indexing/re-structuring of the whole array.
> **Syntax & Example**: `11.08.01.script`
+
```javascript
// remove array element from start and end
// myarray.pop(), myarray.shift()
-var arrColors = new Array('Red', 'Green', 'Blue', 'Orange');
+var arrColors = new Array("Red", "Green", "Blue", "Orange");
console.log(arrColors);
-console.log('arrColors.length: ' + arrColors.length);
+console.log("arrColors.length: " + arrColors.length);
// remove an element from the end of the array
arrColors.pop();
console.log(arrColors);
-console.log('arrColors.length: ' + arrColors.length);
+console.log("arrColors.length: " + arrColors.length);
// ------------------------------
@@ -3006,13 +3064,13 @@ console.log('arrColors.length: ' + arrColors.length);
let startElement = arrColors.shift();
console.log(startElement);
console.log(arrColors);
-console.log('arrColors.length: ' + arrColors.length);
+console.log("arrColors.length: " + arrColors.length);
```
-11.09. Array properties and methods
----------------------
+## 11.09. Array properties and methods
+
+> **Syntax & Example**: ``
-> **Syntax & Example**: ``
```javascript
// length
@@ -3059,32 +3117,29 @@ console.log(numberArray.find(40));
```
-Section 12. Objects
-=====================
+# Section 12. Objects
+
+## 12.01. Real Life Objects
-12.01. Real Life Objects
----------------------
-12.01. Object Properties and Method examples
----------------------
+## 12.01. Object Properties and Method examples
-- In real life almost `everything is an object`.
+- In real life almost `everything is an object`.
- For example: Human, Car, Building, Bike, Pen, Chair, Monitor, Keyboard, Vehicle, Mobile, Computer etc.
- Let's have a look on some Objects with Properties and Methods:
-| Object | Properties | Methods |
-|---------------|-----------------------------------------|------------------------------------|
-| Person | Person.name = 'dinanath';
Person.weight = 65;
Person.color = 'fair' | Person.walk();
Person.talk();
Person.eat(); |
-| Bike | Bike.brand = 'bajaj';
Bike.model = 'discover';
Bike.color = 'blue';
Bike.length = 60;
Bike.height = 30;
| Bike.start();
Bike.break();
Bike.stop(); |
-| Watch | Watch.type = 'analog';
Watch.price = 750;
| Watch.showTime();
Watch.setAlarm(); |
-| | | |
+| Object | Properties | Methods |
+| ------ | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- |
+| Person | Person.name = 'dinanath';
Person.weight = 65;
Person.color = 'fair' | Person.walk();
Person.talk();
Person.eat(); |
+| Bike | Bike.brand = 'bajaj';
Bike.model = 'discover';
Bike.color = 'blue';
Bike.length = 60;
Bike.height = 30;
| Bike.start();
Bike.break();
Bike.stop(); |
+| Watch | Watch.type = 'analog';
Watch.price = 750;
| Watch.showTime();
Watch.setAlarm(); |
+| | | |
> **Note**:
-As a practice think of any other object in your surrounding and list down its Properties and Methods
+> As a practice think of any other object in your surrounding and list down its Properties and Methods
-12.02. What is an Object?
----------------------
-12.02. What are the Objects?
----------------------
+## 12.02. What is an Object?
+
+## 12.02. What are the Objects?
- JavaScript is an `object-based language` and in JavaScript, almost everything is an object or acts like/as an object
- An object is a `special/complex` data type that allows you to `store collections of data`
@@ -3094,26 +3149,29 @@ As a practice think of any other object in your surrounding and list down its Pr
- An object contains properties, defined as a `key-value pair` (Objects are a collection of `key-value pair`)
- A property `key (name) is always a string`, but the value which it stores can be any data types, like strings, numbers, booleans, or complex data types like arrays, function and other objects
- JavaScript object properties can be accessed through two methods:
- 1. .DOT notation: `object.firstName`
+ 1. .DOT notation: `object.firstName`
2. []Bracket notation: `object['firstName']`
### Different ways to create/define an Object
There are 3 main ways to construct an object:
-1. By object literal
+
+1. By object literal
2. By creating an `instance` of Object directly (using `new` keyword)
3. By using an `Object constructor` (using `new` keyword)
-12.03. Object literal
----------------------
+ 12.03. Object literal
+
+---
- The simplest way to create an object in JavaScript is enclosing a `comma-separated list of properties:values and methods in curly braces { }`
-- var MyObject = { property1: value1, property2: value2.....propertyN: valueN }
+- var MyObject = { property1: value1, property2: value2.....propertyN: valueN }
> **Syntax & Example**:
+
```javascript
// create object with object literal
-
+
// var MyObject = { property1: value1, property2: value2.....propertyN: valueN }
// empty object
@@ -3121,64 +3179,69 @@ var HumanObj = {};
console.log(HumanObj);
-console.log('// ------------------------------');
+console.log("// ------------------------------");
// object with properties
-var TechnologyObj = { 'name': 'JavaScript', 'version': 6, 'type': 'script', 'isStable': true }
+var TechnologyObj = {
+ name: "JavaScript",
+ version: 6,
+ type: "script",
+ isStable: true,
+};
console.log(TechnologyObj.name);
-console.log(TechnologyObj['isStable']);
+console.log(TechnologyObj["isStable"]);
-console.log('// ------------------------------');
+console.log("// ------------------------------");
// object properly alignment/arranged for readability - with quotes
var VehicleObj1 = {
- 'type': 'LWM',
- 'brand': 'Maruti',
- 'model': 'Alto-100',
- 'color': 'White',
- 'isHighEndModel': true,
- 'price': 400000,
+ type: "LWM",
+ brand: "Maruti",
+ model: "Alto-100",
+ color: "White",
+ isHighEndModel: true,
+ price: 400000,
keyStart: function () {
- console.log(this.model + ' started!');
- }
-}
+ console.log(this.model + " started!");
+ },
+};
console.log(VehicleObj1.brand);
-console.log(VehicleObj1['color']);
+console.log(VehicleObj1["color"]);
VehicleObj1.keyStart();
-console.log('// ------------------------------');
+console.log("// ------------------------------");
// object properly alignment/arranged for readability - with quotes
var VehicleObj2 = {
- type: 'LWM',
- brand: 'Maruti',
- model: 'Alto-100',
- color: 'White',
+ type: "LWM",
+ brand: "Maruti",
+ model: "Alto-100",
+ color: "White",
isHighEndModel: true,
price: 400000,
keyStart: function () {
- alert(this.model + 'started!');
- }
-}
+ alert(this.model + "started!");
+ },
+};
console.log(VehicleObj1.brand);
-console.log(VehicleObj1['color']);
+console.log(VehicleObj1["color"]);
VehicleObj1.keyStart();
-console.log('// ------------------------------');
+console.log("// ------------------------------");
```
-12.04. Creating an instance of Object directly
----------------------
-12.04. Creating an instance of object directly (using the new keyword)
----------------------
+## 12.04. Creating an instance of Object directly
+
+## 12.04. Creating an instance of object directly (using the new keyword)
- Array instance can be created using the `new` keyword `new Array() with or without passing arguments/properties-methods` in constructor
- var MyObject = new Object(); OR var MyObject = Object();
> **Syntax & Example**:
+
```javascript
// create object with new keyword
@@ -3187,70 +3250,70 @@ console.log('// ------------------------------');
// object with properties
var TechnologyObj = new Object();
-TechnologyObj.name = 'JavaScript';
+TechnologyObj.name = "JavaScript";
TechnologyObj.version = 6;
-TechnologyObj.type = 'script';
-TechnologyObj.isStable = true
+TechnologyObj.type = "script";
+TechnologyObj.isStable = true;
console.log(TechnologyObj.name);
-console.log(TechnologyObj['type']);
+console.log(TechnologyObj["type"]);
-console.log('// ------------------------------');
+console.log("// ------------------------------");
// object properly alignment/arranged for readability - with quotes
var VehicleObj1 = {
- 'type': 'LWM',
- 'brand': 'Maruti',
- 'model': 'Alto-100',
- 'color': 'red',
- 'isHighEndModel': true,
- 'price': 400000,
+ type: "LWM",
+ brand: "Maruti",
+ model: "Alto-100",
+ color: "red",
+ isHighEndModel: true,
+ price: 400000,
keyStart: function () {
- console.log(this.model + ' started!');
- }
-}
+ console.log(this.model + " started!");
+ },
+};
// access property with .DOT notation
console.log(VehicleObj1.brand);
// access property with []Bracket notation
-console.log(VehicleObj1['color']);
+console.log(VehicleObj1["color"]);
VehicleObj1.keyStart();
-console.log('// ------------------------------');
+console.log("// ------------------------------");
// object properly alignment/arranged for readability - without quotes
var VehicleObj2 = {
- type: 'LWM',
- brand: 'Tata',
- model: 'Safari',
- color: 'White',
+ type: "LWM",
+ brand: "Tata",
+ model: "Safari",
+ color: "White",
isHighEndModel: false,
price: 1400000,
keyStart: function () {
- alert(this.model + 'started!');
- }
-}
+ alert(this.model + "started!");
+ },
+};
// access property with .DOT notation
console.log(VehicleObj2.brand);
// access property with []Bracket notation
-console.log(VehicleObj2['color']);
+console.log(VehicleObj2["color"]);
VehicleObj1.keyStart();
-console.log('// ------------------------------');
+console.log("// ------------------------------");
```
-12.05. Object constructor
----------------------
-12.05. Object constructor (using the new keyword)
----------------------
+## 12.05. Object constructor
-- In this method, create a function with arguments
+## 12.05. Object constructor (using the new keyword)
+
+- In this method, create a function with arguments
- Each argument value can be assigned in the current object by using `this` keyword, `this` keyword refers to the `current object`
-> **Syntax & Example**:
+> **Syntax & Example**:
+
```javascript
// create an object with new keyword - Object constructor with function
@@ -3262,122 +3325,122 @@ function Technology(name, version, type) {
console.log(this.type);
}
-let JavaScript = new Technology('JavaScript', 6, 'Script Language');
+let JavaScript = new Technology("JavaScript", 6, "Script Language");
console.log(JavaScript.version);
-console.log('// ------------------------------');
+console.log("// ------------------------------");
-function Vehicle(brand,model,color,price) {
+function Vehicle(brand, model, color, price) {
this.brand = brand;
this.model = model;
this.color = color;
this.price = price;
this.keyStart = function () {
- console.log(this.model + ' started!');
- }
+ console.log(this.model + " started!");
+ };
}
-var Maruti = new Vehicle('Maruti','Alto-100','White',400000);
+var Maruti = new Vehicle("Maruti", "Alto-100", "White", 400000);
Maruti.keyStart();
-console.log('// ------------------------------');
+console.log("// ------------------------------");
```
-12.06. Accessing objects properties
----------------------
-12.06. Looping through Objects properties
----------------------
+## 12.06. Accessing objects properties
+
+## 12.06. Looping through Objects properties
- To access or get the value of a property, you can use the `dot .`, or `square bracket []` notation
- We can iterate through the `key-value pairs` of an object using the `for...in loop`
- MyObject.propertyName; OR MyObject[propertyName]; OR MyObject['propertyName']
-> **Syntax & Example**:
+> **Syntax & Example**:
+
```javascript
// access/loop thourgh array element
// MyObject.propertyName; OR MyObject[propertyName]; OR MyObject['propertyName']
var Person = {
- name:'Dinanath',
- domain:'IT/Software',
- gender:'Male',
- city:'Mumbai',
- country:'India'
-}
+ name: "Dinanath",
+ domain: "IT/Software",
+ gender: "Male",
+ city: "Mumbai",
+ country: "India",
+};
console.log(Person.name);
-console.log(Person['domain']);
+console.log(Person["domain"]);
-console.log('// ------------------------------');
+console.log("// ------------------------------");
// Loop through an Array Elements
for (props in Person) {
- console.log(Person[props])
+ console.log(Person[props]);
}
-console.log('// ------------------------------');
+console.log("// ------------------------------");
```
-12.07. Removing Deleting objects properties
----------------------
+## 12.07. Removing Deleting objects properties
- The `delete` operator can be used to completely remove properties from an object
- delete MyObject.propertyName;
> **Note**:
-The `delete` operator only removes an `object property or array element`. It does not work/does not affect variables or declared functions.
+> The `delete` operator only removes an `object property or array element`. It does not work/does not affect variables or declared functions.
+
+> **Syntax & Example**:
-> **Syntax & Example**:
```javascript
// remove/delete Object's Properties
// delete MyObject.propertyName;
var Person = {
- name:'Dinanath',
- domain:'IT/Software',
- gender:'Male',
- city:'Mumbai',
- country:'India'
-}
+ name: "Dinanath",
+ domain: "IT/Software",
+ gender: "Male",
+ city: "Mumbai",
+ country: "India",
+};
-delete Person.name
+delete Person.name;
console.log(Person);
console.log(Person.name);
-console.log(Person['domain']);
+console.log(Person["domain"]);
```
-12.08. Manipulating by Value Vs Reference
----------------------
+## 12.08. Manipulating by Value Vs Reference
In JavaScript we have two categories of types:
+
1. Value Types (Primitives = Basic type) - Primitives are copied by their value
2. Reference Types (Objects = Complex type) - Objects are copied by their Reference/Location in memory
### 1. Value Types (Primitives)
- 1. Number
- 2. String
- 3. Boolean
- 4. Undefined
- 5. Null
- 6. Symbol (ES6)
+1. Number
+2. String
+3. Boolean
+4. Undefined
+5. Null
+6. Symbol (ES6)
### 2. Reference Types (Objects)
- 1. Object
- 2. Function
- 3. Array
+1. Object
+2. Function
+3. Array
+
+> **Syntax & Example**:
-> **Syntax & Example**:
```
???
```
-12.09. The Window object
----------------------
+## 12.09. The Window object
- Window Object the global variable/global object `available in the browser environment`, represents the browser window in which the script is running
- Simply, the window object `represents a window in a browser`
@@ -3386,23 +3449,22 @@ In JavaScript we have two categories of types:
- The Browser Object Model (BOM) allows JavaScript to "communicate/talk to" the browser
- In `Browser -> Inspect Element -> Console Panel` -> Type `Window`, check different properties and methods available
-> **Syntax & Example**:
-```javascript
+> **Syntax & Example**:
+```javascript
// Methods
-window.console.log('Console! Hello, Welcome to JavaScript');
+window.console.log("Console! Hello, Welcome to JavaScript");
-window.alert('Alert! Hello, Welcome to JavaScript');
+window.alert("Alert! Hello, Welcome to JavaScript");
// const namePrompt = window.prompt();
-const namePrompt = window.prompt('Enter Your Name');
+const namePrompt = window.prompt("Enter Your Name");
window.alert(namePrompt);
-
-if(window.confirm('Are you sure?')) {
- window.console.log('YES - selected');
+if (window.confirm("Are you sure?")) {
+ window.console.log("YES - selected");
} else {
- window.console.log('NO - clicked');
+ window.console.log("NO - clicked");
}
// Properties
@@ -3411,28 +3473,28 @@ if(window.confirm('Are you sure?')) {
outerHeight = window.outerHeight;
outerWidth = window.outerWidth;
-console.log('outerHeight -', outerHeight, '::', 'outerWidth -', outerWidth );
+console.log("outerHeight -", outerHeight, "::", "outerWidth -", outerWidth);
// document/page height & width
innerHeight = window.innerHeight;
innerWidth = window.innerWidth;
-console.log('innerHeight -', innerHeight, '::', 'innerWidth -', innerWidth );
+console.log("innerHeight -", innerHeight, "::", "innerWidth -", innerWidth);
// scroll position
-console.log('scrollY', window.scrollY);
-console.log('scrollX', window.scrollX);
+console.log("scrollY", window.scrollY);
+console.log("scrollX", window.scrollX);
-// location
+// location
-console.log('current window location/url', window.location);
-console.log('current window location/url', window.location.href);
+console.log("current window location/url", window.location);
+console.log("current window location/url", window.location.href);
// location redirect
-window.location.href = 'https://www.google.com';
+window.location.href = "https://www.google.com";
// window location/visited history
@@ -3442,22 +3504,20 @@ let totalPagesVisitedHistory = window.history.length;
// current browser details - navigator
-let curBrowser = window.navigator.appName;
+let curBrowser = window.navigator.appName;
//window.navigator.userAgent;
window.navigator.platform;
window.navigator.vendor;
-
```
-12.10. The Math Object
----------------------
+## 12.10. The Math Object
- The Math object allows to perform mathematical tasks
-- Math object provides several constants and methods to perform mathematical operation (like `min, max, sqrt, pi, round, random`, etc)
+- Math object provides several constants and methods to perform mathematical operation (like `min, max, sqrt, pi, round, random`, etc)
-> **Syntax & Example**:
-```javascript
+> **Syntax & Example**:
+```javascript
let pieValue = Math.PI;
console.log(Math.E);
@@ -3469,8 +3529,8 @@ console.log(Math.floor(2.6));
console.log(Math.sqrt(64));
console.log(Math.abs(-10)); //return absolute ie positive number
-console.log(Math.pow(8,2)); //64
-console.log(Math.pow(10,3)); //10 * 10 * 10 = 1000
+console.log(Math.pow(8, 2)); //64
+console.log(Math.pow(10, 3)); //10 * 10 * 10 = 1000
console.log(Math.min(20, 5, 9, 15, 2));
console.log(Math.max(20, 5, 9, 15, 2));
@@ -3478,24 +3538,22 @@ console.log(Math.max(20, 5, 9, 15, 2));
console.log(Math.random());
console.log(Math.random() * 20 + 1); // random number till 20
console.log(Math.floor(Math.random() * 20 + 1)); // random number till 20 without any decimals
-
```
-12.11. Date and Time
-=====================
+# 12.11. Date and Time
- The Date object is used to deal/work with date and time
- Simply, the JavaScript date object can be used to get date, day, month and year
- Date objects are created with `new Date()` - Date constructor can be used to create date object, It provides methods to get and set day, month, year, hour, minute and seconds
-> **Syntax & Example**:
-```javascript
+> **Syntax & Example**:
+```javascript
const today = new Date();
-console.log('today is:', today);
+console.log("today is:", today);
-const date1 = new Date('March 29 1980');
-const date2 = new Date('09-10-1980');
+const date1 = new Date("March 29 1980");
+const date2 = new Date("09-10-1980");
let currentDate = new Date();
@@ -3508,24 +3566,23 @@ const currentMinutes = currentDate.getMinutes();
const newBirthDate = currentDate.setMonth(5);
console.log(newBirthDate);
-
```
-Section 13. Events
-=====================
+# Section 13. Events
-13.01. Understanding Events and Event Handlers
----------------------
+## 13.01. Understanding Events and Event Handlers
- Events are happening/triggering all over, Event lets the developer know `something has occurred/happened`
- Events occur when the page loads (Onload), when the user interacts with the web page (clicked a link or button/hover) (onlick), pressed key, moved the mouse pointer, mouse-clicked/hover (onmouseover), entered text into an input box or textarea (onchange, onblur, onfocus), submits a form (submit), page unloads (unload)
- When an event occurs, use a JavaScript `event handler (or an event listener) to detect` them and perform a specific task - Event handlers name always begin with the word `"on"`, like onclick, onload, onblur, and so on
- To react to an event you `listen` for it and supply a `callback function or event handler` which will be called by the browser when the event occurs
-13.02. Different Event category
----------------------
+ 13.02. Different Event category
+
+---
In general, the events can be categorized into four main groups:
+
1. Mouse events
2. Keyboard events
3. Form events
@@ -3536,58 +3593,89 @@ In general, the events can be categorized into four main groups:
A mouse event is triggered when the user clicks some element, move the mouse pointer over an element, etc. Find here some of the important mouse events and their event handler:
- **click** (`onclick` event handler)
- - Occurs When the `mouse clicks on an element`, links, buttons etc. on a web page
+ - Occurs When the `mouse clicks on an element`, links, buttons etc. on a web page
- **contextmenu** (`oncontextmenu` event handler)
- Occurs when a `user clicks the right mouse button` on an element to open a context menu
-- **mouseover / mouseout** (`onmouseover` & `onmouseout` event handler)
+- **mouseover / mouseout** (`onmouseover` & `onmouseout` event handler)
- Occurs when the mouse pointer/cursor comes over / leaves (goes outside of) an element
- **mousedown / mouseup** (`onclick/onmousedown` & `onmouseup`)
- Occurs when the mouse button is pressed/released over an element
- **mousemove** (`onmousemove` event handler)
- Occurs when the mouse pointer/cursor is moved
-> **Syntax & Example**:
+> **Syntax & Example**:
+
```html
- ```
> **Syntax & Example**: `Change background color on mouse movement` -```js -const button = document.querySelector('.some-button'); -const headingText = document.querySelector('h1'); +```js +const button = document.querySelector(".some-button"); +const headingText = document.querySelector("h1"); -button.addEventListener('mousemove', someFunction); +button.addEventListener("mousemove", someFunction); function someFunction(evt) { - console.log('Event Details:', evt); - headingText.innerText = 'Changed after click!'; + console.log("Event Details:", evt); + headingText.innerText = "Changed after click!"; - document.body.style.backgroundColor = `rgb(${evt.offsetX},${evt.offsetY},40)` + document.body.style.backgroundColor = `rgb(${evt.offsetX},${evt.offsetY},40)`; } - ``` -### 13.02.02. Keyboard events +### 13.02.02. Keyboard events A keyboard event is fired up when the user presses or release a key on the keyboard. Here're some of the important keyboard events and their event handler: @@ -3597,29 +3685,32 @@ A keyboard event is fired up when the user presses or release a key on the keybo - Occurs when the user presses down a key on the keyboard that has a character value associated with it - Keys like Ctrl, Shift, Alt, Esc, Arrow keys, etc. will not generate a keypress event, but will generate a keydown and keyup event -> **Syntax & Example**: -```html - +> **Syntax & Example**: - +```html + + + ```
-> **Syntax & Example**: -```js +> **Syntax & Example**: -const nameText = document.querySelector('inputNameText'); -nameText.addEventListener('keypress', nameData); +```js +const nameText = document.querySelector("inputNameText"); +nameText.addEventListener("keypress", nameData); function nameData(evt) { - console.log('nameData function called'); + console.log("nameData function called"); headingText.innerText = evt.target.value; } - ``` ### 13.02.03. Form events @@ -3635,26 +3726,37 @@ A form event is triggered when a form control/form fields (text fields/radio but - **submit** (`onsubmit` event handler) - Occurs only when the user submits a form on a web page -> **Syntax & Example**: -```html -
- - ```
> **Syntax & Example**: `Form submit event`
-```js
-const personalDataForm = document.querySelector('form');
-personalDataForm.addEventListener('submit', submitData);
+```js
+const personalDataForm = document.querySelector("form");
+personalDataForm.addEventListener("submit", submitData);
function submitData(evt) {
- console.log('submitData function called');
+ console.log("submitData function called");
// to prevent the default behavior of an element - button, link, submit button etc.
evt.preventDefault();
}
-
```
### 13.02.04. Document/Window events
@@ -3698,28 +3797,28 @@ Events are happening/triggering all over. Events do trigger even when the page h
- Occurs when a user resizes the browser window, even when browser window minimized or maximized
> **Note**:
-The unload event is not supported properly in most of the browsers.
-
-> **Syntax & Example**:
-```html
-