- Notifications
You must be signed in to change notification settings - Fork70
dinanathsj29/javascript-beginners-tutorial
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
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.
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
To move forward with JavaScript you just need basic knowledge of XHTML/HTML. Here, you will learn how easy it is to add interactivity to a web page using JavaScript. But, before we begin, make sure that you have some working knowledge and/or general understanding of:
- The Internet and the World Wide Web (WWW)Web Design Development Foundations-Web Technology Fundamentals
- Good working knowledge of HyperText Markup Language (HTML)HTML5 Essentials and
- Its good to knowCSS3 Fundamentals
- Course Introduction
- 01.01.Welcome
- 01.02.Who is this for? Audience
- Introducing JavaScript
- 02.01.Importance
- 02.02.What is JavaScript?
- 02.03.What is a scripting language?
- 02.04.What can you do with JavaScript? |Use of JavaScript?
- 02.05.Where does the JavaScript code run?
- 02.06.Who are using JavaScript?
- 02.07.History of JavaScript
- 02.08.JavaScript Vs ECMAScript
- 02.09.Types of Script |Various Scripting languages |Client-Side Scripting Vs Server Side Scripting
- 02.10.Prerequisites of using HTML and JavaScript
- JavaScript Getting Started
- JavaScript Language Fundamentals
- 04.01.Generating Output
- Variables
- Data types
- Operators
- 07.01.What is the Operator?
- 07.02.Arithmetic Operators
- 07.03.Assignment Operators
- 07.04.Logical Operators
- 07.05.Comparison Operators |Relational Operators
- 07.06.Conditional Operator |Ternary Operator
- 07.07.String Operators
- 07.08.Operator precedence
- Functions
- Loops |Loops and Iterations
- 09.01.The for loop
- 09.02.The while loop
- 09.03.The do while loop
- 09.04.The for in loop
- 09.05.The for of loop
- 09.06.Break and Continue statement
- 09.07.for each loop
- Conditions - Control Flow
- Array
- 11.01.What is an Array?
- 11.02.Create Array by array literal
- 11.03.Create Array by creating an instance of array directly
- 11.04.Create Array by using an array constructor
- 11.05.Getting the Length of an Array
- 11.06.Accessing Looping through an Array Elements |Loop through an Array Elements
- 11.07.Adding Editing an Array Elements
- 11.08.Removing Deleting an Array Elements
- 11.09.Array properties and methods
- Objects
- 12.01.Real Life Objects |Object Properties and Method examples
- 12.02.What is an Object?
- 12.03.Object literal
- 12.04.Creating an instance of Object directly
- 12.05.Object constructor
- 12.06.Accessing objects properties |Looping through Objects properties
- 12.07.Removing Deleting objects properties
- 12.08.Manipulating by Value Vs Reference
- 12.09.The Window object
- 12.10.The Math Object
- 12.11.Date and Time
- Events
- DOM (Document Object Model)
- What's Next Step?
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.
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.
HTML (HyperText Markup Language) - Markup language, Essential Page Structure/Content, Readable and convey structure to a user, Text Layout Model, page Mark-up, Text, Tags, Data, details for pages, Images, Tables, Anchor Links, Forms
- HTML is an acronym stands for
HyperText Markup Language
which is used for 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
- HTML is an acronym stands for
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
JavaScript (JS) - Scripting language, Dynamic Page Behaviour, Logics, Conditions and Validations, Events (mouse click, hover), Interactivity with User, Dynamic updates in a Web Page
- JavaScript is a
scripting language of the web
that allows you to do Interactivity with User-Events, implement Conditions and Validations, Dynamic updates in a Web Page, etc.
- JavaScript is a
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>
- JavaScript is
1 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 an
Open Source
,Cross-Platform
, andBrowser-based Client-Side (user computer)
programming language of the web - JavaScript is a dynamic computer programming language. It is an
interpreted (translated)
programming language withobject-oriented capabilities
- JavaScript is officially maintained by
ECMA (European Computer Manufacturers Association) as ECMAScript
- ECMAScript 6 (or
ES6
or ECMAScript 2015) is the latest major version of the ECMAScript standard - JavaScript is case sensitive language
Image 02.02.01 - Stackoverflow Programming, Scripting, and Markup Languages Survey 2019 Image 02.02.02 - Google Trends - Language CompareNote:
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.
- 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 are
JavaScript, 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 alongside
HTML, Java or C++
- Popular scripting languages are
- 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
- A script is nothing but sets of instructions
- Series of commands
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 a
programming tool
- JavaScript can react to
events
(mouse click, hover (rollover, rollout), focus, blur) - JavaScript can be used to
validate
data (Client-side validation
) - JavaScript can manipulate
HTML content
andCSS styles
- Dynamic
drop-down menus
, HTML contents at run time/on the fly - Displaying live/current/dynamic
date and time (clocks)
- Displaying
pop-up windows
anddialog boxes
(analert
,confirm
andprompt
dialog box) - Change the website's
behavior
and make it moredynamic with advanced
web designs - Perform and
control 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
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.
Browser | Engine |
---|---|
Browser, Headless Browser, or Runtime | JavaScript Engine |
Mozilla | Spidermonkey |
Safari** | JavaScriptCore* |
IE and Edge | Chakra |
Chrome | V8 |
TrifleJS | V8 |
Node.js*** | V8 |
Io.js*** | V8 |
PhantomJS | JavaScriptCore |
HTMLUnit | Rhino |
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
- 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 to
JAVA
(completely different in concept and design) Microsoft
has developed new version of "JavaScript" as"JScript"
forIE-3
in1996
- JavaScript Submitted to
ECMAScript in 1997
JavaScript | ECMAScript |
---|---|
JavaScript isscripting programming language | ECMAScript is aspecification/standard |
JavaScript is invented byBrandan Eich atNetscape | ECMAScript standards defined byECMA (European Computer Manufacturers Association) |
JavaScript is released in 1995 | First ECMAScript standard published in 1997 |
JavaScript uses/follows ECMAScript specifications/standards | ECMAScript specification defines many new features for JavaScript |
Client-Side Scripting | Server-Side Scripting |
---|---|
Instruction for web Browser | Instruction 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 input | Server-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 computer | Response 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 browser | Server-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. |
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
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
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
Image 02.10.01 - Widely used modern browsers Image 02.10.02 - Developer Tool Inspect Console Image 02.10.03 - Developer Tool Inspect ConsoleNote:
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
- 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
- So the best practice is to place/add the
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>
- Inside the HEAD section
- Inside the BODY section
- External JavaScript .js file (separation of concern)
- 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>
- 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>
- We can easily write JavaScript code in between the
script 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 to
extract and separate
our JavaScript behavior code from our HTML markup code - A simple thumb-rule is if we have a lot of JavaScript code, we can put it into a separate file
- We can use/add/attach an external JavaScript file by using
<script>
tag withsrc (source)
attribute:<script src="path/scriptfile.js"></script>
- One can provide a
full 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 provide
code re-usability
- 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>');
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:
- 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 by
Semicolon;
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 a
Semicolon;
Note:
JavaScript statements are composed of:Values, Operators, Expressions, Keywords, and Comments
- JavaScript ignores
spaces, 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)
- JavaScript statements are generally followed by a
semicolon; character
- A semicolon may be omitted in
most cases
when a line break exists - JavaScript interprets the line break as an
implicit
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
- 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
- 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 JavaScript
function
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();
Usually, JavaScript commands/statements start with aspecific keyword
which defines whataction/function
should the browser will perform/do:
Keyword | Keyword | Keyword | Keyword | Keyword |
---|---|---|---|---|
break | do ... while | if ... else | try ... catch | const |
continue | for | return | var | class |
debugger | function | switch | let | import |
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,
- The comments are a meaningful way to
deliver the message (description to code)
for others/for future reference and to understand/follow the code statements/lines - Comments are special lines written for other developers as a reference purpose and browser ignores while interpreting
- It is used to add information about the code, warnings or suggestions so that end-user can easily interpret the code (
Why and How of code/program/logic
) - 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 to
make code easy to understand
andit avoids the unnecessary code
There are two types of comments in #"auto">
- Single-line JavaScript comments are used for one line of comment only
- Single-line comments starts with
two 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
- Multi-line comments usually comment out a block of code
- Multi-line comments in JavaScript can comment on bigger parts (a few lines) of code
- Multi-line comments are more convenient as it can be used to comment single as well as multi-line comments
- Multiline comments start with
forward slash and an asterisk, /* and also end with an asterisk and a forward slash */
: /* multi-line comment */ - Multi-line comments need closing
- Multi-line comments are more often used for
formal 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 */
- JavaScript does not have any
display or built-in print
functions - Many times we may need to generate output from your JavaScript code like
see the value of a variable
, 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
- Writing into an alert box with
alert() or window.alert()
- Writing into browser console with
console.log()
- Writing into the HTML / Browser Window with
document.write()
- Write into an element of HTML / Inserting Output Inside an HTML Element with
innerHTML
- One can use
alert dialog boxes
to display the message or output data to the user - An alert dialog box is created using the
alert() or window.alert()
method - A small pop-up box appears with a closing button to close alert-box
- This method is great for short and rapid informative messages which can be instantly closed
Syntax & Example:
04.01.01.script.js
// external js file// Write all JavaScript code herealert('I am Dinanath Jayaswal');window.alert('We are learning JavaScript');
- Programmers can easily output a message or write data to the browser console using the
console.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.
document.write()
method is used to write the content to the current document while document is being parsed- Programmers do ues document.write() for
testing 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');
- We can write or insert output inside an HTML element using the element's
innerHTML
property - First we need to select the element using a method such as
document.getElementById(id)
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.
Variables are one of the most fundamental concepts in JavaScript and other all programming languages of the world.
- A variable is
container to store/hold the data/information
- Developers/Programmers use Variable to
store/hold the data/information temporarily
in computer memory - A variable is a kind of data holder where we can store some value for programming or calculation purpose
- A JavaScript variable is simply a
name of the storage location (named containers/named storage)
for data - Variables are symbolic names for values
- Variables are used to store data of different types like a string of text, numbers, boolean values like true/false, an array of data, etc.
- The data or value stored in the variables can be set, updated, and retrieved whenever needed
- Variables are declared using the keyword
var
keyword - The
assignment operator (=)
is used to assign value to a variable, like this:var varName = value;
orvar firstName = 'JavaScript';
- By default value of variable defined in JavaScript is
undefined
(variable is defined but value not assigned:var firstName;
orlet lastName; console.log(firstName, lastName);
// undefined)
- Example: Variables are like
box 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 just
like 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);
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);
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);
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 as
identifiers
)- Identifiers are
simply names
in JavaScript - Identifiers are used to name variables, keywords, functions, and labels
- Identifiers can be
short names/nick names
(like name, age, num1, isDone, sum) or more descriptive names (firstName, totalDashboards, isSeniorCitizen)
- Identifiers are
The basic rules for defining/assigning names for variables (unique identifiers) are:
- A variable name must
start with a letter, underscore (_), or dollar sign ($)
- Example: var firstName, var _firstName, var $firstName;
- Names can contain letters, digits, underscores, and dollar signs
- Example: var $num_total1;
- A variable name
cannot start with a number or special characters
- Example: var 1num_total, var .num_total
- A variable name
cannot contain spaces
- Example: var num total;
- A variable Names are
case sensitive
- Example: var firstName='Dinanath'; and var FirstName='Dinanath'; here
firstName & FirstName
are different ie. two different variable
- Example: var firstName='Dinanath'; and var FirstName='Dinanath'; here
- A variable name cannot be a
JavaScript keyword or a JavaScript reserved word
- Example: var var; var switch; var for; var true;
- One should Always give
meaningful/descriptive names
to variables - for naming the variables that contain multiple words,
camelCase
method is commonly used (camelCase is the default method for identifier naming)
Note:
In the programming world, there have been two most popular methods/mechanism of writing multiple words identifiers: (Underscore, Camel Case)
- Underscore: first_name, last_name, date_of_birth, is_passed, native_place
- 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;
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:
- Local Variables
- Global Variables
- A JavaScript local variable is declared
inside block or function
- It is accessible within the
function or blocks only
- A local variable will be
visible 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);
- A variable
declared 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);
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 - Both
let
andconst
keywords declare variables,scoped at block-level ({})
- Block scoping means that a new scope is created
between a pair of curly brackets {}
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 the
var
keyword arefunction-scoped
and can behoisted
at the top within its scope - Variables declared with
let
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
ES6
introduces the newconst
keyword for declaring variables.
- Use
const
to declare a constant(read-only / unchanging)
variable - Constants are
read-only
, youcannot reassign new values
to them - In Programm/logic when the variable will never change, they can be declared as
const
- constants are named using capital letters and underscoreExample: const NATIVE_CITY
const
are alsoblock-scoped
likelet
- However, you can change
object 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
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">
- String
- Number
- Boolean
- Undefined
- Null
- Symbol (newly introduced in ES6)
- Array
- Object
- Function
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 Type | Description |
---|---|
String | represent textual data. e.g. "welcome" or 'to javascript' |
Number | represents numeric values e.g. 10, 100.29 |
Boolean | represents boolean value either false or true |
Undefined | represents an undefined value (a variable declared but value not assigned) |
Null | represents null i.e. no value at all |
- The string data type is used to
represent textual data (i.e. sequences of characters)
- Strings hold information in
words/text
- A string in JavaScript must be surrounded by
"double"
or'single'
quotes - Example:
06.02.script.js
varfirstName="Java";varlastName='Script';
- 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;
- The Boolean data type can hold only two values:
true or false
- true = ON / yes / correct / 1, false = OFF / no, incorrect / 0
- Boolean data types is often used in
conditional testing
of code - Example:
varisDone=true;varisMarried=false;
- 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, but
not assigned a value
- A variable
without a value
, The type is also undefined - Example:
varfirstName;varcountry;
- 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;
- Non-primitive/Reference data types can hold
collections of values and more complex entities
- Non-primitive values are being compared by
reference
instead of value - 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 Type | Description |
---|---|
Array | represents a group of similar value (multiple values in one variable) |
Object | represents an instance through which we can access members (property & value) |
Function | represents function (bunch/block of line to execute once) |
We have two types of programming languages:
- Static languages
- Declare a variable, the type of the variable is set and it cannot be changed in the future
- 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 JavaScript
variable can contain/hold any data ie. any type of data
, A variable at one moment can be a number and at another moment be a string, boolean - It simply means that
same variable can be used to hold different data types
- JavaScript is a dynamic type language, means you don't need to specify a type of the variable because it is dynamically used by JavaScript engine
Syntax & Example:
06.04.script.js
letname='JavaScript';name=false;name=100;alert(name);alert(typeof(name));
- The typeof operator returns the
type of the argument
- It’s useful to process values of different types differently or want to perform a quick data type check
- The typeof operator can be used to find out what
type 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"
- Type conversion is nothing but taking a variable and changing its data type as per needs requirements and logic
- In JavaScript as and when we take an
input in the form, its data type is a string by default
, so do any calculations we need 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');
- 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);
- We know/use many operators since our initial school days, they are things like addition +, multiplication *, subtraction -, open-close round bracket ( ) or square bracket [ ]
- Operators are symbols/keywords that tell the JavaScript engine to
perform some sort of actions
- JavaScript operators are symbols that are used to perform operations on operands
- Operators used along with our variables and constants to createexpressions to implement logic and algorithms
Note:
Let us take a simple expressionvar sum = 1 + 2
;
- Here 1 and 2 are called
operands
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:
- Arithmetic Operators
- Assignment Operators
- Logical Operators
- Comparison (or Relational) Operators
- Conditional (or ternary) Operators
- String Operators
- Bitwise Operators
- Arithmetic operators are used to performing arithmetic operations (just like mathematics - calculations) on numbers/the operands
JavaScript supports the following Arithmetic operators (List of Arithmetic operators):
Operators | Description | Example / Result |
---|---|---|
+ | Addition | 10 + 20 = 30 (Sum of num1 and num2) |
- | Subtraction | 20 - 10 = 10 (Difference of num1 and num2) |
* | Multiplication | 10 * 20 = 200 (Product of num1 and num2) |
/ | Division | 20 / 10 = 2 (Quotient of num1 and num2) |
% | Modulus (Division Remainder) | 20 % 10 = 0 (Remainder of num1 divided by num2) |
++ | Increment | var num1 = 100; num1++; Now num1 = 11 |
-- | Decrement | var num1 = 100; num1--; Now num1 = 9 |
** | Exponentiation (ES2016 / ES6) | 2 ** 2 = 4 ; 2 ** 3 = 8 (Multiply num1 for num2 times) |
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
- The Assignment operators are used to assign particular values to variables
JavaScript supports the following Assignment operators (List of Assignment operators):
Operators | Description | Example / Result |
---|---|---|
= | Simple Assignment | 10 + 20 = 30; / var total = num1 + num2; (assigns a value to the variable) |
+= | Add and assign | var num1 = 10; num1 += 20; Now num1 = 30 (assigns and adds value to the variable, num1 += 20; is equivalent to num1 = num1 + 20;) |
-= | Subtract and assign | var num1 = 10; num1 -= 5; Now num1 = 5 (assigns and subtract value to the variable, num1 -= 5; is equivalent to num1 = num1 - 5;) |
*= | Multiply and assign | var num1 = 10; num1 *= 5; Now num1 = 50 (assigns and multiply value to variable, num1 *= 5; is equivalent to num1 = num1 * 5;) |
/= | Divide and assign | var num1 = 10; num1 /= 5; Now num1 = 2 (assigns and divide value to the variable, num1 /= 5; is equivalent to num1 = num1 / 5;) |
%= | Modulus and assign | var num1 = 10; num1 %= 5; Now num1 = 0 (assigns and Modulus value to the variable, num1 %= 5; is equivalent to num1 = num1 % 5;) |
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
- The Logical operators are used to make decisions based on multiple conditions
- The logical operators are typically used to combine multiple conditional statements and evaluate
JavaScript supports the following Logical operators (List of Logical operators):
Operators | Description | Example / Result |
---|---|---|
&& | Logical AND | x && y; (True if both operands like x and y are true) |
|| | Logical OR | x || y; (True if either x or y is true) |
! | Logical NOT | !x; (True if x is not true) |
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);
- 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):
Operators | Description | Example / Result |
---|---|---|
== (Loose Equality Operator) | Is equal to / identical | x == y (True if x is equal to y) |
=== (Strict Equality Operator) | Eqaul/identical value and identical type | x === y (True if x is equal to y, and they are of the same type) |
!= | Not equal to / different | x != y (True if x is not equal to y) |
!== | Not identical / different value or different type | x !== y )True if x is not equal to y, or they are not of the same type) |
< | Less than | x < y (True if x is less than y) |
> | Greater than | x > y (True if x is greater than y) |
<= | Less than or equal to | x <= y (True if x is less than or equal to y) |
>= | Greater than or equal to | x >= y (True if x is greater than or equal to y) |
Syntax & Example:
07.05.script.js
// 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
- 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
Operators | Description | Example / Result |
---|---|---|
? | Ternary operator | var result = x < y ? 'x is smaller' : 'y is smaller' (short hand method to write if condition) |
Syntax & Example:
07.06.script.js
// 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);
Variables can also have string values,+ operator
can be used to concatenate strings as well as numbers.
There are two operators which can also be used be for strings:
Operators | Description | Example / Result |
---|---|---|
+ | Concatenation | string1 + string2 (Concatenation of string1 and string2) |
+= | Concatenation assignment | string1 += string2 (Appends the str2 to the str1) |
Syntax & Example:
07.07.script.js
// String Operatorsvarmessage1="Hello";varmessage2=" World!";alert(message1+message2);// Outputs: Hello World!message1+=message2;alert(message1);// Outputs: Hello World!
- If an expression has more than one operator, the
execution order is defined by their precedence
, or the implicit priority order of operators - Operator precedence determines/describes the way in which operators are parsed with respect to each other /
order in which operations are performed
- The operations inside the
parentheses ()
are computed first - If many operations have the same precedence (like addition and subtraction), they are
computed 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
- A function is basically a
group of statements that perform specific tasks/operations
- Functions provide a way to
create reusable code packages
which are more portable and easier to debug - Functions allow a programmer to
divide a big program
into a number of/several small and manageable functions - It helps programmers in writing
modular 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 called
MODULES, SUBROUTINES(SUB-ROUTINES)
- There are two steps to utilize function:
- create/define a function with
function
keyword - call/invoke a function
- create/define a function with
Note:
Best Practice - First Define function than call/envoke it!
- 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
- The function declaration starts by using the
function keyword
, - followed by a
unique function name
, - a list of
parameters in parentheses
i.e. () (that might be empty), - and a statement block surrounded by
curly braces { }
Syntax & Example:
08.01.script.js
//1. define / declare / create functionfunctionshowMessage(){//Body of function//code to be executedconsole.log('welcome to JavaScript function');alert('welcome to JavaScript function');}
- Defined function can be invoked/called/run from anywhere in the document, by typing
function name followed by a set of parentheses, like functionName()
Syntax & Example:
08.01.script.js
//2. invoke / call the functionshowMessage();
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();
- Regular Function
- Parameterized Function
- Return Type Function (Function returning values)
- 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();
- 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);
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);
- A function can
return 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);
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)
- 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));
- 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');
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(','));
ES6 new feature
Strings Template
offers a convenient way to work with string concatenation/interpolationTemplate 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
Use
back-tick (grave accent)
character and{ var name in curly brace }
, no + plus sign requiredThe best part of Template Literals (Template Strings) is we can
use '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);
- Loops are used to execute the
same 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 to
automate the repetitive tasks within a program to save time and effort
- It makes the
code 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">
- for loop
- while loop
- do...while loop
- for...in loop
- for...of loop (ES6)
- for...each
- The
For
loop is used to run a piece of code aset amount of times
- Loops through a block of code until the
counter reach a specified number
- The for loop
repeats 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 (), mostly
i = 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);}
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);}
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); } */}
- 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++;}
- The do...while loop is similar to the while loop except that the
condition check happens at the end of the loop
- The do...while loop will always be
executed at least once (before checking if the condition is true)
, even if the condition is false
Syntax & Example:
09.03.01.script.js
// 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);
- The for-in loop is a special type of a loop that
iterates over the properties of an object or the elements of an array
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]);}
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]);}
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);}
- Loops over
iterable objects such as arrays, strings
, etc. - ES6 introduces a new for-of loop which allows us to iterate over arrays or strings very easily
- The code inside the loop is executed for each element of the iterable object
Syntax & Example:
09.05.01.script.js
// 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+',');}
break
andcontinue
keywords/statement can changehow the loop behaves
break
andcontinue
keywords can be used in all loops to stop or continue the loop- The
break
statement is used to exit a loop early, to "jump out" of a loop, stops executing/running a loop - The
continue
statement tells the interpreter to immediately start the next iteration of the loop and skip the remaining code block
Syntax & Example:
09.06.01.script.js
// 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);}
Syntax & Example: ``
letarrDays=["Monday","TuesDay","Wednesday","Thursday","Friday","Saturday","Sunday"];arrDays.forEach(function(day)){console.log(day);}
- 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: >, <, >=, <=, ==, !=, ===
- If Statement
- If...else Statement
- If...else if...else Statement
- Switch...Case Statement
- If the conditional statement is the simplest and basic control statement make decisions and execute statements conditionally
- The if statement is used to execute a block of code
only if the specified condition evaluates to true
- It evaluates the content only
if 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&¤tHours<12){console.log('Good Morning!');window.alert('Good Morning!');}
- The JavaScript
if...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 an
else
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!');}
- The
if...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 to
make 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&¤tHours<12){console.log('Good Morning!');window.alert('Good Morning!');}elseif(currentHours>12&¤tHours<=18){console.log('Good AfterNoon!');window.alert('Good AfterNoon!');}else{console.log('Good Evening!');window.alert('Good Evening!');}
- The switch...case statement is alternative to an if...else if...else statement, both do almost the same thing
- This matches the
case
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}!`);
- An Array is a special type of variable/object which
consists of / stores multiple values
- Arrays are complex variables that allow us to store more than one value or a group of values under a single variable name
- Arrays are defined with
square brackets [ ]
and withnew
keyword - Array items are normally separated with
commas,
- Arrays are
zero-indexed
i.e. the first element of an array is at index/position 0 - An array is
ordered collection
, where we have a 0th, 1st, a 2nd, and so on elements - Each value (an
element
) 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]
There are 3 main ways to construct an array:
- By array literal
- By creating an instance of Array directly (using the new keyword)
- By using an Array constructor (using the new keyword)
- The simplest way to create an array in JavaScript is enclosing a
comma-separated list of values in square brackets [ ]
- var myArray = [element0, element1, ..., elementN];
Syntax & Example:
11.02.01.script.js
// 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);
- Array instance can be created using the
new
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
- Array instance can be created using the
new
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
- The
length
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 is
4,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);
- Array elements can be accessed by their
index using the square bracket notation ie. [index]
- Arrays are
zero-indexed
i.e. the first element of an array is at index/position 0 - An array is
ordered collection
, where we have a 0th, 1st, a 2nd, and so on elements - Each value (an
element
) 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 use
for 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>');}
- One can add/edit an array element by simply specifying
array[index] and value
ie.myarray[5]='value'
- If array
index exists it will simply edit
the old value and update the array else it will add an element to the array 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);
pop()
methodremove the last element
from an arrayshift()
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);
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));
- In real life almost
everything is an object
.- For example: Human, Car, Building, Bike, Pen, Chair, Monitor, Keyboard, Vehicle, Mobile, Computer etc.
- Let's have a look on some Objects with Properties and Methods:
Object | Properties | Methods |
---|---|---|
Person | Person.name = 'dinanath'; Person.weight = 65; Person.color = 'fair' | Person.walk(); Person.talk(); Person.eat(); |
Bike | Bike.brand = 'bajaj'; Bike.model = 'discover'; Bike.color = 'blue'; Bike.length = 60; Bike.height = 30; | Bike.start(); Bike.break(); Bike.stop(); |
Watch | Watch.type = 'analog'; Watch.price = 750; | Watch.showTime(); Watch.setAlarm(); |
Note:
As a practice think of any other object in your surrounding and list down its Properties and Methods
- JavaScript is an
object-based language
and in JavaScript, almost everything is an object or acts like/as an object - An object is a
special/complex
data type that allows you tostore collections of data
- An object is a kind of container/declaration where we can group various
data, properties, and behaviors
under one roof (group related variables) - A JavaScript object is just a collection of
named values referred to as properties
of the object - Objects are defined with
curly braces { }
, the properties of an object are written in pairs (propertyName: value
) - An object contains properties, defined as a
key-value pair
(Objects are a collection ofkey-value pair
) - A property
key (name) is always a string
, but the value which it stores can be any data types, like strings, numbers, booleans, or complex data types like arrays, function and other objects - JavaScript object properties can be accessed through two methods:
- .DOT notation:
object.firstName
- []Bracket notation:
object['firstName']
- .DOT notation:
There are 3 main ways to construct an object:
- By object literal
- By creating an
instance
of Object directly (usingnew
keyword) - By using an
Object constructor
(usingnew
keyword)
- The simplest way to create an object in JavaScript is enclosing a
comma-separated list of properties:values and methods in curly braces { }
- var MyObject = { property1: value1, property2: value2.....propertyN: valueN }
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('// ------------------------------');
- Array instance can be created using the
new
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('// ------------------------------');
- In this method, create a function with arguments
- Each argument value can be assigned in the current object by using
this
keyword,this
keyword refers to 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('// ------------------------------');
- To access or get the value of a property, you can use the
dot .
, orsquare bracket []
notation - We can iterate through the
key-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('// ------------------------------');
- The
delete
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']);
In JavaScript we have two categories of types:
- Value Types (Primitives = Basic type) - Primitives are copied by their value
- Reference Types (Objects = Complex type) - Objects are copied by their Reference/Location in memory
- Number
- String
- Boolean
- Undefined
- Null
- Symbol (ES6)
- Object
- Function
- Array
Syntax & Example:
???
- Window Object the global variable/global object
available in the browser environment
, represents the browser window in which the script is running - Simply, the window object
represents a window in a browser
- 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
- In
Browser -> 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;
- The Math object allows to perform mathematical tasks
- Math object provides several constants and methods to perform mathematical operation (like
min, max, sqrt, pi, round, random
, etc)
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
- The Date object is used to deal/work with date and time
- Simply, the JavaScript date object can be used to get date, day, month and year
- Date objects are created with
new Date()
- Date constructor can be used to create date object, It provides methods to get and set day, month, year, hour, minute and seconds
Syntax & Example:
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);
- Events are happening/triggering all over, Event lets the developer know
something has occurred/happened
- Events occur when the page loads (Onload), when the user interacts with the web page (clicked a link or button/hover) (onlick), pressed key, moved the mouse pointer, mouse-clicked/hover (onmouseover), entered text into an input box or textarea (onchange, onblur, onfocus), submits a form (submit), page unloads (unload)
- When an event occurs, use a JavaScript
event handler (or an event listener) to detect
them and perform a specific task - Event handlers name always begin with the word"on"
, like onclick, onload, onblur, and so on - To react to an event you
listen
for it and supply acallback function or event handler
which will be called by the browser when the event occurs
In general, the events can be categorized into four main groups:
- Mouse events
- Keyboard events
- Form events
- Document/Window 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 the
mouse clicks on an element
, links, buttons etc. on a web page
- Occurs When the
- contextmenu (
oncontextmenu
event handler)- Occurs when a
user clicks the right mouse button
on an element to open a context menu
- Occurs when a
- 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)`}
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;}
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 an
input
text field
- Occurs when the user focuses on an element on a web page, e.g. on an
- 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();}
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>
- HTML Attribute
- DOM element properties (anonymous function)
- Registering event listeners (Professional Method (add and remove listeners))
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.
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');}
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:
???
- 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???
- 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 of
Nodes
(elements, its attributes, text, etc.)
- Structural representation of HTML document (Tree of nodes/elements/tags)
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 pagedocument.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,
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.
- One can select an element based on its
unique ID
with thegetElementById()
method getElementById()
is the easiest and most common way to find/access an HTML element in the DOM treegetElementById()
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';
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';}
- Developer can also
select 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('// ------------------------------');
querySelectorAll()
method findall HTML elements that match a specified CSS selector
(id, class names, types, attributes, values of attributes, etc)- CSS selectors provide a very
powerful 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';
- selects the single ie first element
???
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.
- CSS properties like
font-size
,background-image
,text-decoration
, etc. containhyphens (-)
in names - In JavaScript
hyphens (-)
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 property
font-size
,background-color
,border-left-style
becomes the DOM propertyfontSize
,borderLeftStyle
respectively and so on
- In HTML inline styles are applied directly to the specific HTML element using the
style attribute
, eg.<element>
- In JavaScript the
style 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';
- We can get the styles applied on the HTML elements using the
style 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 the
window.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);
- We can also get or set CSS classes to the HTML elements using the
className property
- As
class
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';
- Using
classList 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');}
- An attribute in HTML
provides 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 like
setAttribute(), getAttribute(), removeAttribute()
- The
setAttribute()
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','');
- The
getAttribute()
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 return
null
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);
- The
removeAttribute()
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');
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');
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!
About
A JavaScript tutorials for beginners, An introduction to JavaScript programming languages building blocks, step-by-step guide to JavaScript