Introduction to Javascript
How JavaScript aligns with other Web Technologies:
- HTML is for content
- CSS is for presentation
- JavaScript is for interactivity
- validate user input in an HTML form before sending the data to a server;
- build forms that respond to user input without accessing a server;
- change the appearance of HTML documents and write data to browser Windows;
- open and close new browser windows or frames;
- build small but complete client side programs.
Things you can do with JavaScript - Some examples:
- Validate User Input
- Checking the values in input fields
- Checking a Password
- Checking numeric values
- Forms that respond to user input without accessing a server
- Forms that load a URL
- Forms that calculate
- Write information into HTML documents using Javascript Statements
- Programmed ouput via [element selector].innerHTML
- Adjust document colours
- Change/rewrite images in a document
- Open and Close Browser windows and Frames
- Create new Browser windows with documents or programmed output
- Build small but complete client side programs
- Calculators
- Games
- Control Robots
- Control drones (IOT)
ECMAScript 6 (ES6)
ECMAScript 6 (ES6), also known as ECMAScript 2015, is the sixth major version of the ECMAScript programming language. It is the most recent version of the language that was finalized in June 2015. ES6 introduced many new features and syntax enhancements to the JavaScript language that make it more powerful and easier to use.
ES6 includes features such as:
- let and const for variable declaration
- Arrow functions for shorter function syntax
- Template literals for string interpolation
- Destructuring assignment for extracting data from arrays and objects
- Default function parameters and rest parameters
- Classes and inheritance
- Modules for better code organization
- Promises for handling asynchronous code
- Generators for creating iterators
- Maps and Sets for more efficient data storage
- Symbols for creating unique, immutable identifiers
- And many more.
These new features and syntax enhancements have been designed to make it easier for developers to write more efficient and maintainable code, and to help them take advantage of the latest advancements in JavaScript development.
It's worth to note that not all JavaScript engines implement all the features of ES6 yet, but most modern engines have implemented most of the features. You can use transpilers like Babel to convert your ES6 code to a version that can run on older browsers or JavaScript engines.
The <script> </script> tag
<html>
<head>
<title>The Script Tag 1</title>
<script>
function myFunction1() {
document.getElementById("demo").innerHTML = "From the script in the head";
}
</script>
<style>
* {
font-family: arial;
}
div#demo1 {
border: thin solid darkgrey;
background-color: rgba(230, 200, 200, 0.6);
width: 400px;
height: 20px;
padding: 5px;
}
div#demo2 {
border: thin solid darkgrey;
background-color: rgba(200, 200, 230, 0.6);
width: 400px;
height: 20px;
padding: 5px;
}
div#demo3 {
border: thin solid darkgrey;
background-color: rgba(200, 230, 200, 0.6);
width: 400px;
height: 20px;
padding: 5px;
}
</style>
</head>
<body>
<h1>The Script Tag: Example 1</h1>
<div id="demo1">DEMO 1</div>
<p>
Script tags can also be placed in the body of an HTML document.
But to interact with an element on the page, you must ensure the
element is loaded before the script interacts with this element.
</p>
<div id="demo2">DEMO 2</div>
<p>Here, I have a script that will interact with the demo2 (light blue)
and demo3 (light green) divs.
<script>
document.getElementById("demo2").innerHTML = "From the script in the body";
document.getElementById("demo3").innerHTML = "From the script in the body";
</script>
<div id="demo3">DEMO 3</div>
<p></p>
<button type="button" onclick="myFunction();">Call Script in the head</button>
</body>
</html>
The Script Tag 1 on jsbin.com
JavaScript syntax basics
Comments
Javacript supports single line and multi-line comments:
// Single and multi line comments.
// this is an example of a single line comment.
/*
* this is an example
* of a
* multi line
* comment.
*/
Whitespace
Whitespace is also ignored in JavaScript.
const hello = "Hello";
const world = "World!";
Here's an example with whitespace added for readability:
let foo = function() {
for ( let i = 0; i < 10; i++ ) {
alert( i );
}
};
foo();
And the same code without whitespace. It much harder to read!
let foo=function() {for(let i=0;i<10;i++){alert(i);}};foo();
Reserved Words
There are a handful of reserved words that can't be used when declaring user-defined variables and functions. Some of these reserved words are currently implemented, some are saved for future use, and others are reserved for historical reasons.
A list of words and in-depth explanations for each can be found on the Mozilla Developer Network JavaScript Reference site.
Variables
Variables are containers for storing data. You can declare a variable in JavaScript:
- Using
var - Using
let - Using
const
Declaring variables with var
The var statement declares a function-scoped or globally-scoped variable, optionally initializing it to a value. In addition, variables declared with var are processed before any code is executed. This is called hoisting.
The scope of a variable declared with var is its current execution context and closures thereof, which is either the enclosing function and functions declared within it, or, for variables declared outside any function, global. Duplicate variable declarations using var will not trigger an error, even in strict mode, and the variable will not lose its value, unless another assignment is performed.
Declaring variables with let
The let statement declares a block-scoped local variable, optionally initializing it to a value.
let allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used, unlike the var keyword, which declares a variable globally, or locally to an entire function regardless of block scope. The other difference between var and let is that the latter is initialized to a value only when a parser evaluates it
Declaring variables with const
const allows you to declare and initialize a read-only variable that will hold a constant value and something that we can never change. Const variables are block-scoped, much like variables declared using the let keyword. The value of a constant can't be changed through reassignment (i.e. by using the assignment operator), and it can't be redeclared (i.e. through a variable declaration). However, if a variable declared with const is an object or array its properties or items can be updated or removed.
An initializer for a constant is required. You must specify its value in the same statement in which it's declared. (This makes sense, given that it can't be changed later.)
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutableâjust that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.
This declaration creates a constant whose scope can be either global or local to the block in which it is declared.
General Rule for declaring variables
In general, use const for declaring objects or arrays, and variables that will not change. Use let to declare variables that will change through reassignment. Use var only if your code needs to run on in older browsers.
Identifiers
Identifiers are used to give variables and functions a unique name so they can subsequently be referred to by that name. The name of an identifier must follow a few rules:
- Cannot be a reserved word.
- Can only be composed of letters, numbers, dollar signs, and underscores.
- The first character cannot be a number.
It's best practice to name identifers in a way that will make sense to you and other developers later on.
// Valid identifier names.
const myAwesomeVariable = "a";
const myAwesomeVariable2 = "b";
const my_awesome_variable = "c";
const $my_AwesomeVariable = "d";
const _my_awesome_variable_$ = "e";
Types
Types in JavaScript fall into two categories: primitives or objects.
In JavaScript, a primitive data type is a data type that is not an object and has no methods. The following are the primitive data types in JavaScript:
- Number: This data type is used to store numerical values, including integers and floating-point numbers.
- String: This data type is used to store a sequence of characters, such as words or sentences.
- Boolean: This data type is used to store true or false values.
- Symbol: This data type is used to create unique and immutable identifiers. It was introduced in ECMAScript 6.
- BigInt: This data type is used to store big integers that are beyond the safe integer range in JavaScript. It was introduced in ECMAScript 2020.
- undefined: This data type represents a variable that has been declared but does not have a value assigned to it.
- null: This data type is used to indicate that a variable has no value.
These primitive data types are stored in the memory as a single value and are immutable, meaning that once a primitive value is assigned, it can't be changed.
JavaScript also has non-primitive data types such as arrays and objects, which are also known as reference types. These types are stored in the memory as a reference to a location that contains the actual data.
In JavaScript, primitive data types are immutable, and non-primitive data types are mutable, which means that the values of non-primitive data types can be changed.
String
Strings are text wrapped in single or double quotation marks. It is best practice to consistently use one or the other. There may be times when the string contains quotation marks that collide with the ones used to create the string. In this case, either escape the characters using a \ backslash or use different quotes around the string.
Strings can created with double or single quotes.
let a = "I am a string";
let b = 'So am I!';
alert( a );
alert( b );
Sometimes a string may contain quotation marks.
const statement1 = 'He said "JavaScript is awesome!"';
const statement2 = "He said \"JavaScript is awesome!\"";
const welcome = "Hello World";
After the assignment of the literal string "Hello World", welcome is a string object.let result = welcome.length; //result is the number 11
result = welcome.toUpperCase(); //result is HELLO WORLD
result = welcome.toLowerCase(); //result is hello world
result = welcome.charAt( 0 ); //result is the character H
result = welcome.substr( 6, 5 ); //(start,length) result is the string World
result = welcome.substring( 6, 11 ); //(start,end) result is the string World
result = welcome.indexOf( "World", 0 ); //return is the number 6.
//If the string is not found indexOf returns -1
Example
JS Bin on jsbin.comNumber
Number types are any positive or negative numeric value. There is no distinction between integer and floating point values.
let num1 = 100;
let num2 = 100.10;
let num3 = 0.10;
JavaScript is a loosely typed language. Programmers used to strongly typed languages such as C++ or Java find this difficult to get used to. For example in C/C++/Java the following statements, including the integer division,
int result;
result = 5/10;
result would equal 0. In JavaScipt there are no explicit integers or floating point numbers. "Unofficially," you will get one or the other back.
result = 5/10;
result would be assigned 0.5
Example
JS BinJavaScript Precision
Integers are considered accurate up to 15 digits.
The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate:
let result;
result = 0.2 + 0.1; // result will be 0.30000000000000004
The solution to this problem depends on the type of problem you are dealing with. You can round the result, truncate it or work in a smaller unit. The easiest solution is to use correction factors (multiply by a suitable power of 10) so that the arithmetic happens between integers. For example, in the case of 0.2 + 0.1, the correction factor is 10, and you would performing the calculation:
let result;
result = (0.2 * 10) + (0.1 * 10) / 10; // result will be 0.3
In the case of 0.2 * 0.1, the correction factor would still be 10, but this time you would perform the calculation: let result;
result = (0.2 * 10) * (0.1 * 10) / (10 * 10); // result will be 0.02
Numbers in JavaScript are "double-precision 64-bit format IEEE 754 values".
0.1 + 0.2 == 0.3; //false
You can use parseInt to convert Strings to "Integers" and parseFloat to convert Strings to "Floats"
parseInt("20"); //20
parseInt("20.5"); //20
parseFloat("20.5"); //20.5
A special value, NaN ("Not a Number") is returned if the string is non-numeric.
parseInt("ABC", 10) //NaN
Type Coercion
JavaScript uses type coercion whenever it needs to perform an operation on two operands that need to be the same type and are not.
8 == "8" // true
Relying on type coercion is not a good idea.
null == udefined // true
false == undefined // false
false == "false" // false
'' == '0' // false
0 == '' // true
0 == '0' // true
To avoid type coercion, use the === and !== operators.
8 === "8" // false
null === udefined // false
false === undefined // false
false === "false" // false
'' === '0' // false
0 === '' // false
0 === '0' // false
Boolean
Boolean types are either true or false.
const okay = true;
const fail = false;
Null and Undefined
Null and undefined are special types in JavaScript. Null types are a value that represent the absence of a value, similar to many other programming languages. Undefined types represent a state in which no value has been assigned at all. This type is created in two ways: by using the undefined keyword or by not defining a value at all.
// Achieve a null value
let foo = null;
// Two ways to achieve an undefined value.
var bar1 = undefined;
var bar2;
Objects
Everything else is in JavaScript is considered an Object:
- Array: This data type is used to store a collection of values in a single variable. Each value in an array is called an element and is identified by an index.
let myArray = [1, 2, 3]; - Object: This data type is used to store a collection of key-value pairs. Objects are used to represent real-world objects and can be used to store data, methods, and properties.
let myObject = { name: "John", age: 30 }; - Function: This data type is used to store a block of code that can be executed when called. Functions can also be used as values and can be passed as parameters to other functions.
let myFunction = function(){console.log("Hello World")} - Date: This data type is used to work with dates and times.
let myDate = new Date(); - RegExp: This data type is used to work with regular expressions.
let myRegExp = /hello/g; - Map: This data type is used to store key-value pairs and was introduced in ECMAScript 6.
let myMap = new Map(); - Set: This data type is used to store unique values and was introduced in ECMAScript 6.
let mySet = new Set(); - Error: This data type is used to create error objects.
let myError = new Error("An error occurred");
Objects in JavaScript are also known as reference types, which means that they are stored in the memory as a reference to a location that contains the actual data. Unlike primitive data types, objects are mutable, which means that the values of their properties and methods can be changed.
JavaScript's objects are collections of key-value pairs, where keys can be any string and values can be any valid JavaScript data type, including other objects and functions.
JavaScript objects are also known as associative arrays, since they can store multiple values in a single variable and can be accessed using keys (property names) instead of index.
Objects in JavaScript are the foundation of the language and are used to create complex data structures and to represent real-world objects. They are used extensively in JavaScript applications, from basic data storage to more advanced functionality such as object-oriented programming.
String Concatenation
In JavaScript, concatenation is the process of combining two or more strings together. The `+` operator is one of the ways to concatenate strings in JavaScript.
For example, the following code concatenates two strings together:
let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName;
console.log(fullName); // Output: "John Doe"
In this example, the + operator is used to concatenate the firstName variable, a space " ", and the lastName variable together to form the fullName variable.
You can also use the + operator to concatenate a string with a number, in this case, JavaScript will convert the number to a string:
let num = 5;
let message = "The number is: " + num;
console.log(message); // Output: "The number is: 5"
You can also use the `+` operator multiple times to concatenate more than two strings:
let string1 = "Hello";
let string2 = " World";
let string3 = "!";
let finalString = string1 + string2 + string3;
console.log(finalString); // Output: "Hello World!"
It's important to note that the + operator is overloaded in JavaScript, which means that it has different meanings depending on the context. When used with numbers, it performs addition, when used with strings it performs concatenation, and when used with a mix of number and string, it performs concatenation and converts the number to a string.
String Interpolation
In JavaScript, the `${}` syntax is used for string interpolation, which is a way to insert the value of a variable or an expression into a string. It's also known as template literals.
When you use this syntax, you enclose the variable or expression that you want to insert within curly braces `{}` and precede it with a dollar sign `$`.
For example, the following code uses string interpolation to insert the value of the name variable into a string:
let name = "John";
console.log(`Hello, ${name}`); // Output: Hello, John
In the above example, the value of the name variable is inserted into the string by using string interpolation.
Another use case is to insert the result of an expression into a string
let number = 5;
console.log(`the number multiplied by 2 is: ${number*2}`);
// Output: the number multiplied by 2 is: 10
In this example, the `${number*2}` is an expression that is evaluated and the result is inserted into the string.
It's a more readable and elegant way to concatenate variables and expressions with strings compared to the traditional way of concatenating strings using the `+` operator.
It's also less error-prone as it can handle the type conversion automatically.
Conditional Statements
In JavaScript we have the following conditional statements:
- if statement - use this statement to execute some code only if a specified condition is true
- if...else statement - use this statement to execute some code if the condition is true and another code if the condition is false
- if...else if....else statement - use this statement to select one of many blocks of code to be executed
- switch statement - use this statement to select one of many blocks of code to be executed
If Statement
Use the if statement to execute some code only if a specified condition is true.
Syntax
if (condition) {
// code to be executed if condition is true
}
Example
if ( age < 16 ) {
entry = "free";
}
If...else Statement
Use the if....else statement to execute some code if a condition is true and another code if the condition is not true.
Syntax
if ( condition ) {
// code to be executed if condition is true
} else {
// code to be executed if condition is not true
}
Example
if ( age < 16 ) {
entry = "free";
} else {
entry = "£10";
}
If Else Statement using the ternary operator '?'
Note that it is also possible to write an if else statement in a more concise way in JavaScript, using the ternary operator '?'
The ternary operator ? is a shorthand way to write an if-else statement. It's a shorthand for an if else statement, it's also known as a ternary if else statement.
It's used like this:condition ? true : false
So it is possible to rewrite the above example using the ternary operator as follows:
let entry = (age < 16) ? "free" : "£10";
If...else if....else Statement
Use the if....else if...else statement to select one of several blocks of code to be executed.
Syntax
if ( condition1 ) {
// code to be executed if condition1 is true
} else if ( condition2 ) {
// code to be executed if condition2 is true
} else {
// code to be executed if neither condition1 nor condition2 is true
}
Example
if ( age < 12 ) {
entry = "free";
} else if ( age < 18 ) {
entry = "£10";
} else {
entry = "£20";
}
If...else if....else Statement wiht the ternary operator
The above example can also be written with the ternary operator as follows:
let entry = (age < 12) ? "free" : (age < 18) ? "£10" : "£20";
Question
Are these equivalent and why?
|
|
The JavaScript Switch Statement
Syntax
switch( n ) {
case 1:
// execute code block 1
break;
case 2:
// execute code block 2
break;
default:
// code to be executed if n is different from case 1 and 2
}
Example
let day = new Date().getDay();
switch ( day ) {
case 0:
message = "Today is Sunday";
break;
case 1:
message = "Today is Monday";
break;
case 2:
message = "Today is Tuesday";
break;
case 3:
message = "Today is Wednesday";
break;
case 4:
message = "Today is Thursday";
break;
case 5:
message = "Today is Friday";
break;
case 6:
message = "Today is Saturday";
break;
}
document.write( message );
Interactive Example
JS BinExample with default
let day = new Date().getDay();
switch ( day )
{
case 0:
message = "Today is Sunday";
break;
case 6:
message = "Today is Saturday";
break;
default:
message = "Looking forward to the weekend";
}
document.write( message );
A new syntax in ES6
ES6 (ECMAScript 6) is a version of JavaScript that introduced new syntax and features. The basic structure and functionality of a `switch` statement remains the same in ES6 (ECMAScript 6) as in previous versions of JavaScript. The code above would work the same way in ES6 as it would in earlier versions of JavaScript. However, in ES6, you can use `Map()` and `Object.entries()` for more elegant and readable way to write the switch statement, also it's more efficient because the lookup time of a `Map()` is generally faster than a `switch` statement.
The code snippets above could be written as follows:
let day = new Date().getDay();
const days = new Map([
[0, "Sunday"],
[1, "Monday"],
[2, "Tuesday"],
[3, "Wednesday"],
[4, "Thursday"],
[5, "Friday"],
[6, "Saturday"]
]);
let message = `Today is ${days.get(day)}`;
document.write( message );
and with default:
let day = new Date().getDay();
const days = new Map([
[0, "Sunday"],
[6, "Saturday"]
]);
let message = days.get(day) ? `Today is ${days.get(day)}` : "Looking forward to the weekend";
document.write( message );
Comparison Operators
Comparison operators are used in logical statements to determine equality or difference between variables or values.
x = 5; |
|
Logical Operators
Logical operators are used to determine the logic between variables or values
x = 5; y = 3; |
|
JavaScript Loops
In JavaScript we have the following loops:
- for - loops through a block of code a number of times
- for/in - loops through the properties of an object
- while - loops through a block of code while a specified condition is true
- do/while - also loops through a block of code while a specified condition is true
The For Loop
The for loop is often the tool you will use when you want to create a loop. This will often be used if you want to repeat the same code a number of times, each time with a different value.
Syntax
for (initial statement; boolean expression; statement) {
// the code block to be executed
}
- initial statement This statment is executed before looping begins.
- boolean expression This expression is evaluated to true or false. If true the loop is entered.
- Statement This statement is executed at the end of each loop.
Example
for ( let counter=0; counter < 10; counter++ ) {
document.write( "<p>" );
document.write( "Counter is: " + counter );
document.write( "<p>" );
}
The While Loop
The while loop allows you to run a block of code while a condition is true. If the condition is not true at the start, the block of code inside the while loop will not be executed at all.
Syntax
while ( boolean expression ) {
// the code block to be executed
}
- boolean expression This expression is evaluated to true or false. If true the loop is entered.
- Statement(s) Code block to be executed
Example
let counter = 0;
while( counter < 10 ) {
document.write( "<p>" );
document.write( "Counter is: " + counter );
document.write( "</p>" );
counter++;
}
The Do While Loop
The do while loop allows you to run a block of code once, and to continue to run it while a condition is true. If the condition is not true at the start, the block of code inside curly braces will be executed once, as the condition check only takes place at the end of the execution of that block of code. This is particularly useful when asking for user input and validating it. You can ask the user to enter their input once, and to repeat as long as the value they have entered is invalid, see Example 2.
Syntax
do {
// the code block to be executed
} while ( boolean expression );
- boolean expression This expression is evaluated to true or false. If true the loop is re-entered.
- Statement(s) Code block to be executed
Example 1
counter = 0;
do {
document.write( "<p>" );
document.write( "Counter is: " + counter );
document.write( "</p>" );
counter++;
} while ( counter < 10 );
Example 2
let num1Valid = false;
let userNumber1;
do {
userNumber1 = parseInt(prompt("Please choose a number betwee 1 and 59:"));
if (!(Number.isInteger(userNumber1))) {
alert("Error: The number you entered is not an integer");
} else if ((userNumber1 < 1) || (userNumber1 > 59)) {
alert("Error: The number must be between 1 and 59");
} else {
num1Valid = true;
}
} while (num1Valid != true);
The Break Statement
The break statement breaks the loop and continues executing the code after the loop (if any):
Example
let counter = 0;
while ( true ) { //potentially infinite loop
if ( counter > 5 ) {
break;
}
counter++;
}
The Continue Statement
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
Example
let counter = 0;
while ( counter < 6 ) {
counter++;
if ( counter % 2 == 0 ) {
continue;
}
document.write( "Counter is now: " + counter );
}
JavaScript Dialog Boxes
alert();
Show a dialog box with a message
Example
alert( "Your Message Goes Here!" );
confirm();
Show a dialog box and return a boolean
Example
let answer = confirm( "Are you sure you want to close...." );
if ( answer == true ) {
alert( "You said OK!" );
} else {
alert( "You said Cancel!" );
}
prompt();
Show a dialog box and return a string
Example
let answer = prompt( "Enter something here:", "anything will do" );
alert( "You said " + answer );
Line breaks in dialog boxes
To display line breaks inside a popup box, use a backslash followed by the character n.
Example
alert( "Hello,\nHow are you?" );
It's worth noting that most of the above mentioned methods are considered old fashioned and a bad practice to use them, because they can be very disruptive for the user, can block the user's interaction with the web page, and can cause accessibility issues for users with screen readers. They are generally discouraged and modern web development practices use other methods to create dialogs or notifications.
There are new ways to show messages or dialogs that are not as intrusive as the previous ones, such as using modal or toast dialogs that are integrated into the web page's design. You can create these dialogs using JavaScript libraries or frameworks such as Bootstrap, Foundation, or Materialize.
Review Questions
- Question 1 - Which HTML tags are used to hold JavaScript code?
- Question 2 - In which parts of the HTML document should the scripts go?
- Question 3 - If you are going to interact with elements on the page, where should your script go?
- Question 4 - Would it make sense to have a
stringholding HTML code as a parameter for theinnerHTML()method? - Question 5 - Would it make sense to have a
stringholding HTML code as a parameter for thealert()method? - Question 6 - What are the 3 ways to declare variables and what are their differences?
- Question 7 - What are the 3 JavaScript dialog boxes and what are their differences?