JavaScript for Beginners ===================== JavaScript tutorial for Beginners ===================== JavaScript basics and fundamentals for all ===================== Description JavaScript is a scripting language of the web that allows you to do/add Interactivity with User-Events, implement Conditions and Validations, Dynamic updates in a Web Page, etc.. In this practical course will learn JavaScript…
JavaScript is a scripting language of the web that allows you to do/add Interactivity with User-Events, implement Conditions and Validations, Dynamic updates in a Web Page, etc… In this practical course will learn JavaScript basics-programming fundamentals from scratch. We Will start with what is JavaScript? its uses, history, how to write JavaScript, etc. It will also cover various programming building blocks like variable, functions, array, conditionals, objects, and many more.
Topics (separate with spaces)
Add topics to categorize your repository and make it more discoverable:
javascript-programming-language
javascript-language-fundamentals
javascript-basic-programming
javascript-tutorial
javascript-library
learning-javascript
javascript-programs
variables-var-let-const
conditions
loops
arrays
objects
events
dom-document-object-model
webdevelopment
front-end-development
webprogramming
plain-javascript
vanilla-javascript
javascript-typescript-es6
Prerequisites for current course / What you need to know
To move forward with JavaScript you just need basic knowledge of XHTML/HTML. Here, you will learn how easy it is to add interactivity to a web page using JavaScript. But, before we begin, make sure that you have some working knowledge and/or general understanding of:
Hi All, I’m Dinanath Jayaswal, Senior UI/Web Developer and Adobe Certified Expert Professional, I wanna welcome you to JavaScript for Beginners. In this course, I will take you through with the ins and outs of learning JavaScript. This course will help you to learn the fundamentals of programming with JavaScript scripting language, from the basics to advanced topics step-by-step.
01.02. Who is this for? Audience
This course is for any Web Designer, Developer who is interested in dynamic Web Design and Development / Web Programming with JavaScript. Anyone who wants to make a career in Web Development or planning on being a front-end developer must learn JavaScript.
Section 02. Introducing JavaScript
02.01. Importance
3 pillars / core Languages/Technologies used for Front End Web Design/Development:
HTML (HyperText Markup Language) - Markup language, Essential Page Structure/Content, Readable and convey structure to a user, Text Layout Model, page Mark-up, Text, Tags, Data, details for pages, Images, Tables, Anchor Links, Forms
HTML is an acronym stands for HyperText Markup Language which is used for creating web pages and web applications
HTML is not a programming language; it is a markup language that defines the structure of your content ie. document
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.
Syntax & Example: 02.01.js.intro.html
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><metahttp-equiv="X-UA-Compatible"content="ie=edge"><title>02.01.js.intro.html</title><!-- internal style --><style>/* css selector: { property:value; } */body{font-family: arial;}</style><!-- internal JavaScript - head section --><script>// Write all JavaScript code herealert('welcome to JavaScript');</script></head><body>
Content
<!-- internal JavaScript - body section --><script>/* Write all JavaScript code here */
console.log('welcome to JavaScript');</script></body></html>
02.02. What is JavaScript?
JavaScript 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, and Browser-based Client-Side (user computer) programming language of the web
JavaScript is a dynamic computer programming language. It is an interpreted (translated) programming language with object-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
Note:
Now-a-days with the help of Node (Node.js) JavaScript is used for Back-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.
Image 02.02.01 - Stackoverflow Programming, Scripting, and Markup Languages Survey 2019
Image 02.02.02 - Google Trends - Language Compare
02.03. What is a scripting language?
A high-level programming language that is interpreted by another program at runtime rather than compiled by the computer’s processor as other programming languages
A programming language designed for integrating and communicating with other programming languages
Popular scripting languages 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++
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 like JavaScript or PHP need not be compiled
Scripting is interpreted based language, whereas Java, C, C++, and others are compiler-based language
What is a script?
A script is nothing but sets of instructions
Series of commands
02.04. What can you do with JavaScript?
02.04. Use of JavaScript
For a long time, JavaScript is used only as 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:
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 and CSS 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 and dialog boxes (an alert, confirm and prompt dialog box)
Change the website’s behavior and make it more dynamic with advanced web designs
Perform and control transitions and animations
However, there are more serious uses for javascript:
Browser Detection - Detecting the browser used by a visitor
Cookies - Storing information on the visitor’s computer
Control Browsers - Opening pages in customized windows
Validate Forms - Validating inputs to fields before submitting a form
02.05. Where does the JavaScript code run?
JavaScript was originally designed and developed to run only in browsers. But now with the help of 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.
Common JavaScript Browser Engines
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
02.06. Who are using JavaScript?
JavaScript is used by:
Front-end Developer
Back-end Developer
Full-stack Developer
Big companies and brands build entire applications:
Netflix
Walmart
PayPal
Microsoft
Facebook (React.js)
Google (Angular.js)
Ebay
Uber
Groupon
02.07. History of JavaScript
Invented by “Brandan Eich” 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)
Not at-all related to JAVA (completely different in concept and design)
Microsoft has developed new version of “JavaScript” as "JScript" for IE-3 in 1996
JavaScript Submitted to ECMAScript in 1997
02.08. JavaScript Vs ECMAScript
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)
ECMAScript specification defines many new features for JavaScript
02.09. Types of Script
02.09. Various Scripting languages
02.09. Client-Side Scripting Vs Server Side Scripting
Client-Side 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.
02.10. Prerequisites of using HTML and JavaScript
Tools for building web sites-web pages/writing HTML, CSS & JavaScript
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 (like Visual 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
Google Chrome / Safari – Developer Tools Inspect / Inpsect element (in browser -> Right Click on page -> choose Inspect / Inspect Element -> Console Tab
Mozilla FireFox – Firebug
Note:
Use F12 key on the keyboard to open the developer tools then click on the Console Tab, OR on empty area in browser page Right 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
Image 02.10.01 - Widely used modern browsers
Image 02.10.02 - Developer Tool Inspect Console
Image 02.10.03 - Developer Tool Inspect Console
Section 03. JavaScript Getting Started
03.01. How to write Javascript?
03.01. JavaScript in HTML
The HTML <script>.....</script> tag is used to embed/insert/implement a JavaScript programs/code into any part of an HTML document/page
The <script>.....</script> tag specifies that we are using JavaScript
The <script>.....</script> element can be placed in the <head>, or <body> section of an HTML document
Each <script>.....</script> tag blocks the page rendering process until it has fully downloaded and executed the JavaScript code
So the best practice is to place/add the <script>.....</script> at the bottom/end of body tag/section ie. just before the closing </body> tag
Note:
JavaScript is the default scripting language in HTML. The old HTML standard attributes like type="text/javascript" and language="javascript" no longer required in modern browser
Syntax & Example: 03.01.js.script.tag.html
<head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><metahttp-equiv="X-UA-Compatible"content="ie=edge"><title>03.01.js.script.tag.html</title><!-- internal style --><style>/* css selector: { property:value; } */body{font-family: arial;}</style><!-- internal JavaScript - head section --><script>// Write all JavaScript code herealert('welcome to JavaScript');</script></head><body>
Content
<!-- internal JavaScript - body section --><script>/* Write all JavaScript code here */
console.log('welcome to JavaScript');
document.write('This is dyanamic content. Hello All, Lets write something on web page');</script></body>
03.02. Where to write JavaScript in HTML?
03.02. Where to embed include write put JavaScript in HTML?
JavaScript provides 3 places to write the JavaScript code in our webpage:
Inside the HEAD section
Inside the BODY section
External JavaScript .js file (separation of concern)
03.02.01. Inside the HEAD section (code between the head tag)
JavaScript programs/code/statements can be placed in the <head> section of an HTML page
As each <script>.....</script> tag blocks the page rendering process until it has fully downloaded and executed the JavaScript code so placing them in the head section (<head> element of the document without any valid reason will significantly impact your website performance
Syntax & Example: 03.02.01.js.head.html
<head><!-- internal JavaScript - head section --><script>// Write all JavaScript code herealert('welcome to JavaScript written in head section');</script></head>
03.02.02. Inside the BODY section (code between the body tag)
JavaScript programs/code/statements can be placed in the <body> section of an HTML page
As blocking nature of <script>.....</script> tag ideally, scripts should be placed at the end of the body section, just before the closing </body> tag, it will make your web pages load faster since it prevents obstruction of initial page rendering
Syntax & Example: 03.02.02.js.body.html
<body>
page content
<!-- internal JavaScript - body section --><script>// Write all JavaScript code herealert('welcome to JavaScript written in body section');
console.log('welcome to JavaScript written in body section');
document.write('<h2>welcome to JavaScript written in body section</h2>');</script></body>
03.02.03. External JavaScript .js file (separation of concern)
We can easily write JavaScript code in between 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 with src (source) attribute:
<script src="path/scriptfile.js"></script>
One can provide a full URL (absolute path) or relative path from the current page
We can create a single external JavaScript file and embed it in many/any HTML page which provide code re-usability
03.02.04. Advantages of External JavaScript
It separates HTML and JavaScript code (separation of concern)
Code re-usability
It makes HTML and JavaScript file/code easier to read, maintain and more meaningful/semantic
Web page loads faster /increase the speed of the webpage (Cached JavaScript files)
Note:
Usually, when an external JavaScript file is downloaded for the first time, it is stored in the browser’s cache (like images and style sheets), so it won’t need to be get downloaded multiple times from the web server that makes the web pages load faster/quickly.
Syntax & Example - .html file: 03.02.03.js.external.html
<body>
page content
<!-- include external JavaScript - body section --><scriptsrc="./03.script.js"></script></body>
Syntax & Example - .js file: 03.02.03.script.js
// external js file// Write all JavaScript code herealert('welcome to JavaScript written in external file');
console.log('welcome to JavaScript written in external file');
document.write('<h2>welcome to JavaScript written in external file</h2>');
03.03. JavaScript Code structure
The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program. Let’s study some of the building blocks of JavaScript code:
03.03.01. JavaScript Statements
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
03.03.02. Whitespace and Line Breaks
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)
03.03.03. Semicolons
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 an automatic semicolon insertion
In most cases, a newline implies a semicolon, But “in most cases” does not mean “always”!
Note:
It is a good programming practice to use semicolons; after every statement
03.03.04. Case Sensitivity
JavaScript is a case-sensitive language
in Javascript variables, language keywords, function names, and other identifiers must always be typed with a consistent capitalization of letters
Example: var firstName='Dinanath'; and var FirstName='Dinanath'; here firstName & FirstName are different ie. two different variable
Note:
Take care/precautions while writing variable and function names in JavaScript
03.03.05. JavaScript Code Blocks
JavaScript commands/statements/code can be grouped together in code blocks, inside curly brackets {...}
Grouped statements/lines form code blocks
The purpose of code blocks is to define statements to be executed together like a single JavaScript command
An often occurrence of a code block in JavaScript is a 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(){var num1 =10;var num2 =20;var total = num1 + num2;alert('Total is : '+ total);}// invoke / run / call a functionsayHello();showTotal();
03.04. JavaScript Keywords
Usually, JavaScript commands/statements start with a specific keyword which defines what action/function should the browser will perform/do:
Keyword
Keyword
Keyword
Keyword
Keyword
break
do … while
if … else
try … catch
const
continue
for
return
var
class
debugger
function
switch
let
import
03.04.01. Reserved Keywords
JavaScript has several reserved keywords. These are the words that you cannot use as identifiers (variable names, function names, and loop labels) in your JavaScript programs. The following list shows the keywords that are reserved in ECMAScript 6. It also includes keywords that are reserved for future as well as keywords that are disallowed in strict mode.
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 and it avoids the unnecessary code
03.05.01. Types of JavaScript Comments
There are two types of comments in JavaScript:
Single-line Comments
Multi-line Comments
03.05.01.01. Single-line Comments
Single-line JavaScript comments are used for one line of comment only
Single-line comments starts 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!');var firstName ='Dinanath';// variable to store firstNamevar lastName ='Jayaswal';// variable to store lastName
03.05.01.02. Multi-line Comments
Multi-line comments usually comment out a block of code
Multi-line comments in JavaScript can comment on bigger parts (a few lines) of code
Multi-line comments are more convenient as it can be used to comment single as well as multi-line comments
Multiline comments start 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 firstName
var lastName = 'Jayaswal'; // variable to store lastName */
Section 04. JavaScript Language Fundamentals
04.01. Generating Output
JavaScript does not have any display or built-in print functions
Many times we may need to generate output from your JavaScript code like see the value of a variable, or write a message to browser console to help you debug an issue in your running JavaScript code, and so on
That is why you have to use the JavaScript output function to generating output (browser window or browser console dialog boxes, writing output into an HTML element, etc.)
Using different output methods knowledge will help you while debugging or rewriting your code more conveniently
Different ways to show output/display data
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
04.01.01. Displaying Output in Alert Dialog Boxes: alert() or window.alert()
One can use alert dialog boxes to display the message or output data to the user
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');
04.01.02. Writing Output to Browser Console: console.log()
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 for debugging 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 here
console.log('I am Dinanath Jayaswal');
console.log('We are learning JavaScript');
Note:
Use F12 key on the keyboard to open the developer tools then click on the console tab. You can write basic JavaScript statements directly in the browser console panel/tab and get the output.
04.01.03. Writing Output into the HTML / Browser Window: document.write()
document.write() method is used to write the content to the current document while document is being parsed
Programmers do ues document.write() for testing 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');
04.01.04. Inserting Output Inside an HTML Element: innerHTML
We can write or insert output inside an HTML element using the element’s innerHTML property
First we need to select the element using a method such as document.getElementById(id)
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.
Section 05. Variables
05.01. What is Variable?
Variables are one of the most fundamental concepts in JavaScript and other all programming languages of the world.
A variable 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; or var firstName = 'JavaScript';
By default value of variable defined in JavaScript is undefined (variable is defined but value not assigned: var firstName; or let lastName; console.log(firstName, lastName); // undefined)
Example: Variables are like box or an envelope which we use to organize various kinds of stuff and put a label on each box or an envelope
Example: Variable declaration and assignment is just like 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 with let keyword: let techName = 'JavaScript' ;
Syntax & Example: 05.01.script.js
// variables defined to hold different types of datavar techName ='JavaScript';// String literal var version =6;// Number literalvar isDone =true;// Boolean literal
console.log('Learning '+techName+version);
05.02. Declaring variable without a value
05.02. Creating a variable without a value
Variables can also be declared without having any initial values assigned to them. This is useful for variables that are supposed to hold values like user inputs, calculations, status updates, etc.
Syntax & Example: 05.01.script.js
// Declaring Variablesvar techName;var version;var isDone;// Assigning value
techName ='JavaScript';
version =6;
isDone =true;
console.log('Learning '+techName+version);// ------------------------------// Declaring Variablevar userName;// Assigning value
userName ='Dinanath';
console.log('Welcome '+userName);
05.03. Declaring multiple variables at once
We can also declare multiple variables and set their initial values in a single statement, each variable is separated by comma.
Syntax & Example: 05.01.script.js
// Declaring multiple variablesvar techName ='JavaScript', version =6, isDone =true;// Declaring multiple variables in multiple lines for readabilityvar techName ='JavaScript',
version =6,
isDone =true;
console.log('Learning '+techName+version);// ------------------------------// Declaring multiple variablesvar 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);
05.04. Variable Naming Conventions
05.04. Variable Naming Conventions (Identifiers)
All JavaScript variables must be identified/referred/defined/named with unique names, called as identifiers. The naming rules in JavaScript are not much different from any other programming language.
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)
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
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)
// variables defined to hold different types of datavar _firstName ='JavaScript';var $version =6;var $num_total1 =10;
window.alert('variables details: '+ _firstName +' '+ $version +' '+ $num_total1);// wrong identifiers// var #name;
05.05. Variable Scope
The scope of a variable is the region/coverage of your program in which it is defined and exist/available. JavaScript variables have two scopes:
Local Variables
Global Variables
05.05.01. Local 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, a local variable takes precedence over a global variable with the same name.
Syntax & Example: 05.05.01.script.js
// global variablevar globalName ='Global';
window.alert(globalName);functionshowName(){// local variablevar localName ='Local';
window.alert(localName);
window.alert(globalName);// recall global variable}// invoke/call/run functionshowName();// error - as local variable not exist/available outside of block { }
window.alert(localName);
05.05.02. Global Variables
A variable declared outside the function/at the root or declared with window object is known as a global variable
A JavaScript global variable is accessible from any function
A global variable has a global scope which means it can be defined and accessible anywhere in JavaScript code/program
Syntax & Example: 05.05.02.script.js
// global variablevar globalName ='Global';
window.alert(globalName);functionshowName(){// local variablevar 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 functionshowName();// access global variable defined inside function
window.alert('global variable from outside function: '+ window.globalVersion);
05.06. The let and const keywords ES6
ES6 introduces two new keywords let and const for declaring variables. The var, let and const keywords are almost the same, just a few differences with the scope.
In older programs var is used a lot which declares a variable (function-scoped variables), but in a slightly different old way, with scope issues
Both let and const keywords declare variables, scoped at block-level ({})
Block scoping means that a new scope is created between a pair of curly brackets {}
05.06.01. The let Keyword
ES6 introduces the new let keyword for declaring variables. Prior to ES6, the only way to declare a variable in JavaScript was the var keyword. Let’s see what’s the difference:
Variables declared with the var keyword are function-scoped and can be hoisted at the top within its scope
Variables declared with let keyword are block-scoped ({}) and they are not hoisted
Syntax & Example: 05.06.01.script.js
// traditional var syntaxvar 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 syntaxlet 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
05.06.02. The const Keyword
ES6 introduces the new const keyword for declaring variables.
Use const to declare a constant (read-only / unchanging) variable
Constants are read-only, you cannot reassign new values to them
In Programm/logic when the variable will never change, they can be declared as const
constants are named using capital letters and underscore Example: const NATIVE_CITY
const are also block-scoped like let
However, you can change object properties or array elements
Syntax & Example: 05.06.02.script.js
// traditional var syntaxvarPI1=3.14;
console.log(PI1);// 3.14PI1=100;
console.log(PI1);// 100// ------------------------------// ES6 syntaxconstPI2=6.28;
console.log('ES6 syntax const: '+PI2);// 6.28PI2=100;// error
Section 06. Data types
06.01. Data types
A variable in JavaScript can 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 (Primary or Value) data type
String
Number
Boolean
Undefined
Null
Symbol (newly introduced in ES6)
Non-primitive (Reference or Composite) data type
Array
Object
Function
06.02. Primitive data type
06.02. Primitive, Primary or Value data type
Primitive data types 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
06.02.01. String
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
var firstName ="Java";var lastName ='Script';
06.02.02. Number
The number data type simply defined without quotes is used to represent positive or negative numbers with or without a decimal place
Many mathematical operations can be done on numbers, e.g. multiplication *, division /, addition +, subtraction, and so on
Example:
var age =25;var id =1;
06.02.03. Boolean
The Boolean data type can hold only two values: true or false
true = ON / yes / correct / 1, false = OFF / no, incorrect / 0
Boolean data types is often used in conditional testing of code
Example:
var isDone =true;var isMarried =false;
06.02.04. Undefined
The meaning of undefined is “value is not assigned”
The undefined data type can only have one value-the special value undefined
A Variable has been declared, but not assigned a value
A variable without a value, The type is also undefined
Example:
var firstName;var country;
06.02.05. Null
A null value means that there is no value
The special value which represents “ nothing”, “empty” or “value unknown”
It is not equivalent to an empty string (‘’ or ’ ', “”, " "), it is simply nothing
Example:
var firstName =null;var id =null;
06.03. Non-primitive data type
06.03. Non-primitive, Reference or Composite data type
Non-primitive/Reference data types can hold collections of values and more complex entities
Non-primitive values are being compared by reference instead of value
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)
06.04. JavaScript has Dynamic Types
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
let name ='JavaScript';
name =false;
name =100;alert(name);alert(typeof(name));
06.05. The typeof Operator
The typeof operator returns the type of the argument
It’s useful to process values of different types differently or want to perform a quick data type check
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) or typeof x
Syntax & Example: 06.05.script.js
// use typeof to find data type of variables// Stringsalert(typeof"Hello");// "string"alert(typeof'12');// "string"// Numbers
console.log(typeof(100));// "number"
console.log(typeof(100.29));// "number"// Booleansalert(typeoftrue);// "boolean"alert(typeof(1==2));// "boolean"// Undefined
console.log(typeofundefined);// "undefined"var init;
console.log('type of init: '+typeof init);// "undefined"// Null
console.log(typeofnull);// "object"var initObject =null;
console.log('type of initObject: '+typeof initObject);// "object"// Objectsalert(typeof{name:'Dinanath',age:35});// "object"alert(typeof document);// "object"alert(typeof window);// "object"// Arraysvar 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(typeoffunction(){});// "function"
console.log(typeof alert);// "function"
console.log(typeof window.alert);// "function"// Symbolalert(typeofSymbol("dob"));// "symbol"
06.06. Type conversion
06.06. typeof parseInt parseFloat
Type conversion is nothing but taking a variable and changing its data type as per needs requirements and logic
In JavaScript as and when we take an input in the form, its data type is a string by default, so do any calculations we need to parse to integer/int or the number
Data type conversion can be either implicit (automatic) or explicit (forcefully/manually)
Syntax & Example:
// Number to String conversionlet 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 conversionlet boolValue1 =String(false);
console.log(boolValue1);
console.log(typeof boolValue1);// Date to String conversionlet curDate =String(newDate());
console.log(curDate);
console.log(typeof curDate);// Array to String conversionlet numArray =String([1,2,3,4,5]);
console.log(numArray);
console.log(typeof numArray);// toString() methodlet curString =(1000).toString
let curString =(true).toString
// String to Number conversionlet 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 conversionlet boolValue2 =Number(false);// parseInt() methodlet curNumber =parseInt('100');let curNumber =parseFloat('100.41');
06.07. Type coercion
Type coercion simply refer to the JavaScript ability to convert type automatically (developer does not do it but JavaScript does it for us)
Type coercion is the process of converting a value from one type to another (such as string to a number, object to boolean, and so on)
JavaScript engine converts the type as per its rules (implicit ie. automatic conversion of data type)
Syntax & Example:
const num1 ='20';const num1 =10;const sum =(num1)+(num2);
console.log(sum);
console.log(typeof sum);
Section 07. Operators
07.01. What is the Operator?
We know/use many operators since our initial school days, they are things like addition +, multiplication *, subtraction -, open-close round bracket ( ) or square bracket [ ]
Operators are symbols/keywords that tell the JavaScript engine to perform some sort of actions
JavaScript operators are symbols that are used to perform operations on operands
Operators used along with our variables and constants to create
expressions to implement logic and algorithms
Note:
Let us take a simple expression var sum = 1 + 2;
Here 1 and 2 are called operands and
= & + are called the operator
= is the assignment operator, + is the arithmetic operator
Syntax & Example: 07.01.script.js
// 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:
Arithmetic Operators
Assignment Operators
Logical Operators
Comparison (or Relational) Operators
Conditional (or ternary) Operators
String Operators
Bitwise Operators
07.02. Arithmetic Operators
Arithmetic operators are used to performing arithmetic operations (just like mathematics - calculations) on numbers/the operands
JavaScript supports the following Arithmetic operators (List of Arithmetic operators):
评论