Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

A JavaScript tutorials for beginners, An introduction to JavaScript programming languages building blocks, step-by-step guide to JavaScript

NotificationsYou must be signed in to change notification settings

dinanathsj29/javascript-beginners-tutorial

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

32 Commits
 
 
 
 

Repository files navigation

JavaScript logo

JavaScript for Beginners

JavaScript tutorial for Beginners

JavaScript basics and fundamentals for all

Description

JavaScript is ascripting 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)

Add topics to categorize your repository and make it more discoverable:

  • javascript-programming-language
  • javascript-language-fundamentals
  • javascript-basic-programming
  • javascript-tutorial
  • javascript-library
  • learning-javascript
  • javascript-programs
  • variables-var-let-const
  • conditions
  • loops
  • arrays
  • objects
  • events
  • dom-document-object-model
  • webdevelopment
  • front-end-development
  • webprogramming
  • plain-javascript
  • vanilla-javascript
  • javascript-typescript-es6

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:

Topics include

  1. Course Introduction
  2. Introducing JavaScript
  3. JavaScript Getting Started
  4. JavaScript Language Fundamentals
  5. Variables
  6. Data types
  7. Operators
  8. Functions
  9. Loops |Loops and Iterations
  10. Conditions - Control Flow
  11. Array
  12. Objects
  13. Events
  14. DOM (Document Object Model)
  15. What's Next Step?

Section 01. Course Introduction

01.01. Welcome

Hi All, I'mDinanath 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

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

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 forHyperText Markup Language which is used for creatingweb 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
  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 ascripting 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

<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><metahttp-equiv="X-UA-Compatible"content="ie=edge"><title>02.01.js.intro.html</title><!-- internal style --><style>/* css selector: { property:value; } */body {font-family: arial;      }</style><!-- internal JavaScript - head section --><script>// Write all JavaScript code herealert('welcome to JavaScript');</script></head><body>    Content<!-- internal JavaScript - body section --><script>/* Write all JavaScript code here */console.log('welcome to JavaScript');</script></body></html>

02.02. What is JavaScript?

  • JavaScript is1 of the 3 core language/layers of web...(HTML, CSS & JavaScript)
  • JavaScript is one of the most popular, widely used, lightweight scripting programming language
  • JavaScript is anOpen Source,Cross-Platform, andBrowser-based Client-Side (user computer) programming language of the web
  • JavaScript is a dynamic computer programming language. It is aninterpreted (translated) programming language withobject-oriented capabilities
  • JavaScript is officially maintained byECMA (European Computer Manufacturers Association) as ECMAScript
  • ECMAScript 6 (orES6 or ECMAScript 2015) is the latest major version of the ECMAScript standard
  • JavaScript is case sensitive language

