A JavaScript tutorials for beginners, An introduction to JavaScript programming languages building blocks, step-by-step guide to JavaScript
JavaScript is a scripting language of the web
that allows you to do/add Interactivity with User-Events, implement Conditions and Validations, Dynamic updates in a Web Page, etc.. In this practical course will learn JavaScript basics-programming fundamentals from scratch. We Will start with what is JavaScript? its uses, history, how to write JavaScript, etc. It will also cover various programming building blocks like variable, functions, array, conditionals, objects, and many more.
Add topics to categorize your repository and make it more discoverable:
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:
Hi All, I'm Dinanath Jayaswal, Senior UI/Web Developer and Adobe Certified Expert Professional
, I wanna welcome you to JavaScript for Beginners. In this course, I will take you through with the ins and outs of learning JavaScript. This course will help you to learn the fundamentals of programming with JavaScript scripting language, from the basics to advanced topics step-by-step.
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
HyperText Markup Language
which is used for creating web pages and web applications
CSS (Cascading Style Sheet) - Style Sheet language, Page Design / Presentation / Layouts / Styling / Formattings, look and feel, Creative part of Web Pages
JavaScript (JS) - Scripting language, Dynamic Page Behaviour, Logics, Conditions and Validations, Events (mouse click, hover), Interactivity with User, Dynamic updates in a Web Page
scripting language of the web
that allows you to do Interactivity with User-Events, implement Conditions and Validations, Dynamic updates in a Web Page, etc.Syntax & Example:
02.01.js.intro.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-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 here
alert('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>
1 of the 3 core language/layers
of web...(HTML, CSS & JavaScript)Open Source
, Cross-Platform
, and Browser-based Client-Side (user computer)
programming language of the webinterpreted (translated)
programming language with object-oriented capabilities
ECMA (European Computer Manufacturers Association) as ECMAScript
ES6
or ECMAScript 2015) is the latest major version of the ECMAScript standardNote:
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.
JavaScript, VBScript, PHP, Perl, Python, Ruby, ASP
HTML, Java or C++
C program
needs to be compiled before running whereas normally, a scripting language like JavaScript or PHP
need not be compiledFor a long time, JavaScript is used only as a Client 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:
programming tool
events
(mouse click, hover (rollover, rollout), focus, blur)validate
data (Client-side validation
)HTML content
and CSS styles
drop-down menus
, HTML contents at run time/on the flydate and time (clocks)
pop-up windows
and dialog boxes
(an alert
, confirm
and prompt
dialog box)behavior
and make it more dynamic with advanced
web designscontrol transitions
and animations
JavaScript was originally designed and developed to run only in browsers. But now with the help of the Node/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:
Big companies and brands build entire applications:
“Brandan Eich”
at Netscape
in 1995
originally named as "LiveScript"
Netscape
& Sun Java
agreements to rename "LiveScript"
to "JavaScript"
(As java
is already popular in the market)JAVA
(completely different in concept and design)Microsoft
has developed new version of "JavaScript" as "JScript"
for IE-3
in 1996
ECMAScript in 1997
JavaScript | ECMAScript |
---|---|
JavaScript is scripting programming language |
ECMAScript is a specification/standard |
JavaScript is invented by Brandan Eich at Netscape |
ECMAScript standards defined by ECMA (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.
Browsers - To view output of .html pages with .js files - Google Chrome, Mozilla Firefox, Internet Explorer, Safari
etc.
JavaScript Output / Debugging Tool (Developer console) -
Developer Tools Inspect
/ Inpsect element (in browser -> Right Click on page -> choose Inspect / Inspect Element -> Console Tab
Firebug
Note:
UseF12
key on the keyboard to open thedeveloper tools
then click on theConsole Tab
, OR on empty area in browser pageRight Click -> Inspect (Developer Tool) -> Console Tab
. Here You can write basic JavaScript statements and/or valid JavaScript code directly in browser console panel/tab and get the output
<script>.....</script>
tag is used to embed/insert/implement a JavaScript programs/code into any part of an HTML document/page<script>.....</script>
tag specifies that we are using JavaScript<script>.....</script>
element can be placed in the <head>
, or <body>
section of an HTML document<script>.....</script>
tag blocks the page rendering process until it has fully downloaded and executed the JavaScript code
<script>.....</script>
at the bottom/end of body
tag/section ie. just before the closing </body>
tagNote:
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>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-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 here
alert('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>
<head>
section of an HTML page<script>.....</script>
tag blocks the page rendering process until it has fully downloaded and executed the JavaScript code so placing them in the head section (<head> element
of the document without any valid reason will significantly impact your website performanceSyntax & Example:
03.02.01.js.head.html
<head>
<!-- internal JavaScript - head section -->
<script>
// Write all JavaScript code here
alert('welcome to JavaScript written in head section');
</script>
</head>
<body>
section of an HTML page<script>.....</script>
tag ideally, scripts should be placed at the end of the body section
, just before the closing </body> tag
, it will make your web pages load faster since it prevents obstruction of initial page renderingSyntax & Example:
03.02.02.js.body.html
<body>
page content
<!-- internal JavaScript - body section -->
<script>
// Write all JavaScript code here
alert('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>
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 hereextract and separate
our JavaScript behavior code from our HTML markup code<script>
tag with src (source)
attribute:
<script src="path/scriptfile.js"></script>
full URL (absolute path)
or relative path
from the current pagecode re-usability
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 -->
<script src="./03.script.js"></script>
</body>
Syntax & Example -
.js file
:03.02.03.script.js
// external js file
// Write all JavaScript code here
alert('welcome to JavaScript written in external file');
console.log('welcome to JavaScript written in external file');
document.write('<h2>welcome to JavaScript written in external file</h2>');
The syntax of JavaScript is the set of rules
that define a correctly structured JavaScript program. Let's study some of the building blocks of JavaScript code:
<script>.....</script>
tagSemicolon;
so we may write many statements in a line (optional)Semicolon;
Note:
JavaScript statements are composed of:Values, Operators, Expressions, Keywords, and Comments
spaces, tabs, and newlines
that appear in JavaScript programssemicolon; character
most cases
when a line break existsimplicit
semicolon, called an automatic semicolon insertion
Note:
It is a good programming practice to use semicolons; after every statement
var firstName='Dinanath';
and var FirstName='Dinanath';
here firstName & FirstName
are different ie. two different variableNote:
Take care/precautions while writing variable and function names in JavaScript
inside curly brackets {...}
function
Syntax & Example:
03.03.05.script.js
// external js file
// Write all JavaScript code here
// define function - block of code to show welcome message
function sayHello() {
alert('Hello All! Welcome to JavaScript!!');
}
// define function - block of code to show total of two numbers
function showTotal() {
var num1 = 10;
var num2 = 20;
var total = num1 + num2;
alert('Total is : ' + total);
}
// invoke / run / call a function
sayHello();
showTotal();
Usually, JavaScript commands/statements start with a specific keyword
which defines what action/function
should the browser will perform/do:
Keyword | Keyword | Keyword | Keyword | Keyword |
---|---|---|---|---|
break | do ... while | if ... else | try ... catch | const |
continue | for | return | var | class |
debugger | function | switch | let | import |
JavaScript has several reserved keywords. These are the words that you cannot use as identifiers (variable names, function names, and loop labels) in your JavaScript programs. The following list shows the keywords that are reserved in ECMAScript 6
. It also includes keywords that are reserved for future
as well as keywords that are disallowed in strict mode
.
deliver the message (description to code)
for others/for future reference and to understand/follow the code statements/linesWhy and How of code/program/logic
)make code easy to understand
and it avoids the unnecessary code
There are two types of comments in JavaScript:
two forward slash
: // is single comment
//
till the end of the line will be ignored by JavaScript (not be executed)Syntax & Example:
03.05.script.js
// external js file
// Write all JavaScript code here
// show alert box
alert('Welcome to JavaScript!');
var firstName = 'Dinanath'; // variable to store firstName
var lastName = 'Jayaswal'; // variable to store lastName
forward slash and an asterisk, /* and also end with an asterisk and a forward slash */
: /* multi-line comment */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 firstName
var lastName = 'Jayaswal'; // variable to store lastName */
display or built-in print
functionssee the value of a variable
, or write a message to browser console
to help you debug an issue
in your running JavaScript code, and so on(browser window or browser console dialog boxes, writing output into an HTML element, etc.)
alert() or window.alert()
console.log()
document.write()
innerHTML
alert dialog boxes
to display the message or output data to the useralert() or window.alert()
methodSyntax & Example:
04.01.01.script.js
// external js file
// Write all JavaScript code here
alert('I am Dinanath Jayaswal');
window.alert('We are learning JavaScript');
console.log()
methodconsole.log()
function is mainly/widely used for debugging code
as it makes the JavaScript output print to consoleSyntax & Example:
04.01.02.script.js
// external js file
// Write all JavaScript code here
console.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 parsedtesting purposes
Syntax & Example:
04.01.03.script.js
// external js file
// Write all JavaScript code here
document.write('I am Dinanath Jayaswal');
document.write('We are learning JavaScript');
innerHTML
propertydocument.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 element
document.getElementById('mainHeadingText').innerHTML = 'Heading Text change dynamically on run-time';
var paraText = 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.
container to store/hold the data/information
store/hold the data/information temporarily
in computer memoryname of the storage location (named containers/named storage)
for datavar
keywordassignment operator (=)
is used to assign value to a variable, like this: var varName = value;
or var firstName = 'JavaScript';
undefined
(variable is defined but value not assigned: var firstName;
or let lastName; console.log(firstName, lastName);
// undefined)box or an envelope
which we use to organize various kinds of stuff
and put a label
on each box or an envelopelike Maths & Algebra
: x = 10
; and in JavaScript we write var 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 data
var techName = 'JavaScript'; // String literal
var version = 6; // Number literal
var isDone = true; // Boolean literal
console.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 Variables
var techName;
var version;
var isDone;
// Assigning value
techName = 'JavaScript';
version = 6;
isDone = true;
console.log('Learning '+techName+version);
// ------------------------------
// Declaring Variable
var userName;
// Assigning value
userName = 'Dinanath';
console.log('Welcome '+userName);
We can also declare multiple variables
and set their initial values in a single statement, each variable is separated by comma
.
Syntax & Example:
05.01.script.js
// Declaring multiple variables
var techName = 'JavaScript', version = 6, isDone = true;
// Declaring multiple variables in multiple lines for readability
var techName = 'JavaScript',
version = 6,
isDone = true;
console.log('Learning '+techName+version);
// ------------------------------
// Declaring multiple variables
var firstName = '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 be identified
/referred/defined/named with unique names
, called as identifiers
. The naming rules in JavaScript are not much different from any other programming language.
identifiers
)
simply names
in JavaScriptshort names/nick names
(like name, age, num1, isDone, sum) or more descriptive names (firstName, totalDashboards, isSeniorCitizen)The basic rules for defining/assigning names for variables (unique identifiers) are:
start with a letter, underscore (_), or dollar sign ($)
cannot start with a number or special characters
cannot contain spaces
case sensitive
firstName & FirstName
are different ie. two different variableJavaScript keyword or a JavaScript reserved word
meaningful/descriptive names
to variablescamelCase
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)
Syntax & Example:
05.04.script.js
// variables defined to hold different types of data
var _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:
inside block or function
function or blocks only
visible only within a function
where it is definedFunction parameters
are always local to that functionNote:
In the function body, alocal variable takes precedence
over a global variable with the same name.
Syntax & Example:
05.05.01.script.js
// global variable
var globalName = 'Global';
window.alert(globalName);
function showName() {
// local variable
var localName = 'Local';
window.alert(localName);
window.alert(globalName); // recall global variable
}
// invoke/call/run function
showName();
// error - as local variable not exist/available outside of block { }
window.alert(localName);
declared outside the function/at the root
or declared with window object
is known as a global variableSyntax & Example:
05.05.02.script.js
// global variable
var globalName = 'Global';
window.alert(globalName);
function showName() {
// local variable
var globalName = 'Local';
window.alert(globalName);
// define global variable with window
window.globalVersion = 29;
window.alert('global variable from inside function: ' + window.globalVersion);
}
// invoke/call/run function
showName();
// access global variable defined inside function
window.alert('global variable from outside function: ' + window.globalVersion);
ES6 introduces two new keywords let
and const
for declaring variables. The var, let and const
keywords are almost the same, just a few differences with the scope.
var
is used a lot which declares a variable (function-scoped variables)
, but in a slightly different old
way, with scope issueslet
and const
keywords declare variables, scoped at block-level ({})
between a pair of curly brackets {}
ES6
introduces the new let
keyword for declaring variables. Prior to ES6, the only way to declare a variable in JavaScript was the var keyword. Let's see what's the difference:
var
keyword are function-scoped
and can be hoisted
at the top within its scopelet
keyword are block-scoped ({})
and they are not hoistedSyntax & Example:
05.06.01.script.js
// traditional var syntax
var techName1 = 'JavaScript';
for(var i = 1; i <= 5; i++) {
console.log('i : ' + i); // 1,2,3,4,5
console.log('inside block:' + techName1);
var version1 = 100;
}
console.log('outside: ' + i);
console.log('outside: ' + version1);
// ------------------------------
// ES6 syntax
let techName2 = 'LiveScript';
for(let n = 1; n <= 5; n++) {
console.log('n : ' + n); // 1,2,3,4,5
console.log('inside block:' + techName2);
let version2 = 100;
}
console.log(n); // undefined
console.log('outside: ' + version2); // undefined
ES6
introduces the new const
keyword for declaring variables.
const
to declare a constant (read-only / unchanging)
variableread-only
, you cannot reassign new values
to themconst
const
are also block-scoped
like let
object properties
or array elements
Syntax & Example:
05.06.02.script.js
// traditional var syntax
var PI1 = 3.14;
console.log(PI1); // 3.14
PI1 = 100;
console.log(PI1); // 100
// ------------------------------
// ES6 syntax
const PI2 = 6.28;
console.log('ES6 syntax const: ' + PI2); // 6.28
PI2 = 100; // error
A variable in JavaScript can contain any type of data
. Data types specify what kind of data
can be stored and manipulated within the variable in a program. In JavaScript, different data types are available to hold different types of values/data. There are two main categories/types
of data types in JavaScript:
Primitive data types can hold only one value at a time
. Primitives are compared by value
. Two values are strictly equal if they have the same value.
There are different types of primitive data types in JavaScript. They are as follows:
Data Type | Description |
---|---|
String | represent textual data. e.g. "welcome" or 'to javascript' |
Number | represents numeric values e.g. 10, 100.29 |
Boolean | represents boolean value either false or true |
Undefined | represents an undefined value (a variable declared but value not assigned) |
Null | represents null i.e. no value at all |
represent textual data (i.e. sequences of characters)
words/text
"double"
or 'single'
quotes06.02.script.js
var firstName = "Java";
var lastName = 'Script';
multiplication *, division /, addition +, subtraction
, and so onvar age = 25;
var id = 1;
true or false
conditional testing
of codevar isDone = true;
var isMarried = false;
“value is not assigned”
not assigned a value
without a value
, The type is also undefinedvar firstName;
var country;
“ nothing”, “empty” or “value unknown”
var firstName = null;
var id = null;
collections of values and more complex entities
reference
instead of valueThere 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:
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, booleansame variable can be used to hold different data types
Syntax & Example:
06.04.script.js
let name = 'JavaScript';
name = false;
name = 100;
alert(name);
alert(typeof(name));
type of the argument
type of data a variable
or operand contains(typeof(x)
or typeof x
Syntax & Example:
06.05.script.js
// use typeof to find data type of variables
// Strings
alert(typeof "Hello"); // "string"
alert(typeof '12'); // "string"
// Numbers
console.log(typeof(100)); // "number"
console.log(typeof(100.29)); // "number"
// Booleans
alert(typeof true); // "boolean"
alert(typeof(1 == 2)); // "boolean"
// Undefined
console.log(typeof undefined); // "undefined"
var init;
console.log('type of init: ' + typeof init); // "undefined"
// Null
console.log(typeof null); // "object"
var initObject = null;
console.log('type of initObject: ' + typeof initObject); // "object"
// Objects
alert(typeof {name: 'Dinanath', age: 35}); // "object"
alert(typeof document); // "object"
alert(typeof window); // "object"
// Arrays
var techArray = [];
console.log('type of techArray: ' + typeof techArray); // "object"
console.log(typeof ['JavaScript', 'jQuery', 'Angular']); // "object"
console.log(typeof ['Dinanath', 35, 'India']); // "object"
// Functions
console.log(typeof function(){}); // "function"
console.log(typeof alert); // "function"
console.log(typeof window.alert); // "function"
// Symbol
alert(typeof Symbol("dob")); // "symbol"
input in the form, its data type is a string by default
, so do any calculations we need to parse
to integer/int or the number
Syntax & Example:
// Number to String conversion
let num1 = 100;
console.log(num1);
console.log(typeof num1);
console.log(num1.length); //error as number type variables does not have length
num1 = String(num1);
console.log(num1);
console.log(typeof num1);
console.log(num1.length);
// Boolean to String conversion
let boolValue1 = String(false);
console.log(boolValue1);
console.log(typeof boolValue1);
// Date to String conversion
let curDate = String(new Date());
console.log(curDate);
console.log(typeof curDate);
// Array to String conversion
let numArray = String([1,2,3,4,5]);
console.log(numArray);
console.log(typeof numArray);
// toString() method
let curString = (1000).toString
let curString = (true).toString
// String to Number conversion
let num2 = '100';
console.log(num2);
console.log(typeof num2);
console.log(num2.toFixed(2)); //helps to fix decimals - error as string type variables does not have any properties or methods related to number
num2 = Number(num2);
console.log(num2);
console.log(typeof num2);
console.log(num2.toFixed(2));
// Boolean to Number conversion
let boolValue2 = Number(false);
// parseInt() method
let curNumber = parseInt('100');
let curNumber = parseFloat('100.41');
Syntax & Example:
const num1 = '20';
const num1 = 10;
const sum = (num1) + (num2);
console.log(sum);
console.log(typeof sum);
perform some sort of actions
Note:
Let us take a simple expressionvar sum = 1 + 2
;
operands
and=
& +
are called the operator
= is the assignment
operator, + is the arithmetic
operatorSyntax & Example:
07.01.script.js
// Lets take a look on simple expression
var sum = 1 + 2;
// Here 1 and 2 are called `operands` and
// `=` & `+` are called the `operator`
// `= is the assignment` operator, `+ is the arithmetic` operator
JavaScript supports the following types of operators:
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 operators
var num1 = 10;
var num2 = 4;
alert('Addition ' + (num1 + num2)); // 14
alert('Subtraction ' + (num1 - num2)); // 6
alert('Multiplication ' + num1 * num2); // 40
alert('Division ' + num1 / num2); // 2.5
alert('Modulus reminder ' + num1 % num2); // 2
num1++
alert('after Increment ' + num1); // 11
num2--;
alert('after Decrement ' + num2); // 3
num1 = 10;
num2 = 4;
alert('Exponentiation ' + (num1 ** num2)); // (10 ** 4) = 10* 10 * 10 * 10 = 10000
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 operators
var num1 = 10;
var num2 = 20
// old methodology
// num1 = num1 + num2;
// console.log(num1); // 30
// new techniques
num1 += num2;
console.log(num1); // 30
// num2 -= num1;
// console.log(num2); // 10
// num1 *= num2;
// console.log(num1); // 200
// num2 /= num1;
// console.log(num2); // 2
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 true
console.log('true && true: ', true && true);
console.log('true && false: ', true && false);
console.log('false && true: ', false && true);
// ------------------------------
// || (Logical OR) - returns true if one of the operand is true
console.log('true || true: ', true || true);
console.log('true || false: ', true || false);
console.log('false || true: ', false || true);
// ------------------------------
// ! (Logical NOT) True if operand is not true (means I will be true if other is false)
var isSeniorCitizen = true;
var isYoungGeneration = !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)
var isEarningHighIncome = true;
var isGoodCibilScore = false;
var isEligibleForLoan;
// check eligibility with && Logical AND operator
isEligibleForLoan = isEarningHighIncome && isGoodCibilScore;
alert('isEligibleForLoan: ' + isEligibleForLoan);
// check eligibility with || Logical OR operator
isEligibleForLoan = isEarningHighIncome || isGoodCibilScore;
alert('isEligibleForLoan: ' + isEligibleForLoan);
// ! Logical NOT
var isLoanRefused = !isEligibleForLoan;
alert('isLoanRefused: ' + isLoanRefused);
JavaScript supports the following Comparison (or Relational) operators (List of Comparison (or Relational) operators):
Operators | Description | Example / Result |
---|---|---|
== (Loose Equality Operator) |
Is equal to / identical | x == y (True if x is equal to y) |
=== (Strict Equality Operator) |
Eqaul/identical value and identical type | x === y (True if x is equal to y, and they are of the same type) |
!= | Not equal to / different | x != y (True if x is not equal to y) |
!== | Not identical / different value or different type | x !== y )True if x is not equal to y, or they are not of the same type) |
< | Less than | x < y (True if x is less than y) |
> | Greater than | x > y (True if x is greater than y) |
<= | Less than or equal to | x <= y (True if x is less than or equal to y) |
>= | Greater than or equal to | x >= y (True if x is greater than or equal to y) |
Syntax & Example:
07.05.script.js
// Comparison (or Relational) operators
var num1 = 25;
var num2 = 35;
var num3 = "25";
alert(num1 == num3); // true
alert(num1 === num3); // false
alert(num1 != num2); // true
alert(num1 !== num3); // true
alert(num1 < num2); // true
alert(num1 > num2); // false
alert(num1 <= num2); // true
alert(num1 >= num2); // false
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 category
var currentAge = 100;
var category;
category = (currentAge < 18) ? 'Minor' : 'Major';
alert('AGE category: ' + category);
// fees category
var isAuthorisedMember = true;
var fees;
fees = (isAuthorisedMember == true) ? 5 : 10;
alert('fees / charges: ' + fees);
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 Operators
var message1 = "Hello";
var message2 = " World!";
alert(message1 + message2); // Outputs: Hello World!
message1 += message2;
alert(message1); // Outputs: Hello World!
execution order is defined by their precedence
, or the implicit priority order of operatorsorder in which operations are performed
parentheses ()
are computed firstcomputed from left to right
Syntax & Example:
07.08.script.js
// Operator precedence
var result1 = 10 + 2 * 5
alert('10 + 2 * 5 = ' + result1); // answer is 20 NOT 60 (12 * 5 ), actually * or multiplication have higher precedence so the actual calculation is like 10 + ( 2*5 ) = 10 + 10 = 20
// change precedence with `parentheses ()`
var result2 = (10 + 2) * 5;
alert('(10 + 2) * 5 = ' + result2); // (12) * 5 = 60
// same precedence operators
var result3 = 10 + 5 - 2
alert('10 + 5 - 2 = ' + result3); // 13 first addition than subtraction
var result4 = 10 + (5 - 2);
alert('10 + (5 - 2) = ' + result4); // 13 first subtraction ie. ( ) than addition
group of statements that perform specific tasks/operations
create reusable code packages
which are more portable and easier to debugdivide a big program
into a number of/several small and manageable functionsmodular codes
MODULES, SUBROUTINES(SUB-ROUTINES)
function
keywordNote:
Best Practice - First Define function than call/envoke it!
function keyword
,unique function name
,parameters in parentheses
i.e. () (that might be empty),curly braces { }
Syntax & Example:
08.01.script.js
//1. define / declare / create function
function showMessage () {
//Body of function
//code to be executed
console.log('welcome to JavaScript function');
alert('welcome to JavaScript function');
}
function name followed by a set of parentheses, like functionName()
Syntax & Example:
08.01.script.js
//2. invoke / call the function
showMessage();
Function denotes an action/task
. The function name should be brief, as accurate as possible and describe
what the function does, like a verb
.
Usually, Function name starts with:
Examples of function names:
Syntax & Example:
08.02.01.script.js
var name = 'Dinanath';
//1. define / declare / create function
function sayHello () {
//Body of function
//code to be executed
console.log('Hello ' + name);
alert('Hello ' + name);
}
//2. invoke / call the function
sayHello();
Syntax & Example:
08.02.02.01.script.js
// Parameterized function
//1. define / declare / create function
function sayHello (name) {
//Body of function
//code to be executed
console.log('Hello ' + name);
alert('Hello ' + name);
}
//2. invoke / call the function
sayHello('Dinanath');
sayHello('Dino');
// ------------------------------
var total;
function calculateSum (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 function
function sayHello (name = 'User') {
//Body of function
//code to be executed
console.log('Hello ' + name);
alert('Hello ' + name);
}
//2. invoke / call the function
sayHello();
sayHello('Amber');
// ------------------------------
var total;
function calculateSum (num1=1, num2=2) {
total = num1 + num2;
console.log(total);
}
calculateSum();
calculateSum(100, 200);
return a value
back to the script that called the function, as a result, using the return statement
Syntax & Example:
08.02.03.script.js
// Return type function
//1. define / declare / create function
function getSum (num1, num2) {
//Body of function
//code to be executed
var sum = num1 + num2;
return(sum);
}
//2. invoke / call the function
console.log(getSum(10,20));
console.log(getSum(100,200));
var total = getSum(50,50);
alert(total);
The syntax that we've used before to create functions is called function declaration
. There is another syntax for creating a function that is called a function expression
and Immediately invoked function expression (IIFE)
Syntax & Example:
08.03.02.01.script.js
// function declaration (Regular / normal function)
function getSum1(num1, num2) {
var total = num1 + num2;
return total;
}
// ------------------------------
// function expression - Anonymus
var getSum2 = function(num1, num2) {
var total = num1 + num2;
return total;
};
alert(getSum2(10,20));
// ------------------------------
// assign function to another variable
var sum1 = getSum2;
alert(sum1(100,200));
Syntax & Example:
// function expression - named
var getSum2 = function getTotal(num1, num2) {
var total = num1 + num2;
return total;
};
alert(getSum2(10,20));
// ------------------------------
// assign function to another variable
var sum1 = getSum2;
alert(sum1(5,10));
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:
const firstName = 'Dinanath';
const lastName = 'Jayaswal'
const fullName = (firstName) + (lastName);
console.log(fullName);
console.log(typeof fullName);
// concatenation
console.log(firstName + ' ' + lastName);
console.log('Hello ' + firstName + ' ' + lastName + 'Welcome to JavaScript!');
// append
let name1 = 'Dinanath ';
let name1 += 'Jayaswal';
console.log(name1);
// concat() method
console.log(firstName.concat(' ', lastName));
// length
console.log(firstName.length);
// change case
console.log(firstName.toLowercase());
console.log(firstName.toUppercase());
// escaping
// let statement1 = 'wait I'm coming, that's good';
let statement1 = "wait I'm coming, that's good";
let statement2 = 'wait I\'m coming, that\'s good';
// string array - get specific character from string like an array
console.log(firstName[0]);
// indexOf
console.log(firstName.indexOf('i'));
console.log(firstName.lastIndexOf('a'));
// charAt()
console.log(firstName.charAt(2));
// get last character from string
console.log(firstName.charAt(firstName.length - 1));
// replace();
let replaceString = ('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 backside
console.log(firstName.slice(-2));
// includes();
let message2 = 'Hello Dinanath, welcome to JavaScript';
console.log(message2.includes('Hello'));
console.log(message2.includes('Hi'));
// split()
let message2 = 'Hello Dinanath, welcome, to JavaScript';
console.log(message2.split(','));
console.log(message2.split(' '));
let courses = 'html5, css3, javascript, angular';
console.log(courses.split(','));
ES6 new feature Strings Template
offers a convenient way to work with string concatenation/interpolation
Template literals provide an easy and clean way to create multi-line strings and perform string interpolation
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 required
The 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 approach
let user = 'Dinanath';
let greetMessage1 = 'Welcome' + ' ' + user + ' ' + 'to JavaScript.';
console.log(greetMessage1);
console.log('// ------------------------------');
const firstName = 'Dinanath';
const lastName = 'Jayaswal'
const course = 'JavaScript'
const fullName = `Hey ${firstName} ${lastName} Welcome to ${course}.`
console.log('// ------------------------------');
//ES6 Template Literals (Template Strings) approach
let greetMessage2 = `Hello ${firstName}, How are you?`;
console.log(greetMessage2);
console.log('// ------------------------------');
// ------------------------------
//ES6 multi-line string
let greetMessage3 = `ES6 Template Literals (Template Strings):
With Template Literals (Template Strings)
we can add multiple lines in string concatenation/interpolation
`;
console.log(greetMessage3);
let greetMessage4 = ES6 Template Literals (Template Strings):
With Template Literals (Template Strings)
we can add multiple lines in string concatenation/interpolation
;
console.log(greetMessage4);
same block of code again, with a different value, until a certain condition is met
automate the repetitive tasks within a program to save time and effort
code compact
For
loop is used to run a piece of code a set amount of times
counter reach a specified number
repeats a block of code until a certain condition
is meti = index
is used for loop initializationSyntax & 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 (let i=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 order
for (let i = 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 number
for (let i = 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);
} */
}
Syntax & Example:
09.02.01.script.js
// while loop
/*while(condition) {
// Code to be executed
}*/
let i = 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++;
}
condition check happens at the end of the loop
executed at least once (before checking if the condition is true)
, even if the condition is falseSyntax & Example:
09.03.01.script.js
// do...while loop
/*do {
// Code to be executed
}
while(condition);*/
let i = 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);
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 elements
let arrColors = ["Red", "Green", "Blue", "Cyan", "Magenta", "Yellow", "Black"];
// Loop through all the elements in the array
for (let color in arrColors) {
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 properties
let objEmployee = {'emp_name': 'Dinanath', 'emp_addres': 'Mumbai', 'emp_id': '029', 'emp_age':35};
// Loop through all the properties in the object
for (emp in objEmployee) {
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, navigator
for (props in window) {
// alert('document object properties ' + props);
document.write('<li>document object properties ' + props + '</li>');
console.log('document object properties ' + props);
}
iterable objects such as arrays, strings
, etc.Syntax & Example:
09.05.01.script.js
// for...of loop
/*for(element in array/string) {
// Code to be executed
} */
// Iterating over an array
let arrDays = ["Monday", "TuesDay", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
for (let day of arrDays) {
console.log(day);
document.write('<li>' + day + '</li>');
}
// Iterating over string
let name = 'JavaScript';
for (let letter of name) {
document.write(letter + ',');
console.log(letter + ',');
}
break
and continue
keywords/statement can change how the loop behaves
break
and continue
keywords can be used in all loops to stop or continue the loopbreak
statement is used to exit a loop early, to "jump out" of a loop, stops executing/running a loopcontinue
statement tells the interpreter to immediately start the next iteration of the loop and skip the remaining code blockSyntax & Example:
09.06.01.script.js
// break continue statement
/* break */
let arrDays = ["Monday", "TuesDay", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
let i = 1;
while (i <= 10) {
if (i == 5) {
break;
}
console.log(i);
i++
}
console.log('// ------------------------------');
for (let i = 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 body
i + 100; // non of use
console.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 body
console.log('just after 5 continue...'); // non of use
}
console.log(i);
}
console.log('// ------------------------------');
for(let int = 0; int < 10; int++) {
if(int === 2) {
console.log('2 is favorite EVEN number');
continue;
}
if(int === 5) {
console.log('at 5 stop the loop');
break;
}
console.log('current Number is:', int);
}
Syntax & Example: ``
let arrDays = ["Monday", "TuesDay", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
arrDays.forEach(function(day)){
console.log(day);
}
only if the specified condition evaluates to true
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
}
*/
let user = '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 + '!');
}
// ------------------------------
let age = 20;
if (age >= 18) {
console.log('MAJOR! Eligible for Voting');
window.alert('MAJOR! Eligible for Voting');
}
// ------------------------------
let currentHours = 10;
if(currentHours < 12) {
console.log('Good Morning!');
window.alert('Good Morning!');
}
if(currentHours >=6 && currentHours < 12) {
console.log('Good Morning!');
window.alert('Good Morning!');
}
if...else statement
is used to execute the code weather condition is true or false
else
statement to the if
statementNote:
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
}*/
let user = 'Ambar';
if (user == 'Dinanath') {
console.log('Welcome Dinanath!');
window.alert('Welcome Dinanath!');
} else {
console.log('Welcome Guest!');
window.alert('Welcome Guest!');
}
// ------------------------------
let age = 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');
}
// ------------------------------
let currentHours = 10;
if(currentHours < 12) {
console.log('Good Morning!');
window.alert('Good Morning!');
} else {
console.log('Good Evening!');
window.alert('Good Evening!');
}
if...else if...else
a special statement that is used to combine multiple if...else statements
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
}*/
let num1 = 200;
let num2 = 100;
if (num1 == num2) {
console.log('Both numbers are equal');
} else if (num1 < num2 ) {
console.log('Number2 is greater!');
} else {
console.log('Number1 is greater!');
}
// ------------------------------
let age = 15;
if (age >= 60) {
console.log('SINIOR CIRIZEN!');
} else if (age < 18) {
console.log('MINOR!');
} else {
console.log('MAJOR - Middle Age!');
}
// ------------------------------
let currentHours = 15;
if(currentHours >=6 && currentHours< 12) {
console.log('Good Morning!');
window.alert('Good Morning!');
} else if (currentHours >12 && currentHours <=18) {
console.log('Good AfterNoon!');
window.alert('Good AfterNoon!');
} else {
console.log('Good Evening!');
window.alert('Good Evening!');
}
case
and the value of condition
and if the case matches, the subsequent block is executed and if none of the case matches default block
is executedNote:
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
} */
let grade = 'B'; // A.B,C, or something
switch (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;
}
// ------------------------------
let sweets = ''; //cake, chocolates, biscuits
switch (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;
}
// ------------------------------
const color = '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;
}
// ------------------------------
let currentDate = new Date();
let currentDay;
switch(currentDate.getDay()) {
case 0:
currentDay = 'Sunday';
break;
case 1:
currentDay = 'Monday';
break;
case 2:
currentDay = 'Tuesday';
break;
case 3:
currentDay = 'Wednesday';
break;
case 4:
currentDay = 'Thursday';
break;
case 5:
currentDay = 'Friday';
break;
case 6:
currentDay = 'Saturday';
break;
}
console.log(`Today is ${currentDay}!`);
consists of / stores multiple values
square brackets [ ]
and with new
keywordcommas,
zero-indexed
i.e. the first element of an array is at index/position 0ordered collection
, where we have a 0th, 1st, a 2nd, and so on elementselement
) in an array has a numeric position
, known as its index
, starts from 0
, so that the first array element position/index is arr[0]
not arr[1]There are 3 main ways to construct an array:
comma-separated list of values in square brackets [ ]
Syntax & Example:
11.02.01.script.js
// create array with array literal ie. [] square bracket
// var myArray = [element0, element1, ..., elementN];
var arrColors = ['Red', 'Green', 'Blue', 'Orange'];
console.log(arrColors); // show all elements
// ------------------------------
var arrCities = ['Delhi', 'Mumbai', 'Kolkota','Bengaluru','Chennai'];
console.log(arrCities[1]); // show 1st index ie. 2nd positioned element
// ------------------------------
var arrTechnologies = [];
arrTechnologies[0] = 'Java';
arrTechnologies[1] = 'Python';
arrTechnologies[2] = 'C';
console.log(arrTechnologies);
console.log('Total Elements: ' + arrTechnologies.length);
new
keyword)new
keyword new Array()
Syntax & Example:
11.03.01.script.js
// create array with new keyword
// var myArray = new Array();
var arrColors = new Array();
arrColors[0] = 'Red'
arrColors[1] = 'Green'
arrColors[2] = 'Blue'
arrColors[3] = 'Orange'
console.log(arrColors); // show all elements
// read/get array items/elements
for (let i = 0; i < arrColors.length; i++) {
alert(arrColors[i]);
}
// ------------------------------
var arrCities = Array();
arrCities[0] = 'Delhi';
arrCities[1] = 'Mumbai';
arrCities[2] = 'DeKolkotalhi';
arrCities[3] = 'Bengaluru';
arrCities[4] = 'Chennai';
console.log(arrCities); // show all elements
// ------------------------------
var arrTechnologies = new Array();
// add new array items/elements
for (let i = 0; i <= 5; i++) {
arrTechnologies[i] = 'JavaScript';
}
console.log(arrTechnologies); // show all elements
new
keyword)new
keyword new Array() passing arguments
in constructor so that we don't have to provide value explicitlySyntax & Example:
11.04.01.script.js
// create array with new keyword Array constructor passing parameter
// var myArray = new Array(element0, element1, ..., elementN);
var arrColors = new Array('Red', 'Green', 'Blue', 'Orange');
console.log(arrColors); // show all elements
// ------------------------------
var arrCities = new Array('Delhi', 'Mumbai', 'Kolkota','Bengaluru','Chennai');
console.log(arrCities); // show all elements
// ------------------------------
var arrJsFrameworks = new Array('jQuery','Angular','React','Node','Vue','Express','D3');
console.log(arrJsFrameworks); // show all elements
length
property returns the length of an array
, total number of elements
in an arraylength
property brings back an array length - the fixed amount of items
stored in the array(Array length = last array index + 1)
4,294,967,295
Syntax & Example:
11.05.01.script.js
// get/retrieve/find array length
// myarray.length
var arrColors = new Array('Red', 'Green', 'Blue', 'Orange');
console.log(arrColors.length);
// ------------------------------
var arrCities = new Array('Delhi', 'Mumbai', 'Kolkota','Bengaluru','Chennai');
console.log(arrCities.length);
// ------------------------------
var arrJsFrameworks = new Array('jQuery','Angular','React','Node','Vue','Express','D3');
console.log(arrJsFrameworks.length);
index using the square bracket notation ie. [index]
zero-indexed
i.e. the first element of an array is at index/position 0ordered collection
, where we have a 0th, 1st, a 2nd, and so on elementselement
) in an array has a numeric position
, known as its index
, starts from 0
, so that the first array element is arr[0]
not arr[1]for loop
in coordination with array length
property to access each element of an array in sequential orderSyntax & Example:
11.06.01.script.js
// access/loop through array element
// myarray[indexNumber], myarray[0]
var arrColors = new Array('Red', 'Green', 'Blue', 'Orange');
console.log(arrColors[0]); // Red
console.log(arrColors[2]); // Blue
// ------------------------------
var arrCities = new Array('Delhi', 'Mumbai', 'Kolkota', 'Bengaluru', 'Chennai');
console.log(arrCities[1]); // Mumbai
console.log(arrCities[4]); // Chennai
// ------------------------------
var arrJsFrameworks = new Array('jQuery', 'Angular', 'React', 'Node', 'Vue', 'Express', 'D3');
console.log(arrJsFrameworks[3]); // Node
console.log(arrJsFrameworks[5]); // Express
// Loop through an Array Elements
for (let i = 0; i < arrJsFrameworks.length; i++) {
document.write('<li>'+arrJsFrameworks[i] + '</li>');
}
array[index] and value
ie. myarray[5]='value'
index exists it will simply edit
the old value and update the array else it will add an element to the arraypush()
method add a new element at the end of an array
unshift()
method add a new element at the beginning of an array
Syntax & Example:
11.07.01.script.js
// add/edit array element
// myarray[indexNumber]='value', myarray[2]='value', myarray.push('value'), myarray.unshift('value')
var arrColors = new Array('Red', 'Green', 'Blue', 'Orange');
console.log(arrColors);
console.log('arrColors.length: ' + arrColors.length);
// add an element at the end of the array
arrColors.push('Cyan');
console.log(arrColors);
console.log('arrColors.length: ' + arrColors.length);
// add multiple elements at the end of the array
arrColors.push('Magenta','Yellow');
console.log(arrColors);
console.log('arrColors.length: ' + arrColors.length);
// ------------------------------
// add multiple elements at the start of the array
arrColors.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()
method remove the last element
from an arrayshift()
method remove the first element
from an arrayNote:
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()
var arrColors = new Array('Red', 'Green', 'Blue', 'Orange');
console.log(arrColors);
console.log('arrColors.length: ' + arrColors.length);
// remove an element from the end of the array
arrColors.pop();
console.log(arrColors);
console.log('arrColors.length: ' + arrColors.length);
// ------------------------------
// remove an element from the start of the array
let startElement = arrColors.shift();
console.log(startElement);
console.log(arrColors);
console.log('arrColors.length: ' + arrColors.length);
Syntax & Example: ``
// length
var arrColors = new Array('Red', 'Green', 'Blue', 'Orange');
console.log(arrColors.length);
// isArray() - check if array (check the type of variable is array)
var arrCities = new Array('Delhi', 'Mumbai', 'Kolkota','Bengaluru','Chennai');
console.log(Array.isArray(arrCities));
console.log(Array.isArray('I am Dinanath'));
// indexOf() - get index/location of provided value
var arrJsFrameworks = new Array('jQuery','Angular','React','Node','Vue','Express','D3');
console.log(arrJsFrameworks.indexOf('React'));
// splice values
console.log(arrJsFrameworks.splice(1,3)));
// reverse array
console.log(arrJsFrameworks.reverse()));
// concatenate array
let newArray = arrColors.concat(arrCities);
// sort
let newSortedColorsArray = arrColors.sort();
console.log(newSortedColorsArray);
console.log(numberArray.sort());
/* exact ascending sort
let sortedValues = numberArray.sort(function(num1,num2){
return num1 - num2;
})
*/
/* exact descending sort
let sortedValues = numberArray.sort(function(num1,num2){
return num2 - num1;
})
*/
// find
console.log(numberArray.find(40));
everything is an object
.
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
object-based language
and in JavaScript, almost everything is an object or acts like/as an objectspecial/complex
data type that allows you to store collections of data
data, properties, and behaviors
under one roof (group related variables)named values referred to as properties
of the objectcurly braces { }
, the properties of an object are written in pairs (propertyName: value
)key-value pair
(Objects are a collection of key-value pair
)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 objectsobject.firstName
object['firstName']
There are 3 main ways to construct an object:
instance
of Object directly (using new
keyword)Object constructor
(using new
keyword)comma-separated list of properties:values and methods in curly braces { }
Syntax & Example:
// create object with object literal
// var MyObject = { property1: value1, property2: value2.....propertyN: valueN }
// empty object
var HumanObj = {};
console.log(HumanObj);
console.log('// ------------------------------');
// object with properties
var TechnologyObj = { '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 quotes
var VehicleObj1 = {
'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 quotes
var VehicleObj2 = {
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('// ------------------------------');
new
keyword new Array() with or without passing arguments/properties-methods
in constructorSyntax & Example:
// create object with new keyword
// var MyObject = new Object(); OR var MyObject = Object();
// object with properties
var TechnologyObj = new Object();
TechnologyObj.name = 'JavaScript';
TechnologyObj.version = 6;
TechnologyObj.type = 'script';
TechnologyObj.isStable = true
console.log(TechnologyObj.name);
console.log(TechnologyObj['type']);
console.log('// ------------------------------');
// object properly alignment/arranged for readability - with quotes
var VehicleObj1 = {
'type': 'LWM',
'brand': 'Maruti',
'model': 'Alto-100',
'color': 'red',
'isHighEndModel': true,
'price': 400000,
keyStart: function () {
console.log(this.model + ' started!');
}
}
// access property with .DOT notation
console.log(VehicleObj1.brand);
// access property with []Bracket notation
console.log(VehicleObj1['color']);
VehicleObj1.keyStart();
console.log('// ------------------------------');
// object properly alignment/arranged for readability - without quotes
var VehicleObj2 = {
type: 'LWM',
brand: 'Tata',
model: 'Safari',
color: 'White',
isHighEndModel: false,
price: 1400000,
keyStart: function () {
alert(this.model + 'started!');
}
}
// access property with .DOT notation
console.log(VehicleObj2.brand);
// access property with []Bracket notation
console.log(VehicleObj2['color']);
VehicleObj1.keyStart();
console.log('// ------------------------------');
this
keyword, this
keyword refers to the current object
Syntax & Example:
// create an object with new keyword - Object constructor with function
function Technology(name, version, type) {
this.name = name;
this.version = version;
this.type = type;
console.log(this.name);
console.log(this.type);
}
let JavaScript = new Technology('JavaScript', 6, 'Script Language');
console.log(JavaScript.version);
console.log('// ------------------------------');
function Vehicle(brand,model,color,price) {
this.brand = brand;
this.model = model;
this.color = color;
this.price = price;
this.keyStart = function () {
console.log(this.model + ' started!');
}
}
var Maruti = new Vehicle('Maruti','Alto-100','White',400000);
Maruti.keyStart();
console.log('// ------------------------------');
dot .
, or square bracket []
notationkey-value pairs
of an object using the for...in loop
Syntax & Example:
// access/loop thourgh array element
// MyObject.propertyName; OR MyObject[propertyName]; OR MyObject['propertyName']
var Person = {
name:'Dinanath',
domain:'IT/Software',
gender:'Male',
city:'Mumbai',
country:'India'
}
console.log(Person.name);
console.log(Person['domain']);
console.log('// ------------------------------');
// Loop through an Array Elements
for (props in Person) {
console.log(Person[props])
}
console.log('// ------------------------------');
delete
operator can be used to completely remove properties from an objectNote:
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;
var Person = {
name:'Dinanath',
domain:'IT/Software',
gender:'Male',
city:'Mumbai',
country:'India'
}
delete Person.name
console.log(Person);
console.log(Person.name);
console.log(Person['domain']);
In JavaScript we have two categories of types:
Syntax & Example:
???
available in the browser environment
, represents the browser window in which the script is runningrepresents a window in a browser
The Browser Object Model (BOM)
), it is not the object of javascriptBrowser -> Inspect Element -> Console Panel
-> Type Window
, check different properties and methods availableSyntax & Example:
// Methods
window.console.log('Console! Hello, Welcome to JavaScript');
window.alert('Alert! Hello, Welcome to JavaScript');
// const namePrompt = window.prompt();
const namePrompt = 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 & width
outerHeight = window.outerHeight;
outerWidth = window.outerWidth;
console.log('outerHeight -', outerHeight, '::', 'outerWidth -', outerWidth );
// document/page height & width
innerHeight = window.innerHeight;
innerWidth = window.innerWidth;
console.log('innerHeight -', innerHeight, '::', 'innerWidth -', innerWidth );
// scroll position
console.log('scrollY', window.scrollY);
console.log('scrollX', window.scrollX);
// location
console.log('current window location/url', window.location);
console.log('current window location/url', window.location.href);
// location redirect
window.location.href = 'https://www.google.com';
// window location/visited history
window.history.go(-1);
let totalPagesVisitedHistory = window.history.length;
// current browser details - navigator
let curBrowser = window.navigator.appName;
//window.navigator.userAgent;
window.navigator.platform;
window.navigator.vendor;
min, max, sqrt, pi, round, random
, etc)Syntax & Example:
let pieValue = 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 number
console.log(Math.pow(8,2)); //64
console.log(Math.pow(10,3)); //10 * 10 * 10 = 1000
console.log(Math.min(20, 5, 9, 15, 2));
console.log(Math.max(20, 5, 9, 15, 2));
console.log(Math.random());
console.log(Math.random() * 20 + 1); // random number till 20
console.log(Math.floor(Math.random() * 20 + 1)); // random number till 20 without any decimals
new Date()
- Date constructor can be used to create date object, It provides methods to get and set day, month, year, hour, minute and secondsSyntax & Example:
const today = new Date();
console.log('today is:', today);
const date1 = new Date('March 29 1980');
const date2 = new Date('09-10-1980');
let currentDate = new Date();
const currentDateToday = currentDate.getDate();
const currentDayToday = currentDate.getDay();
const currentMonth = currentDate.getMonth();
const currentYear = currentDate.getYear();
const currentHours = currentDate.getHours();
const currentMinutes = currentDate.getMinutes();
const newBirthDate = currentDate.setMonth(5);
console.log(newBirthDate);
something has occurred/happened
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 onlisten
for it and supply a callback function or event handler
which will be called by the browser when the event occursIn general, the events can be categorized into four main groups:
A mouse event is triggered when the user clicks some element, move the mouse pointer over an element, etc. Find here some of the important mouse events and their event handler:
onclick
event handler)
mouse clicks on an element
, links, buttons etc. on a web pageoncontextmenu
event handler)
user clicks the right mouse button
on an element to open a context menuonmouseover
& onmouseout
event handler)
onclick/onmousedown
& onmouseup
)
onmousemove
event handler)
Syntax & Example:
<ol class="normalList">
<li><strong>click</strong> (`onclick` event handler) <br/>
<span onclick="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/>
<span oncontextmenu="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/>
<span onmouseover="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/>
<span onmousedown="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/>
<span onmousemove="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
const button = document.querySelector('.some-button');
const headingText = document.querySelector('h1');
button.addEventListener('mousemove', someFunction);
function someFunction(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:
onkeydown
& onkeyup
event handler)
onkeypress
event handler)
Syntax & Example:
<label>Enter Name:</label>
<input type="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:
const nameText = document.querySelector('inputNameText');
nameText.addEventListener('keypress', nameData);
function nameData(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:
onfocus
event handler)
input
text fieldonblur
event handler)
onchange
event handler)
onsubmit
event handler)
Syntax & Example:
<form action="" method="post" onsubmit="alert('Form data submitted to the server!');">
<label>First Name:</label>
<input type="text" name="first-name" onfocus="showHighlight(this)" onblur="resetHighlight(this)" required> <br/> <br/>
<select onchange="console.log('You have selected something!');">
<option>Select</option>
<option>Male</option>
<option>Female</option>
</select> <br/> <br/>
<input type="submit" value="Submit">
</form>
<script>
// focus text field
function showHighlight(curTxtField) {
curTxtField.style.background = "pink";
}
function resetHighlight(curTxtField) {
curTxtField.style.background = "white";
}
</script>
Syntax & Example:
Form submit event
const personalDataForm = document.querySelector('form');
personalDataForm.addEventListener('submit', submitData);
function submitData(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
event handler)
onload
event handler)
onunload
event handler)
onresize
event handler)
Note:
The unload event is not supported properly in most of the browsers.
Syntax & Example:
<body onload="window.alert('Page loaded successfully!');" onunload="window.alert('sure you want to leave this page?');">
<script>
// resize window
window.onresize = resizeWindowSize;
function resizeWindowSize() {
console.log('window.outerWidth ' + window.outerWidth);
console.log('window.outerHeight ' + window.outerHeight);
}
</script>
Syntax & Example:
<h2 onclick="window.alert('HTML attribute onclick used here!')" style="color:#0000ff; cursor:pointer"> 13.03.01. HTML attribute | Click Me!</h2>
<button onclick="alert('Hello world! Welcome to JavaScript Events!!')">Click here...</button>
<button onclick="fnShowMessage()">Invoke Function</button>
// event handler function
function fnShowMessage () {
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:
<button id="messageButton1">Click here...</button>
<button id="messageButton2">Click here...</button>
// DOM element properties
// method - 1
messageButton1.onclick = function () {
console.log('Welcome to event handler!');
alert('Welcome to event handler!');
}
// method - 2
document.getElementById("messageButton2").onclick = fnShowMessage;
function fnShowMessage() {
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:
???
// create an example of nested element
???
Nodes
(elements, its attributes, text, etc.)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 as nodes
.
There are different types of nodes like: Elements, Attribute & Text Node
.
Syntax & Example:
<ul id="list"> --> Element & Attribute NODE
<li>first item </li> --> text NODE
</ul>
* Elements NODES does not contain text
Syntax & Example:
In Browser Window -> Inspect Element (Developer Tools) -> Console: type following and check the output thoroughly
document
- outputs the entire document/current page
document.all
- shows HTMLAllCollection(1532) [html, head, meta (html tags)
document.url
- displays current url/path
HTMLAllCollection(1532) [html, head, meta, link, link, link, link, link, link, link, link, link, meta, title, meta, link, link, meta, meta, meta, meta, meta, meta, meta, meta, meta,
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.
getElementById()
)unique ID
with the getElementById()
methodgetElementById()
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 valueSyntax & Example:
// Selecting element with id
let mainHeadingElement = document.getElementById('mainHeadingText');
// get html of selected element
let mainHeadingHtml = mainHeadingElement.innerHTML;
// get text of selected element
let mainHeadingText = mainHeadingElement.innerText;
alert('mainHeadingHtml: ' + mainHeadingHtml); // text with complete html tags
alert('mainHeadingText: ' + mainHeadingText); // only text
// console.log('// ------------------------------');
// set text of selected element
mainHeadingElement.innerHTML = 'This text changed with DOM method...';
// console.log('// ------------------------------');
// set text of another element
let subHeadingElement = document.getElementById('subHeadingText');
subHeadingElement.innerHTML = mainHeadingElement.innerHTML ;
// console.log('// ------------------------------');
// set css style
mainHeadingElement.style.backgroundColor = 'pink';
getElementsByClassName()
)getElementsByClassName()
method is used to select all the elements having specific class names
getElementsByClassName()
method returns an array of all elements
with given class namesSyntax & Example:
// Selecting elements with class
let listItems = document.getElementsByClassName("list-item");
console.log(listItems);
// get text of 1st ie 0th element
let firstListItemText = listItems[0].innerHTML;
console.log('firstListItemText: ' + firstListItemText);
// console.log('// ------------------------------');
// set text of last element
let lastListItem = (listItems.length - 1);
listItems[lastListItem].style.color = 'blue';
// console.log('// ------------------------------');
// highlighting all list items through loop
for(var listItem in listItems) {
listItems[listItem].style.marginBottom = '10px';
listItems[listItem].style.background = '#bbbbbb';
}
getElementsByTagName()
)select HTML elements by tag name
using the getElementsByTagName()
methodgetElementsByTagName()
method returns an array of all elements
with given tag nameSyntax & Example:
// Selecting all LI elements with tag name
let liElements = document.getElementsByTagName('li');
console.log(liElements);
// console.log('// ------------------------------');
// get total li tags/elements in page
let totalLiElements = liElements.length;
console.log(totalLiElements);
// console.log('// ------------------------------');
// get text of 1st ie 0th li element
let firstLiText = liElements[0].innerHTML;
console.log('firstLiText: ' + firstLiText);
// console.log('// ------------------------------');
// set text of last element
let lastLi = (liElements.length - 1);
liElements[lastLi].style.color = 'blue';
// console.log('// ------------------------------');
// highlighting all li elements through loop
for(var li in liElements) {
liElements[li].style.marginBottom = '10px';
liElements[li].style.background = '#bbbbbb';
}
// console.log('// ------------------------------');
querySelectorAll()
)querySelectorAll()
method find all HTML elements that match a specified CSS selector
(id, class names, types, attributes, values of attributes, etc)powerful and efficient way
of selecting HTML elements in a documentquerySelectorAll()
method returns an array
or list of all the elements that matches the specified selectorsSyntax & Example:
// Selecting all ul -> li elements
let ulLiElement = document.querySelectorAll('ul li');
console.log(ulLiElement);
let ulListItemClass = document.querySelectorAll("ul li.list-item")
console.log(ulListItemClass);
// set color of last li element
ulLiElement[ulLiElement.length - 1].style.color = 'red';
// set text of last li element
ulLiElement[ulLiElement.length - 1].innerHTML = 'Dynamic text change at run time';
querySelector
???
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.
font-size
, background-image
, text-decoration
, etc. contain hyphens (-)
in nameshyphens (-)
is a reserved operator (a minus sign), so it is impossible to write an expression with hyphens (-)
, like: elem.style.font-size = '10px';font-size
, background-color
,border-left-style
becomes the DOM property fontSize
, borderLeftStyle
respectively and so onstyle attribute
, eg. <element style="color:red;">
style property
is used to get or set the inline style of an element, eg. elem.style.color = 'red';
Syntax & Example:
// Selecting element with id
let mainHeadingElement = document.getElementById('mainHeadingText');
// set css style
mainHeadingElement.style.padding = '5px';
mainHeadingElement.style.backgroundColor = 'pink';
mainHeadingElement.style.color = 'blue';
mainHeadingElement.style.border = '5px solid #999999';
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 sheetswindow.getComputedStyle()
methodSyntax & Example:
// Selecting element with id
let mainHeadingElement = document.getElementById('mainHeadingText');
// set css style
mainHeadingElement.style.padding = '5px';
mainHeadingElement.style.backgroundColor = 'pink';
// console.log('// ------------------------------');
// get inline css styles
console.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 sheets
var cssStyles = window.getComputedStyle(mainHeadingElement);
console.log('internal style - color:',cssStyles.color);
console.log('internal style - border:',cssStyles.border);
className property
class
is a reserved word in JavaScript, it uses the className
property to reference the value of the HTML class attributeSyntax & Example:
// Selecting element with id
let mainHeadingElement = document.getElementById('mainHeadingText');
// remove old classes and apply/set css class
mainHeadingElement.className = 'bg-color';
// apply/set css class
mainHeadingElement.className += ' border';
classList property
is much easier and better to get, set or remove CSS classes from an elementclassList property
is supported in all major browsers except Internet Explorer before version 10Syntax & Example:
// Selecting element with id
let mainHeadingElement = document.getElementById('mainHeadingText');
// apply/set/add css class with classList
mainHeadingElement.classList.add('heading-text');
// apply/set/add css class with classList
mainHeadingElement.classList.add('border','bg-color');
// remove classes with classList
mainHeadingElement.classList.remove('border','bg-color');
// if class exists remove it, if not add it
mainHeadingElement.classList.toggle('heading-text');
// mainHeadingElement.classList.add('border');
// check if class exist and act accordingly
if(mainHeadingElement.classList.contains('border')) {
alert('border class present');
} else {
alert('NO border class present');
}
provides extra information
about the element, and it is applied within the start tagname & value / key & value
setAttribute(), getAttribute(), removeAttribute()
setAttribute()
method is used to set an attribute on the specified elementSyntax & Example:
// Selecting element with id
let mainHeadingElement = document.getElementById('mainHeadingText');
let clickButtonElement = document.getElementById('clickButton');
let linkTextElement = document.getElementById('linkText');
// set attribute class named 'btn'
mainHeadingElement.setAttribute('class', 'btn');
// set attribute disabled
clickButtonElement.setAttribute('disabled', '');
// set blank/empty attribute so that it will remove exisiting attribute value
linkTextElement.setAttribute('href','');
getAttribute()
method is used to get the current value of an attribute on the elementnull
Syntax & Example:
// Selecting element with id
let mainHeadingElement = document.getElementById('mainHeadingText');
let clickButtonElement = document.getElementById('clickButton');
let linkTextElement = document.getElementById('linkText');
// getting the attributes values
let getAttrClass = mainHeadingElement.getAttribute('class');
console.log('getAttrClass:', getAttrClass);
let getAttrDisabled = clickButtonElement.getAttribute('disabled');
console.log('getAttrDisabled:', getAttrDisabled);
let getAttrHref = linkTextElement.getAttribute('href');
console.log('getAttrHref:', getAttrHref);
removeAttribute()
method is used to remove an attribute from the specified elementSyntax & Example:
// Selecting element with id
let mainHeadingElement = document.getElementById('mainHeadingText');
let clickButtonElement = document.getElementById('clickButton');
let linkTextElement = document.getElementById('linkText');
// removing the attributes
mainHeadingElement.removeAttribute('class');
// verify/confirm class removed or not
console.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] or use respective form element index
- 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 visit Mozilla JavaScript Reference Guide.
Best of Luck! Happy Learning!