Introduction to JavaScript
Understanding
Basic Syntax
Objectives
01 Fundamentals Objective: Develop an understanding of fundamentals of JavaScript
02 Statements Objective: Understand Statements as programming instruction unit
03 Values Objective: Understand different type of values in JavaScript
Objectives
04 Operators Objective: Know various Operators in JavaScript and how to use them
05 Expressions Objective: Understand expressions in JavaScript code
06 Comments Objective: Implement different types of Comments in program code
Introduction
What is JavaScript?
JavaScript is:
▪ cross-platform
▪ object-oriented
▪ client-side
▪ scripting language
JavaScript was developed
▪ Used to make webpages interactive:
by Brendan Eich in 1995
• having complex animations
• clickable buttons
• popup menus etc.
There are also more advanced server-side
versions of JavaScript such as nodeJS.
Basics of Front-End Programming
3 languages all web developers must learn
▪ HTML (Hypertext Markup Language) -
to define the content of web pages
▪ JavaScript -
to program the behavior of web pages
▪ CSS (Cascading Style Sheets) -
to specify the layout of web pages
Basics of HTML
HTML: Hypertext Markup Language
▪ Document type
<!DOCTYPE html> this is a HTML5 type
of document
▪ Tags
▪ Elements
• Root element <html>
• Contains meta info <head>
• Contains visible contents <body>
▪ id of an Element (unique attribute for an
HTML element)
Where to Insert JS Code in HTML?
Inserting JS code in HTML
▪ Script element
<script> </script>
▪ Within the <head> element
▪ Within the <body> element
▪ At the bottom of the <body> element
▪ As an attribute
How to Check the Results (Output)?
Various JS output display options
▪ Into an HTML element innerHTML
▪ Directly into the HTML
[Link]()
▪ The alert box [Link]()
▪ The browser console [Link]()
▪ By accessing HTML elements
[Link](id)
JavaScript Statements
Statements: Programming instruction units
Statements:
// Statements end with a ; delimiter
▪ Statements are separated by ; delimiter
var x, y, z; // Statement to Declare Variables
▪ Single instruction unit of JS programming
▪ One-line multiple statements & multi-line
// Multiple statements can be in one line
statements
▪ Multiple blank spaces are ignored x = 1; y = 2; // Statement to Assign value
A statement may contain: // One statement can take multi-line
▪ Values var a =
▪ Operators 'Java';
▪ Expressions
▪ Keywords // Blank-spaces are ignored
▪ Identifiers z = x + y; // Statement to Assign Expression
▪ Comments
[Link](a, z); // output
Values in JS
Values: Texts & Numbers JavaScript uses
Values:
// variables are used to store values
▪ Literals (fixed values)
var x, y, z; // Declare Variables
• Numbers
(with decimals, without decimals,
// Literal (Number) without decimals
exponent)
x = 1; // Assign Literal (Number) to Variable
• Strings
(single quoted, double quoted) // Literal (Number) with a decimal
▪ Variables (may change values) y = 2.5;
• declare
• assign values (Literals, Variables) // Literal (String) with single quote
Variables are declared with keyword var var a = 'Java'; // Assign Literal (String)
Two more keywords are also used: // Literal (String) with double quote
▪ const that cannot be reassigned var b = "script";
▪ let for declaration with restricted scope
[Link](x + y, a + b); // output
Operators in JS
Operators: Special Symbol used to Perform Operations
Operators:
var x, y, z;
▪ Arithmetic operators
x = 1; // Assign
( + - * / % ** ++ -- ) to compute values
▪ Assignment operators
y = 2; // Assign
var a = 'Java'; // Assign
( = += *= %= **= ) to assign values to
variables
▪ Comparison operators // Operators and Operands
( == != > <= ) to compare two values or z = x + y; // Assign Expression to Variable
variables
▪ Logical operators // + operator on Strings
( && || ! ) to check logic between var b = a + " " + "script"; // quotes
variables(values)
▪ Other operators [Link](b, z);
There are many more advanced operators in
the JavaScript to explore in the later part of
the course
Arithmetic Operators
Arithmetic Operators: To Compute Values
Arithmetic Operators:
var x, y;
▪ Simple arithmetic operators
x = 5; // Assign
( + - * / ) add, subtract, multiply, divide
▪ Modulus operator
y = 2; // Assign
var a = x + y; // adds numbers, 7
( % ) to compute the division remainder
▪ Increment & Decrement operators var b = x - y; // subtracts numbers, 3
( ++ -- ) to increment & decrement var c = x * y; // multiplies numbers, 10
numbers var d = x / y; // divides numbers, 2.5
▪ Prefix Increment / decrement var e = x % y; // returns division remainder,1
▪ Postfix Increment / decrement var f = x ** y; // power, returns 25
▪ Exponentiation operators // increment & decrement operators
( ** ) 1st operand to the power of the a = x++; // value of a returns 6
2nd operand b = y-- // value of b returns 1
alert(c++); // Prefix, returns 10
alert(++d); // Postfix, returns 3.5
Assignment Operators
Assignment Operators: To Assign Values to Variables
Assignment Operators:
var x;
▪ Simple assignment operator
// Assign value to a variable
( = ) Assign value to a variable
▪ Add assignment operator x = 3; // value of x returns 3
// Assign added value
( += ) Assign added value to a variable
▪ Subtract assignment operator x += 2; // value of x returns 5
( -= ) Assign subtracted value to a // Assign subtracted value
variable x -= 2; // value of x returns 3
▪ Multiply assignment operator // Assign multiplied value
( *= ) Assign multiplied value to a x *= 2; // value of x returns 6
variable // Assign divided value
▪ Divide assignment operator x /= 2; // value of x returns 3
( /= ) assigns divided value to a // Assign remainder
variable x %= 2; // value of x returns 1
▪ Modulus assignment operator
( %= ) assigns a remainder to a
variable
Comparison Operators
Comparison Operators: To Compare Two Values or Variables
Comparison Operators:
var x, age = 19;
▪ Equal to operator
if (age > 18) x = "Adult"; // Adult
( == )
▪ Equal value and equal type operator
(age > 18) // true
( === )
▪ Not equal operator age = 12;
( != ) (age > 18) // false
▪ Not equal value or not equal type operator (age == "12") // true
( !== ) (age === "12") // false
▪ Greater than & less than operator (age === 12) // true
(><) (age != "10") // true
▪ Greater than or / less than or equal to (age !== 10) // true
operator
( >= <= ) age = 18;
(age >= 18) // true
Conditional Operators
It assigns a value to a variable based on some condition
Conditional or Ternary Operators:
var x, age = 12;
▪ variablename = (condition) ?
value1:value2
// variablename = (condition) ? value1:value2
x = (age > 18) ? "Adult":"Minor"; // Minor
(age > 18) // false
// if the condition (age > 18) is true
// then x = "Adult"
// else x = "Minor"
age = 18;
x = (age >= 18) ? "Adult":"Minor"; // Adult
(age >= 18) // true
Logical Operators
Logical Operators: To Check Logic between Values or Variables
Logical Operators:
var x, y;
▪ Logical and operator
( && )
▪ Logical or operator
x = 5;
y = 3;
( || )
▪ Logical not operator
(!) // Logical and operator
(x < 8 && y > 1) // true
// Logical or operator
(x == 10 || y < 1) // false
// Logical not operator
(!(x == y)) // true
Expressions in JS
Expressions: Combination of Values, Variables, and Operators
Expressions:
Any unit of code that can be evaluated var x = 1, y = 4;
to a value. // Primary Expressions
'Javascript'; // A string literal
▪ Primary expressions
54.2; // A numeric literal
string / numeric literals, boolean,
true; // Boolean value true
variables
sum; // Value of variable sum
('hello world', 54.2, true, x, this)
this; // A current object
▪ Arithmetic expressions
Arithmetic expressions evaluate to a
// Arithmetic Expressions
numeric value
x + 2;
▪ String expressions
// String Expressions
String expressions evaluate to a string
▪ Logical expressions
"Java" + "script";
// Logical Expressions
logical expressions evaluate to the
boolean value x < 8 && y > 1;
(true, false)
Comments in JS
Written part in the code that are ignored by the JavaScript engine
Comments:
// Declare Variables (line comment)
Are used to add information, warnings or
var x, y, z; // Var declired (line comment)
suggestions about the code, making a code easy
/* this is a block comment */
to interpret
x = 1;
▪ Single line comments /* this is a multiline
• // this is a line comment block comment */
• Also used to hide a line from the code y = 2;
// also used to hide a line of the code
▪ Multi-line comments (block comment) // var a = 'Java';
• /* this is a block comment */ // also used to hide a code block
• Also used to hide a code block /*
z = x + y;
var b = "Java" + " " + "script"; // quotes
*/
Understanding Basic
Flow
Objectives
01 Identifiers Learning Identifiers specifications in JavaScript program
02 Strings Use strings to store and manipulate text in a JavaScript program
03 Numbers Execute numeric operations in JavaScript using numbers
Objectives
04 Conditions Objective: Apply conditional statements in a JavaScript program
05 Loops Objective: Discover and execute loops in JavaScript
06 Jumps Objective: Learn and apply how to Jump out of a loop
Identifiers in JS
Character sequence identifying a variable, function, or property
Identifiers:
// Allowed Identifiers
Name of a variable, function, or property
abc; // starts with a letter
▪ Rules for legal identifiers
_abc; // starts with a underscore
1st character: a letter, underscore (_), dollar sign
$abc; // starts with a dollar sign
($)
Subsequent characters may be letters, digits, _ , $ অলীক; // starts with Unicode character
JavaScript uses the Unicode character set
▪ Case sensitivity first-name; // Hyphens not allowed
lowercase char are different from uppercase char first_name; // Underscores allowed
▪ Hyphens, Underscore
Hyphens not allowed, Underscore allowed FirstName; // Upper Camel Case example
▪ Upper Camel Case
FirstName, LastName // The most popular practice among JS coders :
▪ Lower Camel Case firstName; // lower Camel Case
firstName, lastName (popular practice)
Keywords in JS
Keywords are tokens that have special meaning in JavaScript (JavaScript Reserved Words)
arguments await break case catch class const continue
debugger default delete do else enum eval export
extends false finally for function if implements import
in instanceof interface let new null package private
protected public return static super switch this throw
true try typeof var void while with yield
Strings in JavaScript
Strings are used for storing and manipulating text
Strings: strings are zero or more characters
// Strings
inside quotes
str = "This is a 'Javascript' module!";
[Link](str);
▪ Quotes: single or double or one inside other
str = 'This is a "Javascript" module!';
▪ Length Property: returns the length of a [Link](str);
string str = 'It\'s fun to learn "Javascript"';
[Link](str);
▪ Escape Characters: \' \" \\ str = "It's fun to learn \"Javascript\"";
[Link](str);
▪ Breaking Lines: use of \ within a string and str = "This is a \
continue to the next line (not a good 'Javascript' module!";
practice, though) [Link](str);
[Link]([Link]);
Strings in JavaScript
Strings are used for storing and manipulating text
String Methods: String methods help you to work
str = "It's good to know that you are good!";
with strings
[Link]([Link]("good"));
▪ indexOf: returns index of the first occurrence of a
[Link]([Link]("good",10));
specified text in a string (search starting position)
▪ lastIndexOf: returns index of the last occurrence
[Link]([Link]("good"));
[Link]([Link]("good"));
of a specified text in a string (search starting
position) [Link]([Link](23));
▪ search: searches a string for a specified value [Link]([Link](5, 9));
and returns the position of the match [Link]([Link](-5));
▪ slice: extracts a part of a string and returns the [Link]([Link](-5, -1));
extracted part in a new string (-ve index allowed) [Link]([Link](5, 9));
▪ substring: extracts a part of a string and returns [Link]([Link](23));
the extracted part in a new string (-ve index not [Link]([Link](5,4));
allowed) [Link]([Link](23));
▪ substr: same as slice, but the second parameter [Link]([Link](-5,4));
here specifies the length of the extracted part
Strings in JavaScript
Strings are used for storing and manipulating text
String methods: String methods help you to
// String Methods
work with strings.
str = "It's good to know that you are good!";
[Link]([Link]("good", "bad"));
▪ replace: replaces a specified value with
[Link]([Link](5, 9).toUpperCase());
another value in a string (this method is
var str1 = "This is";
case sensitive)
▪ toLowerCase / toUpperCase: converts a var str2 = "script";
string to lowercase/uppercase [Link]([Link](" Java", str2));
▪ concat: joins two or more strings (the +
operator does the similar operation) var str = " Javascript ";
▪ trim: removes whitespace from the [Link]([Link]());
beginning and end of a string
▪ padStart, padEnd: to support padding at str = "1";
the beginning and at the end of a string [Link]([Link](4,0));
[Link]([Link](4,0));
Strings in JavaScript
Strings are used for storing and manipulating text
String methods: String methods help you to
// charAt
work with strings.
var str = "Javascript";
[Link]([Link](0));
▪ charAt / charCodeAt: returns character at
a specified index in a string/returns
// Access char
unicode of the character
▪ access [ ] (read only): same as charAt() [Link](str[0]);
but returns undefined instead of an empty
string // charCodeAt
▪ split: converts a String to an Array on [Link]([Link](0));
separators
// split
var str = "J,a,v,a,s,c,r,i,p,t";
[Link]([Link](","));
Numbers in JavaScript
Number is a type in JS and there is only one type of number
Numbers and Strings:
var a = 1, b = 2;
[Link](a + b);
▪ Adding Numbers and Strings: + operator
var a = "1", b = "2";
can both add numbers and concatenate
[Link](a + b);
strings. Hene, the sequence in the
var a = 1, b = "2";
expression determines the result.
▪ Numeric Strings: JavaScript tries to [Link](a + b);
convert strings to numbers in numeric var a = 1, b = 2;
operations. [Link](a + b + ": sum");
▪ The concept of NaN , isNaN: Not a [Link]("str:" + a + b);
Number (but NaN is of number type), [Link](1/"Javascript");
isNaN checks if a value is a number [Link](isNaN(1/"Javascript"));
▪ toString: converts number to string [Link](typeof NaN);
[Link]([Link](10));
[Link]([Link](2));
Numbers in JavaScript
Number is a type in JS and there is only one type of number
Numbers Methods:
// convert to String,Exponential,Num of digits
var b = 2.5
▪ toExponential: returns string in
[Link]([Link]());
exponential notation
▪ toFixed(n): returns string with n number of
[Link]([Link]());
[Link]([Link](2));
decimals
▪ toPrecision(n): returns string, with length n [Link]([Link](0));
▪ toString: converts number to string [Link]([Link](4));
▪ Number: returns number, from its // convert to Number
argument [Link](Number("2.5 "));
▪ parseFloat: returns a floating point number [Link](Number("Javascript"));
▪ parseInt: returns integer by parsing its // convert to Int, Floating point
argument [Link](parseInt("2.5 "));
[Link](parseInt("2.5 JS"));
[Link](parseFloat("2.5 JS"));
Conditional Statements
Decisions making: if, else
Conditional Statements: Conditional
if(numOfItems >= 12) numOfItems += 2;
statements are used to perform different
actions based on different conditions
if(numOfItems >= 12){
▪ if Statement
speakOut = "It's over a Dozen";
numOfItems += 2;
if (condition) {
// executed if condition is true }
}
▪ else Statement if(numOfItems >= 12){
if (condition) { speakOut = "It's over a Dozen";
// executed if condition is true numOfItems += 2;
} else { } else {
// executed if condition is false speakOut = "It's less than a Dozen";
} }
Conditional Statements
Decisions making: else if
Conditional Statements: Conditional
var dozen = 12;
statements are used to perform different
var offerPerDozen = 2, totalOffer = 0;
actions based on different conditions
var numOfItems = 12;
▪ else if Statement
if(numOfItems == dozen){
speakOut = "It's a Dozen";
if (condition 1) {
// executed if condition is true totalOffer = offerPerDozen;
} else if (condition 2) { } else if (numOfItems < dozen){
// executed if condition is false speakOut = "It's less than a Dozen";
} else { }else{
// executed if condition is false speakOut = "It's more than a Dozen";
} totalOffer = 2 * parseInt(numOfItems/dozen);
}
numOfItems += totalOffer;
[Link](speakOut,numOfItems,totalOffer);
Conditional Statements
Decisions making: switch
Conditional Statements: Conditional
switch (season) {
statements are used to perform different
case "summer":
actions based on different conditions
[Link]('It\'s hot!');
▪ switch Statement
break;
case "winter":
switch(expression) {
case x: [Link]('It\'s cold!');
// code block break;
break; case "spring":
case y: [Link]('It\'s comfortable!');
// code block break;
break; default:
default: [Link]('Not sure how I feel!');
// code block break;
} }
Loops in JavaScript
Loops: Loops can execute a block of code a number of times
Loops: Different types of loops in JavaScript
▪ for loops:
When number of
Loops through a block of code a number of
iterations is fixed,
times for loop
it is recommended
▪ for/in loops:
to use for loop.
Loops through the properties of an
Object/Array When number of
▪ forEach loops: iterations is not
call a function once for each array element fixed, it is while loop
▪ for/of loops: recommended to
Loops through the values of an iterable use while loop.
When number of
object iterations is not
▪ while loops: do while fixed & first
Loops through a block of code while loop iteration is must, it
condition is true is recommended to
▪ do/while loops: use do-while loop.
Same as while loop, with unconditional
first iteration
Loops in JavaScript
Loops: Loops can execute a block of code a number of times
for Loops: repeat with initialization, condition
// for loop
and increment
var sum = 0;
▪ for loops:
for (let i = 0; i < 10; i++) {
for (statement 1; statement 2; statement 3)
sum += i;
{
// code block to be executed }
}
▪ statement 1: [Link](sum);
sets a variable before the loop starts
▪ statement 2:
defines condition for the loop to run
▪ statement 3:
increment the initial variable
Loops in JavaScript
Loops: Loops can execute a block of code a number of times
for/in Loops: loops through the properties of
// for-in on an Object
an Object/Array
var person = {fname:"Dip",lname:"Roy",age:25};
var txt = "";
▪ for/in loops over Objects:
for (let x in person) {
for (key in object) {
txt += person[x] + " ";
// code block to be executed
} }
[Link](txt);
▪ for/in loops over Arrays: // for-in on an Array
for (variable in array) { var num = [23,12,0,2,9,10];
// code block to be executed var sum = 0;
} for (let i in num) {
sum += num[i];
}
[Link](sum);
Loops in JavaScript
Loops: Loops can execute a block of code a number of times
forEach Loops: call a function once for each
// forEach loop
array element
var num = [23,12,0,2,9,10];
var sum = 0, numbered = "";
▪ forEach loops over Arrays:
// either - with a function name:
[Link](someFunction);
[Link](numFunc);
▪ forEach callback function: function numFunc(value, index, array) {
function someFunction(value, index, array) { sum += value;
/* numbered += ++index +" ";
code block using value, index of }
the current element of array & the // or - without a function name:
array itself, which is someArray here [Link](function(value, index, array) {
*/ sum += value; numbered += ++index +" ";
} });
[Link](sum,numbered);
Loops in JavaScript
Loops: Loops can execute a block of code a number of times
for/of Loops: loops through the values of an
// for-of on an Array
iterable object
var num = [23,12,0,2,9,10];
var sum = 0;
▪ for/of loops over Array:
for (let n of num) {
for (variable of array) {
sum += n;
// code block to be executed
} }
[Link](sum);
▪ for/of loops over String: // for-of on a String
for (variable of string) { var txt = "abcdefgh";
// code block to be executed var letters = "";
} for (let x of txt) {
letters += x + ",";
}
[Link](letters);
Loops in JavaScript
Loops: Loops can execute a block of code a number of times
while Loops: loops through a block of code
// while loop
while condition is true
var txt = "";
var x = 1;
▪ while Loops:
while (x < 10) {
check condition before the loop
txt += x + " ";
while (condition) {
// code block to be executed x++;
} }
[Link](txt);
▪ do/while Loops : // do-while loop
check condition after the loop do {
do { txt += x + " ";
// code block to be executed x++;
} } while (x < 10);
while (condition); [Link](txt);
Jumps in Loops
Jump out of a loop & Jump over one iteration in a loop
Jumps: through a block of code while
// break out of & continue a loop
condition is true
var indices = "";
▪ break : "jumps out" of a loop if condition is
for (let i = 0; i < 10; i++) {
true
if (i == 3) {
loop {
if (condition) { break; } continue;
} }
if (i == 5) {
▪ continue : Jump over one iteration in a loop break;
if condition is true }
loop { indices += i + ",";
if (condition) { continue; } }
}
[Link](indices);
Recap
Understanding Basic Syntax
Fundamental Statements Values Operators Expression
s s
What is JavaScript, Syntax, Literals (Numbers, Arithmetic operators, Combination of
Where to write, How Specifications, Strings), Variables Assignment values, variables,
to see outputs etc. Multi-line, Blank (declare, assign operators, and operators
space etc. Values, values), var const let Comparison
Operators, operators, Logical
Expressions, operators
Keywords, Identifiers,
Comments
Recap
Understanding Basic Flow (Part 1)
Identifiers Strings Numbers
Rules for legal Properties and Adding Numbers
identifiers, case methods, Length, and Strings, numeric
sensitivity, hyphens, indexOf, lastIndexOf, Strings, the concept
underscore, upper search, slice, of NaN, toString,
camel case, lower substring, substr, toExponential,
camel case, unicode replace, toFixed, toPrecision,
character set toLowerCase, toString, parseFloat,
toUpperCase, concat, parseInt
trim, padStart,
padEnd, charAt,
charCodeAt, access,
split
Recap
Understanding Basic Flow (Part 2)
Conditions Loops Jumps
if Statement, else for loops, for/in Break out of a loop,
Statement, else if loops, forEach loops, continue a loop
Statement, switch for/of loops, while
Statement loops, do/while loops