Note:
Now-a-days with the help ofNode (Node.js) JavaScript is used forBack-end (Server-side) API development. JavaScript is not compiled language, but it is a translated language (JavaScript Translator (embedded in the browser engine) is responsible for translating the JavaScript code for the web browser.

   

Stackoverflow Programming, Scripting, and Markup Languages Survey 2019

    Image 02.02.01 - Stackoverflow Programming, Scripting, and Markup Languages Survey 2019

   

Google Trends Language Compare

    Image 02.02.02 - Google Trends - Language Compare

02.03. What is a scripting language?

  • A high-level programming language that is interpreted by another program at runtime rather than compiled by the computer's processor as other programming languages
  • A programming language designed for integrating and communicating with other programming languages
    • Popular scripting languages areJavaScript, VBScript, PHP, Perl, Python, Ruby, ASP
    • Since a scripting language is normally used in conjunction with another programming language, they are often found and used alongsideHTML, Java or C++
  • The simple difference between scripting language and programming language is: Scripting languages do not require the compilation step and are rather interpreted
    • C program needs to be compiled before running whereas normally, a scripting language likeJavaScript or PHP need not be compiled
  • Scripting is interpreted based language, whereas Java, C, C++, and others are compiler-based language

What is a script?

  • A script is nothing but sets of instructions
  • Series of commands

02.04. What can you do with JavaScript?

02.04. Use of JavaScript

For a long time, JavaScript is used only as aClient Side Front End Development language to build browser-based interactive web pages. But currently due to huge community support(Node or Nide.js) JavaScript is multi-purpose language and used to develop:

  • Full-fledged Enterprise Web Application
  • Full-blown Mobile Apps
  • Real-time Networking Apps (Chats, Audio/Video Streaming Services)
  • Games
  • Command Line Tools (CLI-Command Line Interface utilities)

02.04.01. JavaScript is used in billions of Web pages/web apps to add interactivity, validate forms and much more:

  • JavaScript gives HTML designers aprogramming tool
  • JavaScript can react toevents (mouse click, hover (rollover, rollout), focus, blur)
  • JavaScript can be used tovalidate data (Client-side validation)
  • JavaScript can manipulateHTML content andCSS styles
  • Dynamicdrop-down menus, HTML contents at run time/on the fly
  • Displaying live/current/dynamicdate and time (clocks)
  • Displayingpop-up windows anddialog boxes (analert,confirm andprompt dialog box)
  • Change the website'sbehavior and make it moredynamic with advanced web designs
  • Perform andcontrol transitions andanimations

However, there are more serious uses for #"Permalink: However, there are more serious uses for javascript:" href="#however-there-are-more-serious-uses-for-javascript">

  • Browser Detection - Detecting the browser used by a visitor
  • Cookies - Storing information on the visitor's computer
  • Control Browsers - Opening pages in customized windows
  • Validate Forms - Validating inputs to fields before submitting a form

02.05. Where does the JavaScript code run?

JavaScript was originally designed and developed to run only in browsers. But now with the help of theNode/Node.js (C++ program, that includes Google's V8 JavaScript engine) we can build the back-end(server-side) for our web and mobile applications.

Common JavaScript Browser Engines

BrowserEngine
Browser, Headless Browser, or RuntimeJavaScript Engine
MozillaSpidermonkey
Safari**JavaScriptCore*
IE and EdgeChakra
ChromeV8
TrifleJSV8
Node.js***V8
Io.js***V8
PhantomJSJavaScriptCore
HTMLUnitRhino

02.06. Who are using JavaScript?

  • JavaScript is used by:

    • Front-end Developer
    • Back-end Developer
    • Full-stack Developer
  • Big companies and brands build entire applications:

    • Netflix
    • Walmart
    • PayPal
    • Microsoft
    • Facebook (React.js)
    • Google (Angular.js)
    • Ebay
    • Uber
    • Groupon

02.07. History of JavaScript

  • Invented by“Brandan Eich” atNetscape in1995 originally named as"LiveScript"
  • Netscape &Sun Java agreements to rename"LiveScript" to"JavaScript" (Asjava is already popular in the market)
  • Not at-all related toJAVA (completely different in concept and design)
  • Microsoft has developed new version of "JavaScript" as"JScript" forIE-3 in1996
  • JavaScript Submitted toECMAScript in 1997

02.08. JavaScript Vs ECMAScript

JavaScriptECMAScript
JavaScript isscripting programming languageECMAScript is aspecification/standard
JavaScript is invented byBrandan Eich atNetscapeECMAScript standards defined byECMA (European Computer Manufacturers Association)
JavaScript is released in 1995First ECMAScript standard published in 1997
JavaScript uses/follows ECMAScript specifications/standardsECMAScript specification defines many new features for JavaScript

02.09. Types of Script

02.09. Various Scripting languages

02.09. Client-Side Scripting Vs Server Side Scripting

Client-Side ScriptingServer-Side Scripting
Instruction for web BrowserInstruction for web Server
Client-side scripting is used when the user's browser already has all the code and the page is altered based on the user's inputServer-side scripting is used to create dynamic pages based several conditions when the user's browser requests the server
Response from a client-side script is faster as compared to a server-side script because the scripts are processed on the local computerResponse from a server-side script is slower as compared to a client-side script because the scripts are processed on the remote computer (server)
Client-side scripting languages such as JavaScript, VBScript, etc. are interpreted and executed by the web browserServer-side scripting languages such as ASP, PHP, Java, Python, Ruby, etc. run on the webserver and the output sent back to the web browser in HTML format
Example: Javascript, VB script, ActionScript, HTML, XHTML etc.Example: ASP, JSP, PHP, ASP#.Net, Perl, Ruby, Python, CGI etc.

02.10. Prerequisites of using HTML and JavaScript

Tools for building web sites-web pages/writing HTML, CSS & JavaScript

  1. Text Editor/HTML Editor/Code Editor/Visual Code Editor -NotePad, NotePad++, SublimeText, Atom, Brackets, Coda, Visual Studio Code, DreamWeaver etc.

    • Just visit registered website of any of your favorite editor, download and install it (likeVisual Studio Code =https://code.visualstudio.com)
    • A JavaScript file (.js) is a text file itself consists of JavaScript code/statements, so to create/modify a JavaScript file we can use any text editors
  2. Browsers - To view output of .html pages with .js files -Google Chrome, Mozilla Firefox, Internet Explorer, Safari etc.

    • Once the .html/.htm file created and saved, we can create a .js file and link within HTML and then we can see its output in any latest web browser
  3. JavaScript Output / Debugging Tool (Developer console) -

    • alert() or window.alert()
    • console.log()
    • Google Chrome / Safari –Developer Tools Inspect / Inpsect element (in browser -> Right Click on page -> chooseInspect / Inspect Element -> Console Tab
    • Mozilla FireFox –Firebug

Note:
UseF12 key on the keyboard to open thedeveloper tools then click on theConsole Tab, OR on empty area in browser pageRight Click -> Inspect (Developer Tool) -> Console Tab. Here You can write basic JavaScript statements and/or valid JavaScript code directly in browser console panel/tab and get the output

   

all browsers

    Image 02.10.01 - Widely used modern browsers

   

developer tool inspect console

    Image 02.10.02 - Developer Tool Inspect Console

   

developer tool inspect console

    Image 02.10.03 - Developer Tool Inspect Console

Section 03. JavaScript Getting Started

03.01. How to write Javascript?

03.01. JavaScript in HTML

  • The HTML<script>.....</script> tag is used to embed/insert/implement a JavaScript programs/code into any part of an HTML document/page
  • The<script>.....</script> tag specifies that we are using JavaScript
  • The<script>.....</script> element can be placed in the<head>, or<body> section of an HTML document
  • Each<script>.....</script> tag blocks the page rendering process until it has fully downloaded and executed the JavaScript code
    • So the best practice is to place/add the<script>.....</script> at the bottom/end ofbody tag/section ie. just before the closing</body> tag

Note:
JavaScript is the default scripting language in HTML. The old HTML standard attributes liketype="text/javascript" andlanguage="javascript" no longer required in modern browser

Syntax & Example:03.01.js.script.tag.html

<head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><metahttp-equiv="X-UA-Compatible"content="ie=edge"><title>03.01.js.script.tag.html</title><!-- internal style --><style>/* css selector: { property:value; } */body {font-family: arial;      }</style><!-- internal JavaScript - head section --><script>// Write all JavaScript code herealert('welcome to JavaScript');</script></head><body>        Content<!-- internal JavaScript - body section --><script>/* Write all JavaScript code here */console.log('welcome to JavaScript');document.write('This is dyanamic content. Hello All, Lets write something on web page');</script></body>

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)

03.02.01. Inside the HEAD section (code between the head tag)

  • JavaScript programs/code/statements can be placed in the<head> section of an HTML page
  • As each<script>.....</script> tag blocks the page rendering process until it has fully downloaded and executed the JavaScript code so placing them in thehead section (<head> element of the document without any valid reason will significantly impact your website performance

Syntax & Example:03.02.01.js.head.html

<head><!-- internal JavaScript - head section --><script>// Write all JavaScript code herealert('welcome to JavaScript written in head section');</script></head>

03.02.02. Inside the BODY section (code between the body tag)

  • JavaScript programs/code/statements can be placed in the<body> section of an HTML page
  • As blocking nature of<script>.....</script> tag ideally, scripts should be placed at the end of thebody section, just before theclosing </body> 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

<body>    page content<!-- internal JavaScript - body section --><script>// Write all JavaScript code herealert('welcome to JavaScript written in body section');console.log('welcome to JavaScript written in body section');document.write('<h2>welcome to JavaScript written in body section</h2>');</script></body>

03.02.03. External JavaScript .js file (separation of concern)

  • We can easily write JavaScript code in between thescript element. In a real-world application, we have 100+ maybe even 1000+ lines of code, we don't want to write all that code inline here
  • We must have toextract 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<script> tag withsrc (source) attribute:
    • <script src="path/scriptfile.js"></script>
    • One can provide afull URL (absolute path) orrelative path from the current page
  • We can create a single external JavaScript file and embed it in many/any HTML page which providecode re-usability

03.02.04. Advantages of External JavaScript

  • It separates HTML and JavaScript code (separation of concern)
  • Code re-usability
  • It makes HTML and JavaScript file/code easier to read, maintain and more meaningful/semantic
  • 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.

Syntax & Example -.html file:03.02.03.js.external.html

<body>    page content<!-- include external JavaScript - body section --><scriptsrc="./03.script.js"></script></body>

Syntax & Example -.js file:03.02.03.script.js

// external js file// Write all JavaScript code herealert('welcome to JavaScript written in external file');console.log('welcome to JavaScript written in external file');document.write('<h2>welcome to JavaScript written in external file</h2>');

03.03. JavaScript Code structure

The syntax of JavaScript is theset 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

  • One line of JavaScript Code is one JavaScript Statement / Instruction / Command
  • Statements are a command to Browser to do something / perform actions
  • A Statement is a piece of code that expresses an action to take place
  • JavaScript code/program (or just JavaScript) is a sequence of statements
  • Statements are written in-between<script>.....</script> tag
  • Statements are separated bySemicolon; so we may write many statements in a line (optional)
  • 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 aSemicolon;

Note:
JavaScript statements are composed of:Values, Operators, Expressions, Keywords, and Comments

03.03.02. Whitespace and Line Breaks

  • JavaScript ignoresspaces, tabs, and newlines that appear in JavaScript programs
  • We can freely use spaces, tabs, and newlines to format and indent programs in a neat-clean and consistent way that makes the code easy to read and understand (not advisable)

03.03.03. Semicolons

  • JavaScript statements are generally followed by asemicolon; character
  • A semicolon may be omitted inmost cases when a line break exists
  • JavaScript interprets the line break as animplicit semicolon, called anautomatic semicolon insertion
  • 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

03.03.04. Case Sensitivity

  • JavaScript is a case-sensitive language
  • in Javascript variables, language keywords, function names, and other identifiers must always be typed with a consistent capitalization of letters
  • Example:var firstName='Dinanath'; andvar FirstName='Dinanath'; herefirstName & FirstName are different ie. two different variable

Note:
Take care/precautions while writing variable and function names in JavaScript

03.03.05. JavaScript Code Blocks

  • JavaScript commands/statements/code can be grouped together in code blocks,inside curly brackets {...}
  • Grouped statements/lines form code blocks
  • The purpose of code blocks is to define statements to be executed together like a single JavaScript command
  • An often occurrence of a code block in JavaScript is a JavaScriptfunction

Syntax & Example:03.03.05.script.js

// external js file// Write all JavaScript code here// define function - block of code to show welcome messagefunctionsayHello(){alert('Hello All! Welcome to JavaScript!!');}// define function - block of code to show total of two numbersfunctionshowTotal(){varnum1=10;varnum2=20;vartotal=num1+num2;alert('Total is : '+total);}// invoke / run  / call a functionsayHello();showTotal();

03.04. JavaScript Keywords

Usually, JavaScript commands/statements start with aspecific keyword which defines whataction/function should the browser will perform/do:

KeywordKeywordKeywordKeywordKeyword
breakdo ... whileif ... elsetry ... catchconst
continueforreturnvarclass
debuggerfunctionswitchletimport

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 inECMAScript 6. It also includes keywords that arereserved for future as well as keywords that aredisallowed 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

  • The comments are a meaningful way todeliver 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)
  • Comments are used to explain code/programs/statements and to make it more readable for developers
  • A comment is ignored by the JavaScript engine embedded in the browser
  • Comments can also be used to prevent the execution of certain logic when testing code
  • Comments can be put into any place of a script, they don’t affect its program execution because the engine simply ignores them
  • Comments help tomake code easy to understand andit avoids the unnecessary code

03.05.01. Types of JavaScript Comments

There are two types of comments in #"auto">

  • Single-line Comments
  • Multi-line Comments
  • 03.05.01.01. Single-line Comments

    • Single-line JavaScript comments are used for one line of comment only
    • Single-line comments starts withtwo forward slash:// is single comment
    • Any statements between// till the end of the line will be ignored by JavaScript (not be executed)
    • Single-line comments do not need closure/closing

    Syntax & Example:03.05.script.js

    // external js file// Write all JavaScript code here// show alert boxalert('Welcome to JavaScript!');varfirstName='Dinanath';// variable to store firstNamevarlastName='Jayaswal';// variable to store lastName

    03.05.01.02. Multi-line Comments

    • 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 withforward 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 forformal documentation

    Syntax & Example:03.05.script.js

    /* show alert box */alert('Welcome to JavaScript!');/* This is a multiline comment.A code block can be commented on. *//* var firstName = 'Dinanath'; // variable to store firstNamevar lastName = 'Jayaswal'; // variable to store lastName */

    Section 04. JavaScript Language Fundamentals

    04.01. Generating Output

    • JavaScript does not have anydisplay or built-in print functions
    • Many times we may need to generate output from your JavaScript code likesee the value of a variable, orwrite a message to browser console to help youdebug 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.)
    • Using different output methods knowledge will help you while debugging or rewriting your code more conveniently

    Different ways to show output/display data

    1. Writing into an alert box withalert() or window.alert()
    2. Writing into browser console withconsole.log()
    3. Writing into the HTML / Browser Window withdocument.write()
    4. Write into an element of HTML / Inserting Output Inside an HTML Element withinnerHTML

    04.01.01. Displaying Output in Alert Dialog Boxes: alert() or window.alert()

    • One can usealert dialog boxes to display the message or output data to the user
    • An alert dialog box is created using thealert() 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

    // external js file// Write all JavaScript code herealert('I am Dinanath Jayaswal');window.alert('We are learning JavaScript');

    04.01.02. Writing Output to Browser Console: console.log()

    • Programmers can easily output a message or write data to the browser console using theconsole.log() method
    • console.log() function is mainly/widely used fordebugging code as it makes the JavaScript output print to console
    • This is a simple, easy but very powerful method for generating detailed output

    Syntax & Example:04.01.02.script.js

    // external js file// Write all JavaScript code hereconsole.log('I am Dinanath Jayaswal');console.log('We are learning JavaScript');

    Note:
    UseF12 key on the keyboard to open thedeveloper tools then click on theconsole 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()

    • document.write() method is used to write the content to the current document while document is being parsed
    • Programmers do ues document.write() fortesting purposes

    Syntax & Example:04.01.03.script.js

    // external js file// Write all JavaScript code heredocument.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'sinnerHTML property
    • First we need to select the element using a method such asdocument.getElementById(id)

    Note:
    HTML element manipulating is fully dependent on JavaScript DOM manipulation concepts

    Syntax & Example:04.01.04.script.js

    /// external js file// Write all JavaScript code here// Writing text string inside an elementdocument.getElementById('mainHeadingText').innerHTML='Heading Text change dynamically on run-time';varparaText=document.getElementById('mainParaText');paraText.innerHTML='<strong>This Paragraphic text inserted dynamically through innerHTML method.</strong>';

    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

    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 iscontainer to store/hold the data/information
    • Developers/Programmers use Variable tostore/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 aname 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.
    • The data or value stored in the variables can be set, updated, and retrieved whenever needed
    • Variables are declared using the keywordvar keyword
    • Theassignment operator (=) is used to assign value to a variable, like this:var varName = value; orvar firstName = 'JavaScript';
    • By default value of variable defined in JavaScript isundefined (variable is defined but value not assigned:var firstName; orlet lastName; console.log(firstName, lastName); // undefined)

    • Example: Variables are likebox or an envelope which we use toorganize various kinds of stuff and put alabel on each box or an envelope
    • Example: Variable declaration and assignment is justlike Maths & Algebra:x = 10; and in JavaScript we writevar x = 10;

    Note:
    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 withlet keyword:let techName = 'JavaScript' ;


    Syntax & Example:05.01.script.js

    // variables defined to hold different types of datavartechName='JavaScript';// String literalvarversion=6;// Number literalvarisDone=true;// Boolean literalconsole.log('Learning '+techName+version);

    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

    // Declaring VariablesvartechName;varversion;varisDone;// Assigning valuetechName='JavaScript';version=6;isDone=true;console.log('Learning '+techName+version);// ------------------------------// Declaring VariablevaruserName;// Assigning valueuserName='Dinanath';console.log('Welcome '+userName);

    05.03. Declaring multiple variables at once

    We can alsodeclare multiple variables and set their initial values in a single statement, each variable isseparated by comma.

    Syntax & Example:05.01.script.js

    // Declaring multiple variablesvartechName='JavaScript',version=6,isDone=true;// Declaring multiple variables in multiple lines for readabilityvartechName='JavaScript',version=6,isDone=true;console.log('Learning '+techName+version);// ------------------------------// Declaring multiple variablesvarfirstName='Dinanath',lastName='Jayaswal',age=35,isMarried='true';// Declaring multiple variables in multiple lines for readability/* var firstName = 'Dinanath',lastName = 'Jayaswal',age = 35,isMarried = 'true'; */console.log('I am '+firstName+' '+lastName);

    05.04. Variable Naming Conventions

    05.04. Variable Naming Conventions (Identifiers)

    All JavaScript variables must beidentified/referred/defined/named withunique names, called asidentifiers. 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 asidentifiers)
      • Identifiers aresimply names in JavaScript
      • Identifiers are used to name variables, keywords, functions, and labels
      • Identifiers can beshort names/nick names (like name, age, num1, isDone, sum) or more descriptive names (firstName, totalDashboards, isSeniorCitizen)

    The basic rules for defining/assigning names for variables (unique identifiers) are:

    • A variable name muststart with a letter, underscore (_), or dollar sign ($)
      • Example: var firstName, var _firstName, var $firstName;
    • Names can contain letters, digits, underscores, and dollar signs
      • Example: var $num_total1;
    • A variable namecannot start with a number or special characters
      • Example: var 1num_total, var .num_total
    • A variable namecannot contain spaces
      • Example: var num total;
    • A variable Names arecase sensitive
      • Example: var firstName='Dinanath'; and var FirstName='Dinanath'; herefirstName & FirstName are different ie. two different variable
    • A variable name cannot be aJavaScript keyword or a JavaScript reserved word
      • Example: var var; var switch; var for; var true;
    • One should Always givemeaningful/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)

    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

    Syntax & Example:05.04.script.js

    // variables defined to hold different types of datavar_firstName='JavaScript';var$version=6;var$num_total1=10;window.alert('variables details: '+_firstName+' '+$version+' '+$num_total1);// wrong identifiers// var #name;

    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

    05.05.01. Local Variables

    • A JavaScript local variable is declaredinside block or function
    • It is accessible within thefunction or blocks only
    • A local variable will bevisible only within a function where it is defined
    • Function parameters are always local to that function

    Note:
    In the function body, alocal variable takes precedence over a global variable with the same name.

    Syntax & Example:05.05.01.script.js

    // global variablevarglobalName='Global';window.alert(globalName);functionshowName(){// local variablevarlocalName='Local';window.alert(localName);window.alert(globalName);// recall global variable}// invoke/call/run functionshowName();// error - as local variable not exist/available outside of block { }window.alert(localName);

    05.05.02. Global Variables

    • A variabledeclared outside the function/at the root or declaredwith 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

    // global variablevarglobalName='Global';window.alert(globalName);functionshowName(){// local variablevarglobalName='Local';window.alert(globalName);// define global variable with windowwindow.globalVersion=29;window.alert('global variable from inside function: '+window.globalVersion);}// invoke/call/run functionshowName();// access global variable defined inside functionwindow.alert('global variable from outside function: '+window.globalVersion);

    05.06. The let and const keywords ES6

    ES6 introduces two new keywordslet andconst for declaring variables. Thevar, 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 differentold way, with scope issues
    • Bothlet andconst keywords declare variables,scoped at block-level ({})
    • Block scoping means that a new scope is createdbetween a pair of curly brackets {}

    05.06.01. The let Keyword

    ES6 introduces the newlet 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 thevar keyword arefunction-scoped and can behoisted at the top within its scope
    • Variables declared withlet keyword areblock-scoped ({}) and they are not hoisted

    Syntax & Example:05.06.01.script.js

    // traditional var syntaxvartechName1='JavaScript';for(vari=1;i<=5;i++){console.log('i : '+i);// 1,2,3,4,5console.log('inside block:'+techName1);varversion1=100;}console.log('outside: '+i);console.log('outside: '+version1);// ------------------------------// ES6 syntaxlettechName2='LiveScript';for(letn=1;n<=5;n++){console.log('n : '+n);// 1,2,3,4,5console.log('inside block:'+techName2);letversion2=100;}console.log(n);// undefinedconsole.log('outside: '+version2);// undefined

    05.06.02. The const Keyword

    ES6 introduces the newconst keyword for declaring variables.

    • Useconst to declare a constant(read-only / unchanging) variable
    • Constants areread-only, youcannot reassign new values to them
    • In Programm/logic when the variable will never change, they can be declared asconst
    • constants are named using capital letters and underscoreExample: const NATIVE_CITY
    • const are alsoblock-scoped likelet
    • However, you can changeobject properties orarray elements

    Syntax & Example:05.06.02.script.js

    // traditional var syntaxvarPI1=3.14;console.log(PI1);// 3.14PI1=100;console.log(PI1);// 100// ------------------------------// ES6 syntaxconstPI2=6.28;console.log('ES6 syntax const: '+PI2);// 6.28PI2=100;// error

    Section 06. Data types

    06.01. Data types

    A variable in JavaScript can containany type of data. Data types specify whatkind 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 aretwo main categories/types of data types in #"auto">

  • Primitive (Primary or Value) data type
    • String
    • Number
    • Boolean
    • Undefined
    • Null
    • Symbol (newly introduced in ES6)
  • 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 canhold only one value at a time. Primitives arecompared 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 TypeDescription
    Stringrepresent textual data. e.g. "welcome" or 'to javascript'
    Numberrepresents numeric values e.g. 10, 100.29
    Booleanrepresents boolean value either false or true
    Undefinedrepresents an undefined value (a variable declared but value not assigned)
    Nullrepresents null i.e. no value at all

    06.02.01. String

    • The string data type is used torepresent textual data (i.e. sequences of characters)
    • Strings hold information inwords/text
    • A string in JavaScript must be surrounded by"double" or'single' quotes
    • Example:06.02.script.js
    varfirstName="Java";varlastName='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:
    varage=25;varid=1;

    06.02.03. Boolean

    • 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 inconditional testing of code
    • Example:
    varisDone=true;varisMarried=false;

    06.02.04. Undefined

    • The meaning of undefined is“value is not assigned”
    • The undefined data type can only have one value-the special value undefined
    • A Variable has been declared, butnot assigned a value
    • A variablewithout a value, The type is also undefined
    • Example:
    varfirstName;varcountry;

    06.02.05. Null

    • 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:
    varfirstName=null;varid=null;

    06.03. Non-primitive data type

    06.03. Non-primitive, Reference or Composite data type

    • Non-primitive/Reference data types can holdcollections of values and more complex entities
    • Non-primitive values are being compared byreference instead of value
    • Data does not store in the variables but stored on the heap - a dynamically allocated memory reference
    • Its a pointer to a location in memory, accessed by reference

    There are different types of non-primitive data types in JavaScript. They are as follows:

    Data TypeDescription
    Arrayrepresents a group of similar value (multiple values in one variable)
    Objectrepresents an instance through which we can access members (property & value)
    Functionrepresents function (bunch/block of line to execute once)

    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
    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)
    • A JavaScriptvariable 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 thatsame 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

    letname='JavaScript';name=false;name=100;alert(name);alert(typeof(name));

    06.05. The typeof Operator

    • The typeof operator returns thetype of the argument
    • It’s useful to process values of different types differently or want to perform a quick data type check
    • The typeof operator can be used to find out whattype of data a variable or operand contains
    • It can be used with or without parentheses(typeof(x) ortypeof x

    Syntax & Example:06.05.script.js

    // use typeof to find data type of variables// Stringsalert(typeof"Hello");// "string"alert(typeof'12');// "string"// Numbersconsole.log(typeof(100));// "number"console.log(typeof(100.29));// "number"// Booleansalert(typeoftrue);// "boolean"alert(typeof(1==2));// "boolean"// Undefinedconsole.log(typeofundefined);// "undefined"varinit;console.log('type of init: '+typeofinit);// "undefined"// Nullconsole.log(typeofnull);// "object"varinitObject=null;console.log('type of initObject: '+typeofinitObject);// "object"// Objectsalert(typeof{name:'Dinanath',age:35});// "object"alert(typeofdocument);// "object"alert(typeofwindow);// "object"// ArraysvartechArray=[];console.log('type of techArray: '+typeoftechArray);// "object"console.log(typeof['JavaScript','jQuery','Angular']);// "object"console.log(typeof['Dinanath',35,'India']);// "object"// Functionsconsole.log(typeoffunction(){});// "function"console.log(typeofalert);// "function"console.log(typeofwindow.alert);// "function"// Symbolalert(typeofSymbol("dob"));// "symbol"

    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 aninput in the form, its data type is a string by default, so do any calculations we need toparse tointeger/int or the number
    • Data type conversion can be either implicit (automatic) or explicit (forcefully/manually)

    Syntax & Example:

    // Number to String conversionletnum1=100;console.log(num1);console.log(typeofnum1);console.log(num1.length);//error as number type variables does not have lengthnum1=String(num1);console.log(num1);console.log(typeofnum1);console.log(num1.length);// Boolean to String conversionletboolValue1=String(false);console.log(boolValue1);console.log(typeofboolValue1);// Date to String conversionletcurDate=String(newDate());console.log(curDate);console.log(typeofcurDate);// Array to String conversionletnumArray=String([1,2,3,4,5]);console.log(numArray);console.log(typeofnumArray);// toString() methodletcurString=(1000).toStringletcurString=(true).toString//  String to Number conversionletnum2='100';console.log(num2);console.log(typeofnum2);console.log(num2.toFixed(2));//helps to fix decimals - error as string type variables does not have any properties or methods related to numbernum2=Number(num2);console.log(num2);console.log(typeofnum2);console.log(num2.toFixed(2));// Boolean to Number conversionletboolValue2=Number(false);// parseInt() methodletcurNumber=parseInt('100');letcurNumber=parseFloat('100.41');

    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:

    constnum1='20';constnum1=10;constsum=(num1)+(num2);console.log(sum);console.log(typeofsum);

    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 [ ]
    • Operators are symbols/keywords that tell the JavaScript engine toperform 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 createexpressions to implement logic and algorithms

    Note:
    Let us take a simple expressionvar sum = 1 + 2;

    • Here 1 and 2 are calledoperands and
    • = &+ are called theoperator
    • = is the assignment operator,+ is the arithmetic operator

    Syntax & Example:07.01.script.js

    // Lets take a look on simple expressionvarsum=1+2;// 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
    4. Comparison (or Relational) Operators
    5. Conditional (or ternary) Operators
    6. String Operators
    7. Bitwise 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):

    OperatorsDescriptionExample / Result
    +Addition10 + 20 = 30 (Sum of num1 and num2)
    -Subtraction20 - 10 = 10 (Difference of num1 and num2)
    *Multiplication10 * 20 = 200 (Product of num1 and num2)
    /Division20 / 10 = 2 (Quotient of num1 and num2)
    %Modulus (Division Remainder)20 % 10 = 0 (Remainder of num1 divided by num2)
    ++Incrementvar num1 = 100; num1++; Now num1 = 11
    --Decrementvar 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

    // Arithmetic operatorsvarnum1=10;varnum2=4;alert('Addition '+(num1+num2));// 14alert('Subtraction '+(num1-num2));// 6alert('Multiplication '+num1*num2);// 40alert('Division '+num1/num2);// 2.5alert('Modulus reminder '+num1%num2);// 2num1++alert('after Increment '+num1);// 11num2--;alert('after Decrement '+num2);// 3num1=10;num2=4;alert('Exponentiation '+(num1**num2));// (10 ** 4) = 10* 10 * 10 * 10 = 10000

    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):

    OperatorsDescriptionExample / Result
    =Simple Assignment10 + 20 = 30; / var total = num1 + num2; (assigns a value to the variable)
    +=Add and assignvar num1 = 10; num1 += 20; Now num1 = 30 (assigns and adds value to the variable, num1 += 20; is equivalent to num1 = num1 + 20;)
    -=Subtract and assignvar num1 = 10; num1 -= 5; Now num1 = 5 (assigns and subtract value to the variable, num1 -= 5; is equivalent to num1 = num1 - 5;)
    *=Multiply and assignvar num1 = 10; num1 *= 5; Now num1 = 50 (assigns and multiply value to variable, num1 *= 5; is equivalent to num1 = num1 * 5;)
    /=Divide and assignvar num1 = 10; num1 /= 5; Now num1 = 2 (assigns and divide value to the variable, num1 /= 5; is equivalent to num1 = num1 / 5;)
    %=Modulus and assignvar 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

    // Assignment operatorsvarnum1=10;varnum2=20// old methodology// num1 = num1 + num2;// console.log(num1); // 30// new techniquesnum1+=num2;console.log(num1);// 30// num2 -= num1;// console.log(num2); // 10// num1 *= num2;// console.log(num1); // 200// num2 /= num1;// console.log(num2); // 2

    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):

    OperatorsDescriptionExample / Result
    &&Logical ANDx && y; (True if both operands like x and y are true)
    ||Logical ORx || 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

    // Logical operators - basic examples// && (Logical AND) - returns true if both operands are trueconsole.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 trueconsole.log('true || true: ',true||true);console.log('true || false: ',true||false);console.log('false || true: ',false||true);// ------------------------------// ! (Logical NOT) True if operand is not true (means I will be true if other is false)varisSeniorCitizen=true;varisYoungGeneration=!isSeniorCitizen;console.log('isYoungGeneration: ',isYoungGeneration);

    Syntax & Example:07.04.02.script.js

    // Logical operators - real world scenario/example// check credit/loan eligibility - (if applicant have HIGH INCOME & GOOD CREDIT SCORE, he is eligible for credit/loan)varisEarningHighIncome=true;varisGoodCibilScore=false;varisEligibleForLoan;// check eligibility with && Logical AND operatorisEligibleForLoan=isEarningHighIncome&&isGoodCibilScore;alert('isEligibleForLoan: '+isEligibleForLoan);// check eligibility with || Logical OR operatorisEligibleForLoan=isEarningHighIncome||isGoodCibilScore;alert('isEligibleForLoan: '+isEligibleForLoan);// ! Logical NOTvarisLoanRefused=!isEligibleForLoan;alert('isLoanRefused: '+isLoanRefused);

    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
    • The comparison operators are used to determine the similarity and difference between different variables

    JavaScript supports the following Comparison (or Relational) operators (List of Comparison (or Relational) operators):

    OperatorsDescriptionExample / Result
    ==
    (Loose Equality Operator)
    Is equal to / identicalx == y (True if x is equal to y)
    ===
    (Strict Equality Operator)
    Eqaul/identical value and identical typex === y (True if x is equal to y, and they are of the same type)
    !=Not equal to / differentx != y (True if x is not equal to y)
    !==Not identical / different value or different typex !== y )True if x is not equal to y, or they are not of the same type)
    <Less thanx < y (True if x is less than y)
    >Greater thanx > y (True if x is greater than y)
    <=Less than or equal tox <= y (True if x is less than or equal to y)
    >=Greater than or equal tox >= y (True if x is greater than or equal to y)

    Syntax & Example:07.05.script.js

    // Comparison (or Relational) operatorsvarnum1=25;varnum2=35;varnum3="25";alert(num1==num3);// truealert(num1===num3);// falsealert(num1!=num2);// truealert(num1!==num3);// truealert(num1<num2);// truealert(num1>num2);// falsealert(num1<=num2);// truealert(num1>=num2);// false

    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 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
    OperatorsDescriptionExample / Result
    ?Ternary operatorvar result = x < y ? 'x is smaller' : 'y is smaller' (short hand method to write if condition)

    Syntax & Example:07.06.script.js

    // Conditional (? or ternary) Operator// age categoryvarcurrentAge=100;varcategory;category=(currentAge<18) ?'Minor' :'Major';alert('AGE category: '+category);// fees categoryvarisAuthorisedMember=true;varfees;fees=(isAuthorisedMember==true) ?5 :10;alert('fees / charges: '+fees);

    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:

    OperatorsDescriptionExample / Result
    +Concatenationstring1 + string2 (Concatenation of string1 and string2)
    +=Concatenation assignmentstring1 += string2 (Appends the str2 to the str1)

    Syntax & Example:07.07.script.js

    // String Operatorsvarmessage1="Hello";varmessage2=" World!";alert(message1+message2);// Outputs: Hello World!message1+=message2;alert(message1);// Outputs: Hello World!

    07.08. Operator precedence

    • If an expression has more than one operator, theexecution 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
    • The operations inside theparentheses () are computed first
    • If many operations have the same precedence (like addition and subtraction), they arecomputed from left to right

    Syntax & Example:07.08.script.js

    // Operator precedencevarresult1=10+2*5alert('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 ()`varresult2=(10+2)*5;alert('(10 + 2) * 5 =  '+result2);// (12) * 5 = 60// same precedence operatorsvarresult3=10+5-2alert('10 + 5 - 2 =  '+result3);// 13 first addition than subtractionvarresult4=10+(5-2);alert('10 + (5 - 2) =  '+result4);// 13 first subtraction ie. ( ) than addition

    Section 08. Functions

    08.01. What is a Function?

    • A function is basically agroup of statements that perform specific tasks/operations
    • Functions provide a way tocreate reusable code packages which are more portable and easier to debug
    • Functions allow a programmer todivide a big program into a number of/several small and manageable functions
    • It helps programmers in writingmodular codes
    • The function is a kind of reusable tool where we can write code/functionality to reuse whenever we want (Function allow the code to be called many times without repetition)
    • 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 calledMODULES, SUBROUTINES(SUB-ROUTINES)
    • There are two steps to utilize function:
      1. create/define a function withfunction keyword
      2. call/invoke a function

    Note:
    Best Practice - First Define function than call/envoke it!

    08.01.01. Here are some advantages of using functions:

    • Code reusability - call a function several times
    • Less coding - makes our program compact, no need to write lines of code each time
    • Easier to maintain - changes are done only at one location
    • Easier to eliminate the errors - fixing errors becomes much easier

    08.01.02. Function Definition / Function Declaration / Creating Function

    • The function declaration starts by using thefunction keyword,
    • followed by aunique function name,
    • a list ofparameters in parentheses i.e. () (that might be empty),
    • and a statement block surrounded bycurly braces { }

    Syntax & Example:08.01.script.js

    //1. define / declare / create functionfunctionshowMessage(){//Body of function//code to be executedconsole.log('welcome to JavaScript function');alert('welcome to JavaScript function');}

    08.01.03. Function Invocation / Calling a Function / Run a Function

    • Defined function can be invoked/called/run from anywhere in the document, by typingfunction name followed by a set of parentheses, like functionName()

    Syntax & Example:08.01.script.js

    //2. invoke / call the functionshowMessage();

    08.01.04. Function Naming

    Functiondenotes an action/task. The function name should bebrief, as accurate as possible and describe what the function does, like averb.

    Usually, Function name starts with:

    • "getSomething" – returns value,
    • "createSomething" – create something,
    • "calcSomething" – calculate something,
    • "checkSomething" – check something and return a boolean, etc.

    Examples of function names:

    • getSum();
    • createFields();
    • calcAge();
    • checkUserType();

    08.02. Types of Function

    • Regular Function
    • Parameterized Function
    • Return Type Function (Function returning values)

    08.02.01. Regular Function

    • Simple/Normal function which we use daily to perform some action/task

    Syntax & Example:08.02.01.script.js

    varname='Dinanath';//1. define / declare / create functionfunctionsayHello(){//Body of function//code to be executedconsole.log('Hello '+name);alert('Hello '+name);}//2. invoke / call the functionsayHello();

    08.02.02.01. Parameterized Function

    • One can pass data to functions using parameters (function arguments)
    • You can specify parameters when you define your function to accept input values at run time

    Syntax & Example:08.02.02.01.script.js

    // Parameterized function//1. define / declare / create functionfunctionsayHello(name){//Body of function//code to be executedconsole.log('Hello '+name);alert('Hello '+name);}//2. invoke / call the functionsayHello('Dinanath');sayHello('Dino');// ------------------------------vartotal;functioncalculateSum(num1,num2){total=num1+num2;console.log(total);}calculateSum(10,20);calculateSum(100,200);

    08.02.02.02. Default Values for Function Parameters ES6

    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

    // Parameterized function with default parameters//1. define / declare / create functionfunctionsayHello(name='User'){//Body of function//code to be executedconsole.log('Hello '+name);alert('Hello '+name);}//2. invoke / call the functionsayHello();sayHello('Amber');// ------------------------------vartotal;functioncalculateSum(num1=1,num2=2){total=num1+num2;console.log(total);}calculateSum();calculateSum(100,200);

    08.02.03. Return Type Function (Function returning values)

    • A function canreturn a value back to the script that called thefunction, as a result, using the return statement
    • We can call a function that returns a value and use it in our program
    • The return statement usually placed as the last line of the function

    Syntax & Example:08.02.03.script.js

    // Return type function//1. define / declare / create functionfunctiongetSum(num1,num2){//Body of function//code to be executedvarsum=num1+num2;return(sum);}//2. invoke / call the functionconsole.log(getSum(10,20));console.log(getSum(100,200));vartotal=getSum(50,50);alert(total);

    08.03. Different ways to define Function

    The syntax that we've used before to create functions is calledfunction declaration. There is another syntax for creating a function that is called afunction expression andImmediately invoked function expression (IIFE)

    08.03.01. function declaration (Regular/Normal function)

    08.03.02. function expression

    • Variables contain the expressions of a function
      • Anonymous function expression
      • Named function expression

    Syntax & Example:08.03.02.01.script.js

    // function declaration (Regular / normal function)functiongetSum1(num1,num2){vartotal=num1+num2;returntotal;}// ------------------------------// function expression - AnonymusvargetSum2=function(num1,num2){vartotal=num1+num2;returntotal;};alert(getSum2(10,20));// ------------------------------// assign function to another variablevarsum1=getSum2;alert(sum1(100,200));

    Syntax & Example:

    // function expression - namedvargetSum2=functiongetTotal(num1,num2){vartotal=num1+num2;returntotal;};alert(getSum2(10,20));// ------------------------------// assign function to another variablevarsum1=getSum2;alert(sum1(5,10));

    08.03.03. Immediately invoked function expression (IIFE)

    • It runs as soon as the browser finds it
    • Declare and run the function at the same time

    Syntax & Example:08.03.03.script.js

    // Immediately invoked function expression (IIFE)(function(){console.log('Welcome to Immediately invoked function expression (IIFE)');}());(function(userName){console.log('Welcome',userName);})('Dinanath');

    08.04. String Methods and Concatenation

    Syntax & Example:

    constfirstName='Dinanath';constlastName='Jayaswal'constfullName=(firstName)+(lastName);console.log(fullName);console.log(typeoffullName);// concatenationconsole.log(firstName+' '+lastName);console.log('Hello '+firstName+' '+lastName+'Welcome to JavaScript!');// appendletname1='Dinanath ';letname1+='Jayaswal';console.log(name1);// concat() methodconsole.log(firstName.concat(' ',lastName));// lengthconsole.log(firstName.length);// change caseconsole.log(firstName.toLowercase());console.log(firstName.toUppercase());// escaping// let statement1 = 'wait I'm coming, that's good';letstatement1="wait I'm coming, that's good";letstatement2='wait I\'m coming, that\'s good';// string array - get specific character from string like an arrayconsole.log(firstName[0]);// indexOfconsole.log(firstName.indexOf('i'));console.log(firstName.lastIndexOf('a'));// charAt()console.log(firstName.charAt(2));// get last character from stringconsole.log(firstName.charAt(firstName.length-1));// replace();letreplaceString=('Dinanath','DJ');console.log('My name is:',replaceString);// substring();console.log(firstName.substring(0,4));// slice();console.log(firstName.slice(0,4));// slice(); negative number starts from backsideconsole.log(firstName.slice(-2));// includes();letmessage2='Hello Dinanath, welcome to JavaScript';console.log(message2.includes('Hello'));console.log(message2.includes('Hi'));// split()letmessage2='Hello Dinanath, welcome, to JavaScript';console.log(message2.split(','));console.log(message2.split(' '));letcourses='html5, css3, javascript, angular';console.log(courses.split(','));

    08.05. Template String

    08.05. Template Literals

    • ES6 new featureStrings 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

    • Intuitive expression interpolation for single-line and multi-line strings

    • Useback-tick (grave accent) character and{ var name in curly brace }, no + plus sign required

    • The best part of Template Literals (Template Strings) is we canuse 'single' "double" quotes inside

    • It is part of ES6 but compatible with all the modern browsers and its latest versions

    Syntax & Example:

    //old plain javascript approachletuser='Dinanath';letgreetMessage1='Welcome'+' '+user+' '+'to JavaScript.';console.log(greetMessage1);console.log('// ------------------------------');constfirstName='Dinanath';constlastName='Jayaswal'constcourse='JavaScript'constfullName=`Hey${firstName}${lastName} Welcome to${course}.`console.log('// ------------------------------');//ES6 Template Literals (Template Strings) approachletgreetMessage2=`Hello${firstName}, How are you?`;console.log(greetMessage2);console.log('// ------------------------------');// ------------------------------//ES6 multi-line stringletgreetMessage3=`ES6 Template Literals (Template Strings):                    With Template Literals (Template Strings)                    we can add multiple lines in string concatenation/interpolation`;console.log(greetMessage3);letgreetMessage4=ES6TemplateLiterals(TemplateStrings):WithTemplateLiterals(TemplateStrings)wecanaddmultiplelinesinstringconcatenation/interpolation;console.log(greetMessage4);

    Section 09. Loops

    Section 09. Loops and Iterations

    • Loops are used to execute thesame block of code again, with a different value, until a certain condition is met
    • Loops can execute/repeat a block of code (an action) a number of/several times
    • The basic idea behind a loop is toautomate the repetitive tasks within a program to save time and effort
    • It makes thecode compact
    • It is mostly used in array or object (to iterate through series)
    • Loops/iterations is an instruction repeat until a specific condition is reached

    Different Types of Loops in #"Permalink: Different Types of Loops in JavaScript:" href="#different-types-of-loops-in-javascript">

    1. for loop
    2. while loop
    3. do...while loop
    4. for...in loop
    5. for...of loop (ES6)
    6. for...each

    09.01. The for loop

    • TheFor loop is used to run a piece of code aset amount of times
    • Loops through a block of code until thecounter reach a specified number
    • The for looprepeats a block of code until a certain condition is met
    • The for loop is the most simple/compact form of looping
    • For loop consists of 3 statements (), mostlyi = index is used for loop initialization

    Syntax & Example:09.01.01.script.js

    // for loop/* for (statement 1; statement 2; statement 3) {  // Code to be executed} *//* for(variable definition/index/initialization; condition checking; increment/decrement expression) {  // Code to be executed} */for(leti=1;i<=5;i++){alert('Hello, The current index/num is: '+i);document.write('<li>Hello, The current index/num is: '+i+'</li>');console.log('Hello, The current index/num is: '+i);}

    09.01.01. The for loop - Reverse order

    Syntax & Example:09.01.02.script.js

    // for loop - reverse orderfor(leti=5;i>=1;i--){alert('Hello, The current index/num is: '+i);document.write('<li>Hello, The current index/num is: '+i+'</li>');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

    // for loop - to find out odd even numberfor(leti=1;i<=10;i++){if(i%2==0){console.log('The current index/num is EVEN : '+i);}/* else {    console.log('The current index/num is ODD : ' + i);  } */}

    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

    // while loop/*while(condition) {  // Code to be executed}*/leti=1;while(i<=5){alert('Hello, The current index/num is: '+i);document.write('<li>Hello, The current index/num is: '+i+'</li>');console.log('Hello, The current index/num is: '+i);i++;}

    09.03. The do while loop

    09.03. The do...while loop

    • The do...while loop is similar to the while loop except that thecondition check happens at the end of the loop
    • The do...while loop will always beexecuted at least once (before checking if the condition is true), even if the condition is false

    Syntax & Example:09.03.01.script.js

    // do...while loop/*do {    // Code to be executed}while(condition);*/leti=1;do{alert('Hello, The current index/num is: '+i);document.write('<li>Hello, The current index/num is: '+i+'</li>');console.log('Hello, The current index/num is: '+i);i++;}while(i<=5);

    09.04. The for in loop

    09.04. The for...in loop

    • The for-in loop is a special type of a loop thatiterates 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

    // for...in loop/*for(variable/key in array/object) {    // Code to be executed}*/// An array with some elementsletarrColors=["Red","Green","Blue","Cyan","Magenta","Yellow","Black"];// Loop through all the elements in the arrayfor(letcolorinarrColors){alert('Color is: '+arrColors[color]);document.write('<li>Color is: '+arrColors[color]+'</li>');console.log('Color is: '+arrColors[color]);}

    09.04.02. The for...in Loop - object

    Syntax & Example:09.04.02.script.js

    // for...in loop/*for(variable/key in array/object) {    // Code to be executed}*/// An object with some propertiesletobjEmployee={'emp_name':'Dinanath','emp_addres':'Mumbai','emp_id':'029','emp_age':35};// Loop through all the properties in the objectfor(empinobjEmployee){alert('Employee '+emp+' is: '+objEmployee[emp]);document.write('<li>Employee '+emp+' is: '+objEmployee[emp]+'</li>');console.log('Employee '+emp+' is: '+objEmployee[emp]);}

    09.04.03. The for...in Loop - Inbuilt JavaScript objects

    Syntax & Example:09.04.03.script.js

    // for...in loop/*for(variable/key in array/object) {    // Code to be executed}*/// Loop through all the properties in the inbuilt object - window, document, navigatorfor(propsinwindow){// alert('document object properties ' + props);document.write('<li>document object properties '+props+'</li>');console.log('document object properties '+props);}

    09.05. The for of loop

    09.05. The for...of loop (ES6)

    • Loops overiterable 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

    // for...of loop/*for(element in array/string) {  // Code to be executed} */// Iterating over an arrayletarrDays=["Monday","TuesDay","Wednesday","Thursday","Friday","Saturday","Sunday"];for(letdayofarrDays){console.log(day);document.write('<li>'+day+'</li>');}// Iterating over stringletname='JavaScript';for(letletterofname){document.write(letter+',');console.log(letter+',');}

    09.06. Break and Continue statement

    • break andcontinue keywords/statement can changehow the loop behaves
    • break andcontinue keywords can be used in all loops to stop or continue the loop
    • Thebreak statement is used to exit a loop early, to "jump out" of a loop, stops executing/running a loop
    • Thecontinue 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

    // break continue statement/* break */letarrDays=["Monday","TuesDay","Wednesday","Thursday","Friday","Saturday","Sunday"];leti=1;while(i<=10){if(i==5){break;}console.log(i);i++}console.log('// ------------------------------');for(leti=0;i<=arrDays.length;i++){if(i==3){break;}console.log(arrDays[i]);}console.log('// ------------------------------');/* continue */i=1;while(i<=20){if(i%2==0){// console.log('Even Number ', i);i++;continue;// skip rest of the loop bodyi+100;// non of useconsole.log('just in even num continue');// non of use}console.log('Odd Number ',i);i++;}console.log('// ------------------------------');for(i=1;i<=10;i++){if(i===5){continue;// skip rest of the loop bodyconsole.log('just after 5 continue...');// non of use}console.log(i);}console.log('// ------------------------------');for(letint=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');break;}console.log('current Number is:',int);}

    09.07. for each loop

    09.07. for...each loop

    Syntax & Example: ``

    letarrDays=["Monday","TuesDay","Wednesday","Thursday","Friday","Saturday","Sunday"];arrDays.forEach(function(day)){console.log(day);}

    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
    • It helps to perform different actions for different decisions
    • We can use conditional operator to check our condition: >, <, >=, <=, ==, !=, ===

    We can use the following conditional statements in JavaScript to make decisions:

    1. If Statement
    2. If...else Statement
    3. If...else if...else Statement
    4. Switch...Case Statement

    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 codeonly if the specified condition evaluates to true
    • It evaluates the content onlyif an expression is true

    If conditional statements are used to evaluate some kind of condition and do something/perform some actions based on the result

    Note:
    Useif to specify a block of code to be executed,if a specified condition is true

    Syntax & Example:10.01.01.script.js

    // if conditional statement/*if(condition/expression) {  // Code to be executed if condition/expression is true}*/letuser='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+'!');}// ------------------------------letage=20;if(age>=18){console.log('MAJOR! Eligible for Voting');window.alert('MAJOR! Eligible for Voting');}// ------------------------------letcurrentHours=10;if(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

    • The JavaScriptif...else statement is used to execute the codeweather condition is true or false
    • The developer can enhance the decision-making capabilities by providing an alternative choice through adding anelse statement to theif statement
    • The condition can be any expression that evaluates to true or false
    • If the condition evaluates to true, statements_1 are executed; otherwise, statements_2 are executed

    Note:
    Useelse to specify a block of code to be executed,if the same condition is false

    Syntax & Example:10.02.01.script.js

    // if...else conditional statement/*if(condition/expression){// content to be executed if condition is true - statements_1}else{// content to be executed if condition is false - statements_2}*/letuser='Ambar';if(user=='Dinanath'){console.log('Welcome Dinanath!');window.alert('Welcome Dinanath!');}else{console.log('Welcome Guest!');window.alert('Welcome Guest!');}// ------------------------------letage=15;if(age>=18){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');}// ------------------------------letcurrentHours=10;if(currentHours<12){console.log('Good Morning!');window.alert('Good Morning!');}else{console.log('Good Evening!');window.alert('Good Evening!');}

    10.03. The if else if else statement

    10.03. The if...else, if...else statement

    • Theif...else if...else a special statement that is used tocombine multiple if...else statements
    • It is an advanced form of if...else that allows us tomake a correct decision out of several conditions

    Note:
    Useelse if to specify a new condition to test,if the first condition is false

    Syntax & Example:10.03.01.script.js

    // If...else if...else conditional statement/*if(condition/expression 1) {    // Code to be executed if condition1 is true statements_1} else if(condition/expression 2) {    // Code to be executed if the condition1 is false and condition2 is true statements_2} else {    // Code to be executed if both condition1 and condition2 are false statements_3}*/letnum1=200;letnum2=100;if(num1==num2){console.log('Both numbers are equal');}elseif(num1<num2){console.log('Number2 is greater!');}else{console.log('Number1 is greater!');}// ------------------------------letage=15;if(age>=60){console.log('SINIOR CIRIZEN!');}elseif(age<18){console.log('MINOR!');}else{console.log('MAJOR - Middle Age!');}// ------------------------------letcurrentHours=15;if(currentHours>=6&&currentHours<12){console.log('Good Morning!');window.alert('Good Morning!');}elseif(currentHours>12&&currentHours<=18){console.log('Good AfterNoon!');window.alert('Good AfterNoon!');}else{console.log('Good Evening!');window.alert('Good Evening!');}

    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 thecase and thevalue of condition and if the case matches, the subsequent block is executed and if none of the case matchesdefault block is executed
    • The JavaScript switch statement is used to execute one code from multiple blocks of expressions

    Note:
    Useswitch to specify manyalternative blocks of code to be executed

    Syntax & Example:10.04.01.script.js

    // switch...case conditional statement/* switch(variable/expression){  case value1:    // Code to be executed if variable/expression === value1    break;  case value2:    // Code to be executed if variable/expression === value2    break;  default:    // Code to be executed if variable/expression is different from all values} */letgrade='B';// A.B,C, or somethingswitch(grade){case'A':console.log('Great Job! - A Grade');break;case'B':console.log('Good! - B Grade');break;case'C':console.log('Congratulations! - Passed');break;default:console.log('Sorry! - Failed...Keep trying!');break;}// ------------------------------letsweets='';//cake, chocolates, biscuitsswitch(sweets){case'chocolates':console.log('Chubby Chocolates!');break;case'cake':console.log('Happy BirthDay Cake!');break;case'biscuits':console.log('Enjoy Biscuits!');break;default:console.log('No Sweets! Try some other sweets!');break;}// ------------------------------constcolor='red';switch(color){case'red':console.log('The Dark RED');break;case'green':console.log('Go Green');break;case'blue':console.log('Boys are Blue');break;case'yellow':console.log('Golden Yellow');break;default:console.log('Its some other Color, Enter correct color');break;}// ------------------------------letcurrentDate=newDate();letcurrentDay;switch(currentDate.getDay()){case0:currentDay='Sunday';break;case1:currentDay='Monday';break;case2:currentDay='Tuesday';break;case3:currentDay='Wednesday';break;case4:currentDay='Thursday';break;case5:currentDay='Friday';break;case6:currentDay='Saturday';break;}console.log(`Today is${currentDay}!`);

    Section 11. Array

    11.01. What is an Array?

    • An Array is a special type of variable/object whichconsists 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
    • Arrays are defined withsquare brackets [ ] and withnew keyword
    • Array items are normally separated withcommas,
    • Arrays arezero-indexed i.e. the first element of an array is at index/position 0
    • An array isordered collection, where we have a 0th, 1st, a 2nd, and so on elements
    • Each value (anelement) in an array has anumeric position, known as itsindex,starts from 0, so that the first array element position/index isarr[0] not arr[1]

    Different ways to create/define an Array

    There are 3 main ways to construct an array:

    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

    • The simplest way to create an array in JavaScript is enclosing acomma-separated list of values in square brackets [ ]
    • var myArray = [element0, element1, ..., elementN];

    Syntax & Example:11.02.01.script.js

    // create array with array literal ie. [] square bracket// var myArray = [element0, element1, ..., elementN];vararrColors=['Red','Green','Blue','Orange'];console.log(arrColors);// show all elements// ------------------------------vararrCities=['Delhi','Mumbai','Kolkota','Bengaluru','Chennai'];console.log(arrCities[1]);// show 1st index ie. 2nd positioned element// ------------------------------vararrTechnologies=[];arrTechnologies[0]='Java';arrTechnologies[1]='Python';arrTechnologies[2]='C';console.log(arrTechnologies);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 (usingnew keyword)

    • Array instance can be created using thenew keywordnew Array()
    • var myArray = new Array(); OR var myArray = Array();

    Syntax & Example:11.03.01.script.js

    // create array with new keyword// var myArray = new Array();vararrColors=newArray();arrColors[0]='Red'arrColors[1]='Green'arrColors[2]='Blue'arrColors[3]='Orange'console.log(arrColors);// show all elements// read/get array items/elementsfor(leti=0;i<arrColors.length;i++){alert(arrColors[i]);}// ------------------------------vararrCities=Array();arrCities[0]='Delhi';arrCities[1]='Mumbai';arrCities[2]='DeKolkotalhi';arrCities[3]='Bengaluru';arrCities[4]='Chennai';console.log(arrCities);// show all elements// ------------------------------vararrTechnologies=newArray();// add new array items/elementsfor(leti=0;i<=5;i++){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 (usingnew keyword)

    • Array instance can be created using thenew keywordnew 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

    // create array with new keyword Array constructor passing parameter// var myArray = new Array(element0, element1, ..., elementN);vararrColors=newArray('Red','Green','Blue','Orange');console.log(arrColors);// show all elements// ------------------------------vararrCities=newArray('Delhi','Mumbai','Kolkota','Bengaluru','Chennai');console.log(arrCities);// show all elements// ------------------------------vararrJsFrameworks=newArray('jQuery','Angular','React','Node','Vue','Express','D3');console.log(arrJsFrameworks);// show all elements

    11.05. Getting the Length of an Array

    • Thelength property returns thelength of an array,total number of elements in an array
    • length property brings back anarray length - the fixed amount of items stored in the array
    • The array length is always greater than the index of any of its element(Array length = last array index + 1)
    • The maximum length allowed for an array is4,294,967,295
    • myarray.length

    Syntax & Example:11.05.01.script.js

    // get/retrieve/find array length// myarray.lengthvararrColors=newArray('Red','Green','Blue','Orange');console.log(arrColors.length);// ------------------------------vararrCities=newArray('Delhi','Mumbai','Kolkota','Bengaluru','Chennai');console.log(arrCities.length);// ------------------------------vararrJsFrameworks=newArray('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

    • Array elements can be accessed by theirindex using the square bracket notation ie. [index]
    • Arrays arezero-indexed i.e. the first element of an array is at index/position 0
    • An array isordered collection, where we have a 0th, 1st, a 2nd, and so on elements
    • Each value (anelement) in an array has anumeric position, known as itsindex,starts from 0, so that the first array element isarr[0] not arr[1]
    • One can usefor loop in coordination with arraylength property to access each element of an array in sequential order
    • myarray[indexNumber], myarray[0] // get first array element

    Syntax & Example:11.06.01.script.js

    // access/loop through array element// myarray[indexNumber], myarray[0]vararrColors=newArray('Red','Green','Blue','Orange');console.log(arrColors[0]);// Redconsole.log(arrColors[2]);// Blue// ------------------------------vararrCities=newArray('Delhi','Mumbai','Kolkota','Bengaluru','Chennai');console.log(arrCities[1]);// Mumbaiconsole.log(arrCities[4]);// Chennai// ------------------------------vararrJsFrameworks=newArray('jQuery','Angular','React','Node','Vue','Express','D3');console.log(arrJsFrameworks[3]);// Nodeconsole.log(arrJsFrameworks[5]);// Express// Loop through an Array Elementsfor(leti=0;i<arrJsFrameworks.length;i++){document.write('<li>'+arrJsFrameworks[i]+'</li>');}

    11.07. Adding Editing an Array Elements

    • One can add/edit an array element by simply specifyingarray[index] and value ie.myarray[5]='value'
    • If arrayindex exists it will simply edit the old value and update the array else it will add an element to the array
    • push() method add a new element at theend of an array
    • unshift() method add a new element at thebeginning of an array
    • myarray[indexNumber]='value', myarray[2]='value', myarray.push('value'), myarray.unshift('value')

    Syntax & Example:11.07.01.script.js

    // add/edit array element// myarray[indexNumber]='value', myarray[2]='value', myarray.push('value'), myarray.unshift('value')vararrColors=newArray('Red','Green','Blue','Orange');console.log(arrColors);console.log('arrColors.length: '+arrColors.length);// add an element at the end of the arrayarrColors.push('Cyan');console.log(arrColors);console.log('arrColors.length: '+arrColors.length);// add multiple elements at the end of the arrayarrColors.push('Magenta','Yellow');console.log(arrColors);console.log('arrColors.length: '+arrColors.length);// ------------------------------// add multiple elements at the start of the arrayarrColors.unshift('Black','White');console.log(arrColors);console.log('arrColors.length: '+arrColors.length);// ------------------------------// edit 1st index ie. 'white' to 'pink'arrColors[1]='pink';console.log(arrColors);console.log('arrColors.length: '+arrColors.length);

    11.08. Removing Deleting an Array Elements

    • pop() methodremove the last element from an array
    • shift() method remove thefirst element from an array
    • myarray.pop(), myarray.shift()

    Note:
    Thepush() 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

    // remove array element from start and end// myarray.pop(), myarray.shift()vararrColors=newArray('Red','Green','Blue','Orange');console.log(arrColors);console.log('arrColors.length: '+arrColors.length);// remove an element from the end of the arrayarrColors.pop();console.log(arrColors);console.log('arrColors.length: '+arrColors.length);// ------------------------------// remove an element from the start of the arrayletstartElement=arrColors.shift();console.log(startElement);console.log(arrColors);console.log('arrColors.length: '+arrColors.length);

    11.09. Array properties and methods

    Syntax & Example: ``

    // lengthvararrColors=newArray('Red','Green','Blue','Orange');console.log(arrColors.length);// isArray() - check if array (check the type of variable is array)vararrCities=newArray('Delhi','Mumbai','Kolkota','Bengaluru','Chennai');console.log(Array.isArray(arrCities));console.log(Array.isArray('I am Dinanath'));// indexOf() - get index/location of provided valuevararrJsFrameworks=newArray('jQuery','Angular','React','Node','Vue','Express','D3');console.log(arrJsFrameworks.indexOf('React'));// splice valuesconsole.log(arrJsFrameworks.splice(1,3)));// reverse arrayconsole.log(arrJsFrameworks.reverse()));// concatenate arrayletnewArray=arrColors.concat(arrCities);// sortletnewSortedColorsArray=arrColors.sort();console.log(newSortedColorsArray);console.log(numberArray.sort());/* exact ascending sortlet sortedValues = numberArray.sort(function(num1,num2){  return num1 - num2;})*//* exact descending sortlet sortedValues = numberArray.sort(function(num1,num2){  return num2 - num1;})*/// findconsole.log(numberArray.find(40));

    Section 12. Objects

    12.01. Real Life Objects

    12.01. Object Properties and Method examples

    • In real life almosteverything 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:
    ObjectPropertiesMethods
    PersonPerson.name = 'dinanath';
    Person.weight = 65;
    Person.color = 'fair'
    Person.walk();
    Person.talk();
    Person.eat();
    BikeBike.brand = 'bajaj';
    Bike.model = 'discover';
    Bike.color = 'blue';
    Bike.length = 60;
    Bike.height = 30;
    Bike.start();
    Bike.break();
    Bike.stop();
    WatchWatch.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

    12.02. What is an Object?

    12.02. What are the Objects?

    • JavaScript is anobject-based language and in JavaScript, almost everything is an object or acts like/as an object
    • An object is aspecial/complex data type that allows you tostore collections of data
    • An object is a kind of container/declaration where we can group variousdata, properties, and behaviors under one roof (group related variables)
    • A JavaScript object is just a collection ofnamed values referred to as properties of the object
    • Objects are defined withcurly braces { }, the properties of an object are written in pairs (propertyName: value)
    • An object contains properties, defined as akey-value pair (Objects are a collection ofkey-value pair)
    • A propertykey (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
      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
    2. By creating aninstance of Object directly (usingnew keyword)
    3. By using anObject constructor (usingnew keyword)

    12.03. Object literal

    • The simplest way to create an object in JavaScript is enclosing acomma-separated list of properties:values and methods in curly braces { }
    • var MyObject = { property1: value1, property2: value2.....propertyN: valueN }

    Syntax & Example:

    // create object with object literal// var MyObject = { property1: value1, property2: value2.....propertyN: valueN }// empty objectvarHumanObj={};console.log(HumanObj);console.log('// ------------------------------');// object with propertiesvarTechnologyObj={'name':'JavaScript','version':6,'type':'script','isStable':true}console.log(TechnologyObj.name);console.log(TechnologyObj['isStable']);console.log('// ------------------------------');// object properly alignment/arranged for readability - with quotesvarVehicleObj1={'type':'LWM','brand':'Maruti','model':'Alto-100','color':'White','isHighEndModel':true,'price':400000,keyStart:function(){console.log(this.model+' started!');}}console.log(VehicleObj1.brand);console.log(VehicleObj1['color']);VehicleObj1.keyStart();console.log('// ------------------------------');// object properly alignment/arranged for readability - with quotesvarVehicleObj2={type:'LWM',brand:'Maruti',model:'Alto-100',color:'White',isHighEndModel:true,price:400000,keyStart:function(){alert(this.model+'started!');}}console.log(VehicleObj1.brand);console.log(VehicleObj1['color']);VehicleObj1.keyStart();console.log('// ------------------------------');

    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 thenew keywordnew Array() with or without passing arguments/properties-methods in constructor
    • var MyObject = new Object(); OR var MyObject = Object();

    Syntax & Example:

    // create object with new keyword// var MyObject = new Object(); OR var MyObject = Object();// object with propertiesvarTechnologyObj=newObject();TechnologyObj.name='JavaScript';TechnologyObj.version=6;TechnologyObj.type='script';TechnologyObj.isStable=trueconsole.log(TechnologyObj.name);console.log(TechnologyObj['type']);console.log('// ------------------------------');// object properly alignment/arranged for readability - with quotesvarVehicleObj1={'type':'LWM','brand':'Maruti','model':'Alto-100','color':'red','isHighEndModel':true,'price':400000,keyStart:function(){console.log(this.model+' started!');}}// access property with .DOT notationconsole.log(VehicleObj1.brand);// access property with []Bracket notationconsole.log(VehicleObj1['color']);VehicleObj1.keyStart();console.log('// ------------------------------');// object properly alignment/arranged for readability - without quotesvarVehicleObj2={type:'LWM',brand:'Tata',model:'Safari',color:'White',isHighEndModel:false,price:1400000,keyStart:function(){alert(this.model+'started!');}}// access property with .DOT notationconsole.log(VehicleObj2.brand);// access property with []Bracket notationconsole.log(VehicleObj2['color']);VehicleObj1.keyStart();console.log('// ------------------------------');

    12.05. Object constructor

    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 usingthis keyword,this keyword refers to thecurrent object

    Syntax & Example:

    // create an object with new keyword - Object constructor with functionfunctionTechnology(name,version,type){this.name=name;this.version=version;this.type=type;console.log(this.name);console.log(this.type);}letJavaScript=newTechnology('JavaScript',6,'Script Language');console.log(JavaScript.version);console.log('// ------------------------------');functionVehicle(brand,model,color,price){this.brand=brand;this.model=model;this.color=color;this.price=price;this.keyStart=function(){console.log(this.model+' started!');}}varMaruti=newVehicle('Maruti','Alto-100','White',400000);Maruti.keyStart();console.log('// ------------------------------');

    12.06. Accessing objects properties

    12.06. Looping through Objects properties

    • To access or get the value of a property, you can use thedot ., orsquare bracket [] notation
    • We can iterate through thekey-value pairs of an object using thefor...in loop
    • MyObject.propertyName; OR MyObject[propertyName]; OR MyObject['propertyName']

    Syntax & Example:

    // access/loop thourgh array element// MyObject.propertyName; OR MyObject[propertyName]; OR MyObject['propertyName']varPerson={name:'Dinanath',domain:'IT/Software',gender:'Male',city:'Mumbai',country:'India'}console.log(Person.name);console.log(Person['domain']);console.log('// ------------------------------');// Loop through an Array Elementsfor(propsinPerson){console.log(Person[props])}console.log('// ------------------------------');

    12.07. Removing Deleting objects properties

    • Thedelete operator can be used to completely remove properties from an object
    • delete MyObject.propertyName;

    Note:
    Thedelete operator only removes anobject property or array element. It does not work/does not affect variables or declared functions.

    Syntax & Example:

    // remove/delete Object's Properties// delete MyObject.propertyName;varPerson={name:'Dinanath',domain:'IT/Software',gender:'Male',city:'Mumbai',country:'India'}deletePerson.nameconsole.log(Person);console.log(Person.name);console.log(Person['domain']);

    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)

    2. Reference Types (Objects)

    1. Object
    2. Function
    3. Array

    Syntax & Example:

    ???

    12.09. The Window object

    • Window Object the global variable/global objectavailable in the browser environment, represents the browser window in which the script is running
    • Simply, the window objectrepresents a window in a browser
    • The Window interface represents a window containing a DOM (Document Object Model)
    • Window is the object of browser (The Browser Object Model (BOM)), it is not the object of javascript
    • The Browser Object Model (BOM) allows JavaScript to "communicate/talk to" the browser
    • InBrowser -> Inspect Element -> Console Panel -> TypeWindow, check different properties and methods available

    Syntax & Example:

    // Methodswindow.console.log('Console! Hello, Welcome to JavaScript');window.alert('Alert! Hello, Welcome to JavaScript');// const namePrompt = window.prompt();constnamePrompt=window.prompt('Enter Your Name');window.alert(namePrompt);if(window.confirm('Are you sure?')){window.console.log('YES - selected');}else{window.console.log('NO - clicked');}// Properties// full/complete browser window height & widthouterHeight=window.outerHeight;outerWidth=window.outerWidth;console.log('outerHeight -',outerHeight,'::','outerWidth -',outerWidth);// document/page height & widthinnerHeight=window.innerHeight;innerWidth=window.innerWidth;console.log('innerHeight -',innerHeight,'::','innerWidth -',innerWidth);// scroll positionconsole.log('scrollY',window.scrollY);console.log('scrollX',window.scrollX);// locationconsole.log('current window location/url',window.location);console.log('current window location/url',window.location.href);// location redirectwindow.location.href='https://www.google.com';// window location/visited historywindow.history.go(-1);lettotalPagesVisitedHistory=window.history.length;// current browser details - navigatorletcurBrowser=window.navigator.appName;//window.navigator.userAgent;window.navigator.platform;window.navigator.vendor;

    12.10. The Math Object

    • The Math object allows to perform mathematical tasks
    • Math object provides several constants and methods to perform mathematical operation (likemin, max, sqrt, pi, round, random, etc)

    Syntax & Example:

    letpieValue=Math.PI;console.log(Math.E);console.log(Math.round(2.6));console.log(Math.ceil(2.6));console.log(Math.floor(2.6));console.log(Math.sqrt(64));console.log(Math.abs(-10));//return absolute ie positive numberconsole.log(Math.pow(8,2));//64console.log(Math.pow(10,3));//10 * 10 * 10 = 1000console.log(Math.min(20,5,9,15,2));console.log(Math.max(20,5,9,15,2));console.log(Math.random());console.log(Math.random()*20+1);// random number till 20console.log(Math.floor(Math.random()*20+1));// random number till 20 without any decimals

    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 withnew 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:

    consttoday=newDate();console.log('today is:',today);constdate1=newDate('March 29 1980');constdate2=newDate('09-10-1980');letcurrentDate=newDate();constcurrentDateToday=currentDate.getDate();constcurrentDayToday=currentDate.getDay();constcurrentMonth=currentDate.getMonth();constcurrentYear=currentDate.getYear();constcurrentHours=currentDate.getHours();constcurrentMinutes=currentDate.getMinutes();constnewBirthDate=currentDate.setMonth(5);console.log(newBirthDate);

    Section 13. Events

    13.01. Understanding Events and Event Handlers

    • Events are happening/triggering all over, Event lets the developer knowsomething 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 JavaScriptevent 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 youlisten for it and supply acallback function or event handler which will be called by the browser when the event occurs

    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
    4. Document/Window events

    13.02.01. Mouse events

    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 themouse clicks on an element, links, buttons etc. on a web page
    • contextmenu (oncontextmenu event handler)
      • Occurs when auser clicks the right mouse button on an element to open a context menu
    • 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:

    <olclass="normalList"><li><strong>click</strong> (`onclick` event handler)<br/><spanonclick="alert('You have clicked an element!')"style="color:blue;cursor: pointer;">Occurs When the `mouse clicks on an element`, links, buttons etc. on a web page</span></li><li><strong>contextmenu</strong> (`oncontextmenu` event handler)<br/><spanoncontextmenu="alert('You have Right clicked on Me!')"style="color:blue;cursor: pointer;">Occurs when a `user clicks the right mouse button` on an element to open a context menu</span></li><li><strong>mouseover / mouseout</strong> (`onmouseover` &  `onmouseout` event handler)<br/><spanonmouseover="console.log('You have Mouse Over Me!')"onmouseout="console.log('You have Mouse Out Me!')"style="color:blue;cursor: pointer;">Occurs when the mouse pointer/cursor comes over / leaves (goes outside of) an element</span></li><li><strong>mousedown / mouseup</strong> (`onclick/onmousedown` & `onmouseup`)<br/><spanonmousedown="console.log('You have clicked on Me!')"onmouseup="console.log('You have released click on Me!')"style="color:blue;cursor: pointer;">Occurs when the mouse button is pressed / released over an element</span></li><li><strong>mousemove</strong> (`onmousemove` event handler)<br/><spanonmousemove="console.log('You Moved mouse over Me!')"style="color:blue;cursor: pointer;">Occurs when the mouse pointer/cursor is moved</span></li></ol>

    Syntax & Example:Change background color on mouse movement

    constbutton=document.querySelector('.some-button');constheadingText=document.querySelector('h1');button.addEventListener('mousemove',someFunction);functionsomeFunction(evt){console.log('Event Details:',evt);headingText.innerText='Changed after click!';document.body.style.backgroundColor=`rgb(${evt.offsetX},${evt.offsetY},40)`}

    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:

    • keydown / keyup (onkeydown &onkeyup event handler)
      • Occurs when the user presses down a key and then releases the button/a key on the keyboard
    • keypress (onkeypress event handler)
      • 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:

    <label>Enter Name:</label><inputtype="text"placeholder="Enter Name"onkeydown="console.log('onkeydown pressed a key inside input text!')"onkeyup="console.log('onkeyup released a key inside input text!')"onkeypress="console.log('onkeypress Other than Ctrl, Shift, Alt, Esc, Arrow keys pressed!')"/>

    Syntax & Example:

    constnameText=document.querySelector('inputNameText');nameText.addEventListener('keypress',nameData);functionnameData(evt){console.log('nameData function called');headingText.innerText=evt.target.value;}

    13.02.03. Form events

    A form event is triggered when a form control/form fields (text fields/radio buttons/checkbox) receives or loses focus or when the user modifies a form control value by typing text in a text input, select an option in a dropdown/select box, etc. Let us look into some of the most important form events and their event handler:

    • focus (onfocus event handler)
      • Occurs when the user focuses on an element on a web page, e.g. on aninput text field
    • blur (onblur event handler)
      • Occurs when the user takes the focus away from a form element or a window
    • change (onchange event handler)
      • Occurs when the user changes the value of a form element/fields
    • submit (onsubmit event handler)
      • Occurs only when the user submits a form on a web page

    Syntax & Example:

    <formaction=""method="post"onsubmit="alert('Form data submitted to the server!');"><label>First Name:</label><inputtype="text"name="first-name"onfocus="showHighlight(this)"onblur="resetHighlight(this)"required><br/><br/><selectonchange="console.log('You have selected something!');"><option>Select</option><option>Male</option><option>Female</option></select><br/><br/><inputtype="submit"value="Submit"></form><script>// focus text fieldfunctionshowHighlight(curTxtField){curTxtField.style.background="pink";}functionresetHighlight(curTxtField){curTxtField.style.background="white";}</script>

    Syntax & Example:Form submit event

    constpersonalDataForm=document.querySelector('form');personalDataForm.addEventListener('submit',submitData);functionsubmitData(evt){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

    Events are happening/triggering all over. Events do trigger even when the page has loaded/unloaded or the user resizes the browser window. Mentioned here some of the most important document/window events and their event handler:

    • DOMContentLoaded (DOMContentLoaded event handler)
      • Occurs when the HTML is loaded and processed, DOM is fully built
    • load (onload event handler)
      • Occurs when web page has finished loading in the web browser
    • unload (onunload event handler)
      • Occurs when a user leaves the current web page
    • resize (onresize event handler)
      • 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:

    <bodyonload="window.alert('Page loaded successfully!');"onunload="window.alert('sure you want to leave this page?');"><script>// resize windowwindow.onresize=resizeWindowSize;functionresizeWindowSize(){console.log('window.outerWidth '+window.outerWidth);console.log('window.outerHeight '+window.outerHeight);}</script>

    13.03. Different ways to write the event handler

    1. HTML Attribute
    2. DOM element properties (anonymous function)
    3. Registering event listeners (Professional Method (add and remove listeners))

    13.03.01. HTML attribute

    Syntax & Example:

    <h2onclick="window.alert('HTML attribute onclick used here!')"style="color:#0000ff; cursor:pointer">    13.03.01. HTML attribute | Click Me!</h2><buttononclick="alert('Hello world! Welcome to JavaScript Events!!')">Clickhere...</button><buttononclick="fnShowMessage()">Invoke Function</button>// event handler functionfunctionfnShowMessage(){console.log('Welcome to fnShowMessage event handler!');alert('Welcome to fnShowMessage event handler!');}

    Note:
    This way should be avoided as it makes markup less readable and making it harder to find if there is any bug.

    13.03.02. DOM element properties

    Syntax & Example:

    <buttonid="messageButton1">Click here...</button><buttonid="messageButton2">Clickhere...</button>// DOM element properties// method - 1messageButton1.onclick=function(){console.log('Welcome to event handler!');alert('Welcome to event handler!');}// method - 2document.getElementById("messageButton2").onclick=fnShowMessage;functionfnShowMessage(){alert('Hello World! Welcome to JavaScript events');}

    13.03.03. Registering event listeners

    Syntax & Example:

    // myButton.addEventListener('click', someFunc, false);document.querySelector('.clear-button').addEventLister('click',function(){console.log('clear-button clicked');})

    Note:
    This method is preferred in modern web pages. IE 6-8 do not support this method, there is an alternate for theaddEventListener isattachEvent (myButton.attachEvent (‘onclick', someFunc);)

    Syntax & Example:

    ???

    13.03.04. Event Bubbling Delegation

    • Event Bubbling = bubbling up the event from bottom to top ie from child to parent element
    • Event Delegation = Event Delegation is exactly the opposite of Event Bubbling. It simply means event passed from top to bottom ie from parent to child element
    // create an example of nested element???

    Section 14. DOM (Document Object Model)

    14.01. What is DOM?

    14.01. What is the Document Object Model?

    • DOM represents the whole HTML document, DOM is a structure of HTML web page where all tags are defined in a structured/structural way
    • The Document Object Model (DOM) is the model that describes how all elements in an HTML page (like input fields, images, paragraphs, headings, etc.), are related to the topmost structure: the document itself
    • DOM defines the logical structure of the documents and how they can be accessed and manipulated
    • DOM is a W3C (World Wide Web Consortium) standard which defines a standard for accessing documents like programmers can build documents, navigate their structure, and add, modify, or delete elements and content
    • In DOM world always think in form/terms ofNodes (elements, its attributes, text, etc.)
    • Structural representation of HTML document (Tree of nodes/elements/tags)

    14.02. Node

    As we learned above, in DOM, all parts of the document (like elements, its attributes, text, etc.) are organized in a hierarchical tree-like structure; similar to a real-life family tree that consists of parents and children. In DOM terminology these individual parts of the document are known asnodes.

    There are different types of nodes like:Elements, Attribute & Text Node.

    Syntax & Example:

    <ulid="list"> --> Element & Attribute NODE<li>first item</li> --> text NODE</ul>* Elements NODES does not contain text

    Syntax & Example:In Browser Window -> Inspect Element (Developer Tools) -> Console: type following and check the output thoroughly

    • document - outputs the entire document/current page

    • document.all - shows HTMLAllCollection(1532) [html, head, meta (html tags)

    • document.url - displays current url/path

    HTMLAllCollection(1532) [html, head, meta, link, link, link, link, link, link, link, link, link, meta, title, meta, link, link, meta, meta, meta, meta, meta, meta, meta, meta, meta,

    14.03. JavaScript DOM Selectors

    JavaScript is commonly used to find or select, to get or modify the content/value of the HTML elements on the page, and as well as to apply some effects (like show, hide, add events, animate, etc.)

    DOM selectors are nothing but methods which helps to pull/traverse/navigate things (elements, nodes)f from the document and do some operations on the same.

    Let's learn some of the common ways of selecting the elements on a page and do something using JavaScript.

    14.03.01. Selecting Elements by ID (getElementById())

    • One can select an element based on itsunique ID with thegetElementById() method
    • getElementById() is the easiest and most common way to find/access an HTML element in the DOM tree
    • getElementById() method returns the element having the given id value

    Syntax & Example:

    // Selecting element with idletmainHeadingElement=document.getElementById('mainHeadingText');// get html of selected elementletmainHeadingHtml=mainHeadingElement.innerHTML;// get text of selected elementletmainHeadingText=mainHeadingElement.innerText;alert('mainHeadingHtml: '+mainHeadingHtml);// text with complete html tagsalert('mainHeadingText: '+mainHeadingText);// only text// console.log('// ------------------------------');// set text of selected elementmainHeadingElement.innerHTML='This text changed with DOM method...';// console.log('// ------------------------------');// set text of another elementletsubHeadingElement=document.getElementById('subHeadingText');subHeadingElement.innerHTML=mainHeadingElement.innerHTML;// console.log('// ------------------------------');// set css stylemainHeadingElement.style.backgroundColor='pink';

    14.03.02. Selecting Elements by Class Name (getElementsByClassName())

    • getElementsByClassName() method is used to select all theelements having specific class names
    • getElementsByClassName() methodreturns an array of all elements with given class names

    Syntax & Example:

    // Selecting elements with classletlistItems=document.getElementsByClassName("list-item");console.log(listItems);// get text of 1st ie 0th elementletfirstListItemText=listItems[0].innerHTML;console.log('firstListItemText: '+firstListItemText);// console.log('// ------------------------------');// set text of last elementletlastListItem=(listItems.length-1);listItems[lastListItem].style.color='blue';// console.log('// ------------------------------');// highlighting all list items through loopfor(varlistIteminlistItems){listItems[listItem].style.marginBottom='10px';listItems[listItem].style.background='#bbbbbb';}

    14.03.03. Selecting Elements by Tag Name (getElementsByTagName())

    • Developer can alsoselect HTML elements by tag name using thegetElementsByTagName() method
    • getElementsByTagName() methodreturns an array of all elements with given tag name

    Syntax & Example:

    // Selecting all LI elements with tag nameletliElements=document.getElementsByTagName('li');console.log(liElements);// console.log('// ------------------------------');// get total li tags/elements in pagelettotalLiElements=liElements.length;console.log(totalLiElements);// console.log('// ------------------------------');// get text of 1st ie 0th li elementletfirstLiText=liElements[0].innerHTML;console.log('firstLiText: '+firstLiText);// console.log('// ------------------------------');// set text of last elementletlastLi=(liElements.length-1);liElements[lastLi].style.color='blue';// console.log('// ------------------------------');// highlighting all li elements through loopfor(varliinliElements){liElements[li].style.marginBottom='10px';liElements[li].style.background='#bbbbbb';}// console.log('// ------------------------------');

    14.03.04. Selecting Elements with CSS Selectors (querySelectorAll())

    • querySelectorAll() method findall HTML elements that match a specified CSS selector (id, class names, types, attributes, values of attributes, etc)
    • CSS selectors provide a verypowerful and efficient way of selecting HTML elements in a document
    • querySelectorAll() methodreturns an array or list of all the elements that matches the specified selectors

    Syntax & Example:

    // Selecting all ul -> li elementsletulLiElement=document.querySelectorAll('ul li');console.log(ulLiElement);letulListItemClass=document.querySelectorAll("ul li.list-item")console.log(ulListItemClass);// set color of last li elementulLiElement[ulLiElement.length-1].style.color='red';// set text of last li elementulLiElement[ulLiElement.length-1].innerHTML='Dynamic text change at run time';

    14.03.05.querySelector

    • selects the single ie first element
    ???

    14.04. JavaScript DOM CSS Styling

    Using JavaScript we can also apply CSS style on HTML elements to change the visual look and feel specification/presentation of HTML documents dynamically/at run time. We can apply/set almost all the CSS styles for the elements like fonts, colors, margins, padding, borders, alignments, background images, width and height, position, and so on.

    Naming Conventions of CSS Properties in JavaScript

    • CSS properties likefont-size,background-image,text-decoration, etc. containhyphens (-) in names
    • In JavaScripthyphens (-) is a reserved operator (a minus sign), so it is impossible to write an expression withhyphens (-), like: elem.style.font-size = '10px';
    • In JavaScript the CSS property names with hyphens are converted to intercapitalized style word (camelCasingNaming)
    • So CSS propertyfont-size,background-color,border-left-style becomes the DOM propertyfontSize,borderLeftStyle respectively and so on

    14.04.01. Applying/Setting Inline Styles on Elements

    • In HTML inline styles are applied directly to the specific HTML element using thestyle attribute, eg.<element>
    • In JavaScript thestyle property is used to get or set the inline style of an element, eg.elem.style.color = 'red';

    Syntax & Example:

    // Selecting element with idletmainHeadingElement=document.getElementById('mainHeadingText');// set css stylemainHeadingElement.style.padding='5px';mainHeadingElement.style.backgroundColor='pink';mainHeadingElement.style.color='blue';mainHeadingElement.style.border='5px solid #999999';

    14.04.02. Retrieving/Getting CSS Styles details from Elements

    • We can get the styles applied on the HTML elements using thestyle property
    • style property only returns the style rules set in the element's style attribute, not those applied through internal/embedded style sheets, or external style sheets
    • To get the values of all CSS properties that actually render an element we can use thewindow.getComputedStyle() method

    Syntax & Example:

    // Selecting element with idletmainHeadingElement=document.getElementById('mainHeadingText');// set css stylemainHeadingElement.style.padding='5px';mainHeadingElement.style.backgroundColor='pink';// console.log('// ------------------------------');// get inline css stylesconsole.log('mainHeadingElement.style.padding:',mainHeadingElement.style.padding);console.log('mainHeadingElement.style.backgroundColor:',mainHeadingElement.style.backgroundColor);// console.log('// ------------------------------');// get computed style information/ any type of css styles internal/embeded style sheetsvarcssStyles=window.getComputedStyle(mainHeadingElement);console.log('internal style - color:',cssStyles.color);console.log('internal style - border:',cssStyles.border);

    14.04.03. Applying/Adding CSS Classes to Elements - className

    • We can also get or set CSS classes to the HTML elements using theclassName property
    • Asclass is a reserved word in JavaScript, it uses theclassName property to reference the value of the HTML class attribute

    Syntax & Example:

    // Selecting element with idletmainHeadingElement=document.getElementById('mainHeadingText');// remove old classes and apply/set css classmainHeadingElement.className='bg-color';// apply/set css classmainHeadingElement.className+=' border';

    14.04.04. Applying/Adding CSS Classes to Elements - classList

    • UsingclassList property is much easier and better to get, set or remove CSS classes from an element
    • classList property is supported in all major browsers except Internet Explorer before version 10

    Syntax & Example:

    // Selecting element with idletmainHeadingElement=document.getElementById('mainHeadingText');// apply/set/add css class with classListmainHeadingElement.classList.add('heading-text');// apply/set/add css class with classListmainHeadingElement.classList.add('border','bg-color');// remove classes with classListmainHeadingElement.classList.remove('border','bg-color');// if class exists remove it, if not add itmainHeadingElement.classList.toggle('heading-text');// mainHeadingElement.classList.add('border');// check if class exist and act accordinglyif(mainHeadingElement.classList.contains('border')){alert('border class present');}else{alert('NO border class present');}

    14.05. JavaScript DOM HTML get set attributes

    • An attribute in HTMLprovides extra information about the element, and it is applied within the start tag
    • An HTML attribute contains two fields:name & value / key & value
    • JavaScript provides several methods for adding, reading or removing an HTML element's attribute likesetAttribute(), getAttribute(), removeAttribute()

    14.05.01. Applying/Setting Attribute on Element

    • ThesetAttribute() method is used to set an attribute on the specified element
    • If the attribute already present/exists on the element, the attribute value will be updated; else a new attribute is added with the specified name and value

    Syntax & Example:

    // Selecting element with idletmainHeadingElement=document.getElementById('mainHeadingText');letclickButtonElement=document.getElementById('clickButton');letlinkTextElement=document.getElementById('linkText');// set attribute class named 'btn'mainHeadingElement.setAttribute('class','btn');// set attribute disabledclickButtonElement.setAttribute('disabled','');// set blank/empty attribute so that it will remove exisiting attribute valuelinkTextElement.setAttribute('href','');

    14.05.02. Retrieving/Getting Attribute Value

    • ThegetAttribute() method is used to get the current value of an attribute on the element
    • If the specified attribute does not present/exists on the element, it will returnnull

    Syntax & Example:

    // Selecting element with idletmainHeadingElement=document.getElementById('mainHeadingText');letclickButtonElement=document.getElementById('clickButton');letlinkTextElement=document.getElementById('linkText');// getting the attributes valuesletgetAttrClass=mainHeadingElement.getAttribute('class');console.log('getAttrClass:',getAttrClass);letgetAttrDisabled=clickButtonElement.getAttribute('disabled');console.log('getAttrDisabled:',getAttrDisabled);letgetAttrHref=linkTextElement.getAttribute('href');console.log('getAttrHref:',getAttrHref);

    14.05.03. Removing Attributes from Elements

    • TheremoveAttribute() method is used to remove an attribute from the specified element

    Syntax & Example:

    // Selecting element with idletmainHeadingElement=document.getElementById('mainHeadingText');letclickButtonElement=document.getElementById('clickButton');letlinkTextElement=document.getElementById('linkText');// removing the attributesmainHeadingElement.removeAttribute('class');// verify/confirm class removed or notconsole.log('mainHeadingElement.getAttribute:',mainHeadingElement.getAttribute('class'));console.log('mainHeadingElement.classList.contains:',mainHeadingElement.classList.contains('class'));// console.log('// ------------------------------');clickButtonElement.removeAttribute('disabled');linkTextElement.removeAttribute('href');

    14.05.04. Selecting document elements without selectors

    14.05.04. Select HTMLCollection without selectors

    Syntax & Example:

    -document.forms-document.forms[0]oruserespectiveformelementindex-document.forms[0].id-document.forms[1].method-document.forms[1].action-document.links-document.links[0]-document.links[0].className//class names as a string-document.links[1].classList[]// collection of classes-document.images-document.images[0]-document.scripts-document.scripts[0]-document.scripts[1].getAttribute('src');

    Section 15. What's Next Step?

    Great Job! Thank You for looking into JavaScript for Beginners. I hope you enjoyed and learned a lot out of it. I think Now you have better understandings of how JavaScript works and functions. To learn more about JavaScript visitMozilla JavaScript Reference Guide.

    • Your Next step could be looking into advanced topics ofHTML5, [CSS3] or [JavaScript].
    • For detailed view on JavaScript look into [Advanced JavaScript Tutorial],JavaScript ES6 Tutorial orTypeScript Tutorials.
    • You may move forward with any famous and popular JavaScript Frameworks or Libraries like jQuery.js,Angular, React.js, NPM, Node.js, Vue.js etc.

    Best of Luck! Happy Learning!


    [8]ページ先頭

    ©2009-2025 Movatter.jp