MODULE 2
MODULE 2
JavaScript Variables
The var keyword was used in all JavaScript code from 1995 to 2015.
The let and const keywords were added to JavaScript in 2015.
The var keyword should only be used in code written for older browsers.
Example using let
let x = 5;
let y = 6;
let z = x + y;
Example using const
const x = 5;
const y = 6;
const z = x + y;
Mixed Example
const price1 = 5;
const price2 = 6;
let total = price1 + price2;
The two variables price1 and price2 are declared with the const keyword.
These are constant values and cannot be changed.
The variable total is declared with the let keyword.
The value total can be changed.
When to Use var, let, or const?
1. Always declare variables
2. Always use const if the value should not be changed
3. Always use const if the type should not be changed (Arrays and Objects)
4. Only use let if you can't use const
5. Only use var if you MUST support old browsers.
From the example above, you can guess that the total is calculated to be 11.
JavaScript Operators
Javascript operators are used to perform different types of mathematical and logical
computations.
Examples:
The Assignment Operator = assigns values
The Addition Operator + adds values
The Multiplication Operator * multiplies values
The Comparison Operator > compares values
JavaScript Assignment
The Assignment Operator (=) assigns a value to a variable:
Assignment Examples
let x = 10;
// Assign the value 5 to x
let x = 5;
// Assign the value 2 to y
let y = 2;
// Assign the value x + y to z:
let z = x + y;
JavaScript Addition
The Addition Operator (+) adds numbers:
Adding
let x = 5;
let y = 2;
let z = x + y;
JavaScript Multiplication
The Multiplication Operator (*) multiplies numbers:
Multiplying
let x = 5;
let y = 2;
let z = x * y;
Types of JavaScript Operators
There are different types of JavaScript operators:
Arithmetic Operators
Assignment Operators
Comparison Operators
String Operators
Logical Operators
Bitwise Operators
Ternary Operators
Type Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
++ Increment
-- Decrement
Note
Arithmetic operators are fully described in the JS Arithmetic chapter.
ADVERTISEMENT
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y
Note
Assignment operators are fully described in the JS Assignment chapter.
JavaScript Comparison Operators
Operator Description
== equal to
!= not equal
? ternary operator
Note
Comparison operators are fully described in the JS Comparisons chapter.
Note
When used on strings, the + operator is called the concatenation operator.
Note
If you add a number and a string, the result will be a string!
|| logical or
! logical not
Note
Logical operators are fully described in the JS Comparisons chapter.
Operator Description
Note
Type operators are fully described in the JS Type Conversion chapter.
~ NOT ~5 ~0101
JAVASCRIPT DATATYPES
// Booleans
let x = true;
let y = false;
// Object:
const person = {firstName:"John", lastName:"Doe"};
// Array object:
const cars = ["Saab", "Volvo", "BMW"];
// Date object:
const date = new Date("2022-03-25");
Note
A JavaScript variable can hold any type of data.
The Concept of Data Types
In programming, data types is an important concept.
To be able to operate on variables, it is important to know something
about the type.
Without data types, a computer cannot safely solve this:
let x = 16 + "Volvo";
Does it make any sense to add "Volvo" to sixteen? Will it produce an
error or will it produce a result?
JavaScript will treat the example above as:
let x = "16" + "Volvo";
Note
When adding a number and a string, JavaScript will treat the number as
a string.
Example
let x = 16 + "Volvo";
Example
let x = "Volvo" + 16;
JavaScript:
let x = "Volvo" + 16 + 4;
Result:
Volvo164
ADVERTISEMENT
JavaScript Strings
A string (or a text string) is a series of characters like "John Doe".
Strings are written with quotes. You can use single or double quotes:
Example
// Using double quotes:
let carName1 = "Volvo XC60";
You can use quotes inside a string, as long as they don't match the
quotes surrounding the string:
Example
// Single quote inside double quotes:
let answer1 = "It's alright";
JavaScript Numbers
All JavaScript numbers are stored as decimal numbers (floating point).
Numbers can be written with, or without decimals:
Example
// With decimals:
let x1 = 34.00;
// Without decimals:
let x2 = 34;
Exponential Notation
Extra large or extra small numbers can be written with scientific
(exponential) notation:
Example
let y = 123e5; // 12300000
let z = 123e-5; // 0.00123
Note
Most programming languages have many number types:
Whole numbers (integers):
byte (8-bit), short (16-bit), int (32-bit), long (64-bit)
Real numbers (floating-point):
float (32-bit), double (64-bit).
Javascript numbers are always one type:
double (64-bit floating point).
You will learn more about numbers later in this tutorial.
JavaScript BigInt
All JavaScript numbers are stored in a 64-bit floating-point format.
JavaScript BigInt is a new datatype (ES2020) that can be used to store
integer values that are too big to be represented by a normal JavaScript
Number.
Example
let x = BigInt("123456789012345678901234567890");
JavaScript Booleans
Booleans can only have two values: true or false.
Example
let x = 5;
let y = 5;
let z = 6;
(x == y) // Returns true
(x == z) // Returns false
Booleans are often used in conditional testing.
JavaScript Arrays
JavaScript arrays are written with square brackets.
Array items are separated by commas.
The following code declares (creates) an array called cars, containing
three items (car names):
Example
const cars = ["Saab", "Volvo", "BMW"];
Array indexes are zero-based, which means the first item is [0], second
is [1], and so on.
JavaScript Objects
JavaScript objects are written with curly braces {}.
Object properties are written as name:value pairs, separated by
commas.
Example
const person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
Undefined
In JavaScript, a variable without a value, has the value undefined. The
type is also undefined.
Example
let car; // Value is undefined, type is undefined
Any variable can be emptied, by setting the value to undefined. The type
will also be undefined.
Example
car = undefined; // Value is undefined, type is undefined
Empty Values
An empty value has nothing to do with undefined.
An empty string has both a legal value and a type.
Example
let car = ""; // The value is "", the typeof is "string"
JavaScript Objects
❮ PreviousNext ❯
car.name = Fiat
car.model = 500
car.weight = 850kg
car.color = white
Object Properties
A real life car has properties like weight and color:
car.name = Fiat, car.model = 500, car.weight = 850kg, car.color = white.
Car objects have the same properties, but the values differ from car to
car.
Object Methods
A real life car has methods like start and stop:
car.start(), car.drive(), car.brake(), car.stop().
Car objects have the same methods, but the methods are performed at
different times.
JavaScript Variables
JavaScript variables are containers for data values.
This code assigns a simple value (Fiat) to a variable named car:
Example
let car = "Fiat";
JavaScript Objects
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to an object named
car:
Example
const car = {type:"Fiat", model:"500", color:"white"};
Note:
It is a common practice to declare objects with the const keyword.
Learn more about using const with objects in the chapter: JS Const.
Note:
name:value pairs are also called key:value pairs.
object literals are also called object initializers.
Spaces and line breaks are not important. An object initializer can span
multiple lines:
// Create an Object
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
// Add Properties
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
// Add Properties
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
Note:
The examples above do exactly the same.
But, there is no need to use new Object().
For readability, simplicity and execution speed, use the object
literal method.
Object Properties
The named values, in JavaScript objects, are called properties.
Property Value
firstName John
lastName Doe
Age 50
eyeColor blue
person["lastName"];
firstName John
lastName Doe
Age 50
eyeColor blue
Example
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
JavaScript Primitives
A primitive value is a value that has no properties or methods.
3.14 is a primitive value
A primitive data type is data that has a primitive value.
JavaScript defines 7 types of primitive data types:
string
number
boolean
null
undefined
symbol
bigint
Immutable
Primitive values are immutable (they are hardcoded and cannot be
changed).
if x = 3.14, you can change the value of x, but you cannot change the
value of 3.14.
// Create a copy
const x = person;
// Change Age in both
x.age = 10;
Block Scope
Before ES6 (2015), JavaScript variables had only Global
Scope and Function Scope.
ES6 introduced two important new JavaScript keywords: let and const.
These two keywords provide Block Scope in JavaScript.
Variables declared inside a { } block cannot be accessed from outside
the block:
Example
{
let x = 2;
}
// x can NOT be used here
Variables declared with the var keyword can NOT have block scope.
Variables declared inside a { } block can be accessed from outside the
block.
Example
{
var x = 2;
}
// x CAN be used here
Local Scope
Variables declared within a JavaScript function, are LOCAL to the
function:
Example
// code here can NOT use carName
function myFunction() {
let carName = "Volvo";
// code here CAN use carName
}
Function Scope
JavaScript has function scope: Each function creates a new scope.
Variables defined inside a function are not accessible (visible) from
outside the function.
Variables declared with var, let and const are quite similar when declared
inside a function.
They all have Function Scope:
function myFunction() {
var carName = "Volvo"; // Function Scope
}
function myFunction() {
let carName = "Volvo"; // Function Scope
}
function myFunction() {
const carName = "Volvo"; // Function Scope
}
function myFunction() {
// code here can also use carName
}
A global variable has Global Scope:
All scripts and functions on a web page can access it.
Global Scope
Variables declared Globally (outside any function) have Global Scope.
Global variables can be accessed from anywhere in a JavaScript
program.
Variables declared with var, let and const are quite similar when declared
outside a block.
They all have Global Scope:
var x = 2; // Global scope
let x = 2; // Global scope
const x = 2; // Global scope
JavaScript Variables
In JavaScript, objects and functions are also variables.
Scope determines the accessibility of variables, objects, and functions
from different parts of the code.
Automatically Global
If you assign a value to a variable that has not been declared, it will
automatically become a GLOBAL variable.
This code example will declare a global variable carName, even if the
value is assigned inside a function.
Example
myFunction();
function myFunction() {
carName = "Volvo";
}
Strict Mode
All modern browsers support running JavaScript in "Strict Mode".
You will learn more about how to use strict mode in a later chapter of this
tutorial.
In "Strict Mode", undeclared variables are not automatically global.
Global variables defined with the let keyword do not belong to the
window object:
Example
let carName = "Volvo";
// code here can not use window.carName
Function Arguments
Function arguments (parameters) work as local variables inside
functions.
HTML Events
An HTML event can be something the browser does, or something a
user does.
Here are some examples of HTML events:
An HTML web page has finished loading
An HTML input field was changed
An HTML button was clicked
Often, when events happen, you may want to do something.
JavaScript lets you execute code when events are detected.
HTML allows event handler attributes, with JavaScript code, to be
added to HTML elements.
With single quotes:
<element event='some JavaScript'>
With double quotes:
<element event="some JavaScript">
In the following example, an onclick attribute (with code), is added to
a <button> element:
Example
<button onclick="document.getElementById('demo').innerHTML =
Date()">The time is?</button>
In the example above, the JavaScript code changes the content of the
element with id="demo".
In the next example, the code changes the content of its own element
(using this.innerHTML):
Example
<button onclick="this.innerHTML = Date()">The time is?</button>
Event Description
onmouseout The user moves the mouse away from an HTML element
Function Invocation
The code inside the function will execute when
"something" invokes (calls) the function:
When an event occurs (when a user clicks a button)
When it is invoked (called) from JavaScript code
Automatically (self invoked)
You will learn a lot more about function invocation later in this tutorial.
ADVERTISEMENT
Function Return
When JavaScript reaches a return statement, the function will stop
executing.
If the function was invoked from a statement, JavaScript will "return" to
execute the code after the invoking statement.
Functions often compute a return value. The return value is "returned"
back to the "caller":
Example
Calculate the product of two numbers, and return the result:
// Function is called, the return value will end up in x
let x = myFunction(4, 3);
function myFunction(a, b) {
// Function returns the product of a and b
return a * b;
}
Why Functions?
With functions you can reuse code
You can write code that can be used many times.
You can use the same code with different arguments, to produce
different results.
The () Operator
The () operator invokes (calls) the function:
Example
Convert Fahrenheit to Celsius:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
Accessing a function without () returns the function and not the function
result:
Example
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
Note
As you see from the examples above, toCelsius refers to the function
object, and toCelsius() refers to the function result.
Local Variables
Variables declared within a JavaScript function, become LOCAL to the
function.
Local variables can only be accessed from within the function.
Example
// code here can NOT use carName
function myFunction() {
let carName = "Volvo";
// code here CAN use carName
}
Since local variables are only recognized inside their functions, variables
with the same name can be used in different functions.
Local variables are created when a function starts, and deleted when the
function is completed.
JavaScript Loops
Loops are handy, if you want to run the same code over and over again,
each time with a different value.
Often this is the case when working with arrays:
Instead of writing:
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";
You can write:
for (let i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
T
From the example above, you can read:
Expression 1 sets a variable before the loop starts (let i = 0).
Expression 2 defines the condition for the loop to run (i must be less
than 5).
Expression 3 increases a value (i++) each time the code block in the
loop has been executed.
ADVERTISEMENT
Loop Scope
Using var in a loop:
Example
var i = 5;
// Here i is 10
// Here i is 5
In the first example, using var, the variable declared in the loop
redeclares the variable outside the loop.
In the second example, using let, the variable declared in the loop does
not redeclare the variable outside the loop.
When let is used to declare the i variable in a loop, the i variable will only
be visible within the loop.
JAVASCRIPT ARRAYS
JavaScript Arrays
An array is a special variable, which can hold more than one value:
const cars = ["Saab", "Volvo", "BMW"];
Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
const array_name = [item1, item2, ...];
It is a common practice to declare arrays with the const keyword.
Learn more about const with arrays in the chapter: JS Array Const.
Example
const cars = ["Saab", "Volvo", "BMW"];
Spaces and line breaks are not important. A declaration can span
multiple lines:
Example
const cars = [
"Saab",
"Volvo",
"BMW"
];
You can also create an array, and then provide the elements:
Example
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
The length property is always one more than the highest array index.
function myFunction(value) {
text += "<li>" + value + "</li>";
}
New element can also be added to an array using the length property:
Example
const fruits = ["Banana", "Orange", "Apple"];
fruits[fruits.length] = "Lemon"; // Adds "Lemon" to fruits
WARNING !
Adding elements with high indexes can create undefined "holes" in an
array:
Example
const fruits = ["Banana", "Orange", "Apple"];
fruits[6] = "Lemon"; // Creates undefined "holes" in fruits
Associative Arrays
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
JavaScript does not support arrays with named indexes.
In JavaScript, arrays always use numbered indexes.
Example
const person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
person.length; // Will return 3
person[0]; // Will return "John"
WARNING !!
If you use named indexes, JavaScript will redefine the array to an object.
After that, some array methods and properties will produce incorrect
results.
Example:
const person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
person.length; // Will return 0
person[0]; // Will return undefined
A Common Error
const points = [40];
is not the same as:
const points = new Array(40);
// Create an array with one element:
const points = [40];
Solution 2:
The instanceof operator returns true if an object is created by a given
constructor:
const fruits = ["Banana", "Orange", "Apple"];
JavaScript Forms
Data Validation
Data validation is the process of ensuring that user input is clean,
correct, and useful.
Typical validation tasks are:
has the user filled in all required fields?
has the user entered a valid date?
has the user entered text in a numeric field?
Most often, the purpose of data validation is to ensure correct user input.
Validation can be defined by many different methods, and deployed in
many different ways.
Server side validation is performed by a web server, after input has
been sent to the server.
Client side validation is performed by a web browser, before input is
sent to a web server.
Attribute Description
Selector Description
DOM
JavaScript HTML DOM Document
The HTML DOM document object is the owner of all other objects in
your web page.
Method Description
Property Description
Method Description
Method Description
document.createElement(element) Create an HTML element
If the element is found, the method will return the element as an object (in element).
If the element is not found, element will contain null.
A simple UI design
A simple UI design in JavaScript typically involves manipulating HTML elements
directly using JavaScript to create interactive components like buttons, text fields,
and alerts, often with basic styling using CSS, without relying on complex
frameworks like React or Angular; essentially, directly changing the content and
appearance of a webpage based on user interaction.
Key elements of a simple UI with JavaScript:
HTML Structure:
Create the basic layout of your UI using HTML tags like <div>, <input>, <button>,
and <p> to define the elements where content will be displayed and user interaction
will occur.
JavaScript DOM Manipulation:
Accessing
Elements: Use document.getElementById(), document.querySelector()
to select specific HTML elements on the page to modify them with
JavaScript.
Modifying Content: Change text content using .textContent or
innerHTML to update what is displayed within an element.
Styling: Apply CSS styles dynamically using .style.property = 'value' to
change color, font, or positioning of elements.
Event Listeners: Add event listeners like addEventListener('click',
function) to respond to user actions like button clicks, mouse hovers, or
form submissions.
<p id="result"></p>
Code
const button = document.getElementById('myButton');
button.addEventListener('click', function() {
});
Explanation:
HTML:
A button with the ID "myButton" and a paragraph with the ID "result" are created.
JavaScript:
The getElementById function gets references to the button and
paragraph elements.
An event listener is added to the button: when clicked, the function
inside is executed.
Inside the click function, the text content of the paragraph is updated to
"Button clicked!".
Important considerations for simple UI design:
Accessibility: Ensure your UI is accessible to users with disabilities by using
appropriate ARIA attributes and semantic HTML tags.
Responsiveness: Design your UI to adapt to different screen sizes using
CSS media queries.
Visual Hierarchy: Organize content with clear visual cues to guide the user's
attention.
What is JSON?
JSON
JSON stands for JavaScript Object Notation
JSON is a lightweight format for storing and transporting data
JSON is often used when data is sent from a server to a web page
JSON is "self-describing" and easy to understand
JSON Example
This example defines an employees object: an array of 3 employee records
(objects):
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}
JSON Objects
JSON objects are written inside curly braces.
Just like in JavaScript, objects can contain multiple name/value pairs:
{"firstName":"John", "lastName":"Doe"}
JSON Arrays
JSON arrays are written inside square brackets.
Just like in JavaScript, an array can contain objects:
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
In the example above, the object "employees" is an array. It contains three objects.
Each object is a record of a person (with a first name and a last name).
S
Converting a JSON Text to a JavaScript Object
A common use of JSON is to read data from a web server, and display the data in a
web page.
For simplicity, this can be demonstrated using a string as input.
First, create a JavaScript string containing JSON syntax:
var text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';
Then, use the JavaScript built-in function JSON.parse() to convert the string into a
JavaScript object:
var obj = JSON.parse(text);
Finally, use the new JavaScript object in your page:
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>