Java Script
Java Script
Java Script
JavaScript is a dynamic computer programming language. It is lightweight and most commonly used as a
part of web pages, whose implementations allow client-side script to interact with the user and make
dynamic pages. It is an interpreted programming language with object-oriented capabilities.
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly because of
the excitement being generated by Java. JavaScript made its first appearance in Netscape 2.0 in 1995 with
the name LiveScript. The general-purpose core of the language has been embedded in Netscape, Internet
Explorer, and other web browsers.
JavaScript is a lightweight, interpreted programming language.
Designed for creating network-centric applications.
Complementary to and integrated with Java.
Complementary to and integrated with HTML.
Open and cross-platform
1
First Java Script Code:
<html>
<body>
<script language = "javascript" type = "text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>
</body>
</html>
<html>
<head>
</head>
<body>
<script type = "text/javascript">
<!--
document.write("Hello World")
//-->
</script>
External JavaScript
External file: myScript.js
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
External scripts are practical when the same code is used in many different web pages.
JavaScript files have the file extension .js.
To use an external script, put the name of the script file in the src (source) attribute of a <script> tag:
<script src="myScript.js"></script>
You can place an external script reference in <head> or <body> as you like.
3
JavaScript versions
JavaScript was invented by Brendan Eich in 1995, and became an ECMA( European Computer Manufacturer's
Association) standard in 1997.
ECMAScript versions have been abbreviated to ES1, ES2, ES3, ES5, and ES6.
Since 2016, versions are named by year (ECMAScript 2016, 2017, 2018, 2019, 2020).
JavaScript Output
JavaScript Display Possibilities
JavaScript can "display" data in different ways:
Writing into an HTML element, using innerHTML.
Writing into the HTML output using document.write().
Writing into an alert box, using window.alert().
Writing into the browser console, using console.log().
Using innerHTML
To access an HTML element, JavaScript can use the document.getElementById(id) method.
The id attribute defines the HTML element. The innerHTML property defines the HTML content:
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Using document.write()
For testing purposes, it is convenient to use document.write():
Example
<!DOCTYPE html>
<html>
<body>
<script>
document.write(5 + 6);
</script>
4
</body>
</html>
Using document.write() after an HTML document is loaded, will delete all existing HTML:
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Using window.alert()
You can use an alert box to display data:
Example
<!DOCTYPE html>
<html>
<body>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
In JavaScript, the window object is the global scope object. This means that variables, properties, and
methods by default belong to the window object. This also means that specifying the window keyword is
optional:
alert(5 + 6);
Using console.log()
For debugging purposes, you can call the console.log() method in the browser to display data.
Example
<h2>Activate Debugging</h2>
<script>
console.log(5 + 6);
5
</script>
Semicolons
A semicolon may be omitted in most cases when a line break exists.
This would also work:
alert('Hello')
alert('World')
Here, JavaScript interprets the line break as an “implicit” semicolon. This is called an automatic semicolon
insertion.
In most cases, a newline implies a semicolon. But “in most cases” does not mean “always”!
There are cases when a newline does not mean a semicolon. For example:
alert(3 +
1
+ 2);
The code outputs 6 because JavaScript does not insert semicolons here. It is intuitively obvious that if the
line ends with a plus "+", then it is an “incomplete expression”, so a semicolon there would be incorrect. And
in this case, that works as intended.
But there are situations where JavaScript “fails” to assume a semicolon where it is really needed.
Errors which occur in such cases are quite hard to find and fix.
An example of an error
If you’re curious to see a concrete example of such an error, check this code out:
alert("Hello");
[1, 2].forEach(alert);
No need to think about the meaning of the brackets [] and forEach yet. We’ll study them later. For now, just
remember the result of running the code: it shows Hello, then 1, then 2.
Now let’s remove the semicolon after the alert:
alert("Hello")
[1, 2].forEach(alert);
The difference compared to the code above is only one character: the semicolon at the end of the first line is
gone.
If we run this code, only the first Hello shows (and there’s an error, you may need to open the console to see
it). There are no numbers any more.
That’s because JavaScript does not assume a semicolon before square brackets [...]. So, the code in the last
example is treated as a single statement.
Here’s how the engine sees it:
alert("Hello")[1, 2].forEach(alert);
Looks weird, right? Such merging in this case is just wrong. We need to put a semicolon after alert for the
code to work correctly.
6
This can happen in other situations also.
We recommend putting semicolons between statements even if they are separated by newlines. This rule is
widely adopted by the community. Let’s note once again – it is possible to leave out semicolons most of the
time. But it’s safer – especially for a beginner – to use them.
JavaScript Values
The JavaScript syntax defines two types of values:
Fixed values
Variable values
Fixed values are called Literals.
Variable values are called Variables.
JavaScript Literals
The two most important syntax rules for fixed values are:
1. Numbers are written with or without decimals:
10.50
1001
"John Doe"
'John Doe'
JavaScript Variables
In a programming language, variables are used to store data values.
avaScript Variables can be declared in 4 ways:
Automatically
Using var
Using let
Using const
x = 5;
y = 6;
z = x + y;
var x = 5;
var y = 6;
var z = x + y;
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.
let x = 5;
let y = 6;
let z = x + y;
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.
7
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.
<h2>JavaScript Variables</h2>
<p id="demo"></p>
<script>
let x;
x = 6;
document.getElementById("demo").innerHTML = x;
</script>
JavaScript Identifiers
All JavaScript variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
Names can contain letters, digits, underscores, and dollar signs.
Names must begin with a letter.
Names can also begin with $ and _ (but we will not use it in this tutorial).
Names are case sensitive (y and Y are different variables).
Reserved words (like JavaScript keywords) cannot be used as names.
8
1. String
2. Number
Besides regular numbers, there are so-called “special numeric values” which also belong to this data
type: Infinity, -Infinity and NaN.
Infinity represents the mathematical Infinity ∞. It is a special value that’s greater than any number.
We can get it as a result of division by zero:
alert( 1 / 0 ); // Infinity
Or just reference it directly:
3. Bigint
In JavaScript, the “number” type cannot safely represent integer values larger than (253-
1) (that’s 9007199254740991), or less than -(253-1) for negatives.
(let x = BigInt("123456789012345678901234567890");)
A BigInt value is created by appending n to the end of an integer:
6. Null
7. Symbol
8. Object
JavaScript Operators
There are different types of JavaScript operators:
Arithmetic Operators
Assignment Operators
Comparison Operators
String Operators
Logical Operators
Bitwise Operators
Ternary Operators
9
Type Operators
Arithmetic Operator
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement
String Comparison
String Addition
Adding two numbers, will return the sum, but adding a number and a string will return a string:
10
Example
let x = 5 + 5;
let y = "5" + 5;
let z = "Hello" + 5;
When comparing values of different types, JavaScript converts the values to numbers.
For example:
A funny consequence
It is possible that at the same time:
Two values are equal.
One of them is true as a boolean and the other one is false as a boolean.
For example:
let a = 0;
alert( Boolean(a) ); // false
let b = "0";
alert( Boolean(b) ); // true
Strict equality
A regular equality check == has a problem. It cannot differentiate 0 from false:
11
In other words, if a and b are of different types, then a === b immediately returns false without an attempt to convert
them.
Let’s try it:
An incomparable undefined
Avoid problems
Why did we go over these examples? Should we remember these peculiarities all the time? Well, not really. Actually,
these tricky things will gradually become familiar over time, but there’s a solid way to avoid problems with them:
Treat any comparison with undefined/null except the strict equality === with exceptional care.
Don’t use comparisons >= > < <= with a variable which may be null/undefined, unless you’re really sure of what
you’re doing. If a variable can have these values, check for them separately.
Operator Description
Typeof Returns the type of a variable
instanceof Returns true if an object is an instance of an object type
typeof 0 // "number"
Type Conversions
Most of the time, operators and functions automatically convert the values given to them to the right type.
For example, alert automatically converts any value to a string to show it. Mathematical operations convert
values to numbers.
There are also cases when we need to explicitly convert a value to the expected type.
String Conversion
String conversion happens when we need the string form of a value.
For example, alert(value) does it to show the value.
We can also call the String(value) function to convert a value to a string:
Numeric Conversion
Numeric conversion in mathematical functions and expressions happens automatically.
For example, when division / is applied to non-numbers:
14
alert(typeof num); // number
Explicit conversion is usually required when we read a value from a string-based source like a text form but
expect a number to be entered.
If the string is not a valid number, the result of such a conversion is NaN. For instance:
Value Becomes…
undefined NaN
null 0
Whitespaces (includes spaces, tabs \t, newlines \n etc.) from the start and end are removed.
string If the remaining string is empty, the result is 0. Otherwise, the number is “read” from the
string. An error gives NaN.
Examples:
Boolean Conversion
Boolean conversion is the simplest one.
It happens in logical operations (later we’ll meet condition tests and other similar things) but can also be
performed explicitly with a call to Boolean(value).
The conversion rule:
Values that are intuitively “empty”, like 0, an empty string, null, undefined, and NaN, become false.
Other values become true.
For instance:
Conditional Statements
The if Statement
Use the if statement to specify a block of JavaScript code to be executed if a condition is true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
let year = prompt('In which year was ECMAScript-2015 specification published?', '');
if (year == 2015) alert( 'You are right!' );
The else if Statement
Use the else if statement to specify a new condition if the first condition is false.
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
16
case 'value1': // if (x === 'value1')
...
[break]
default:
...
[break]
}
The value of x is checked for a strict equality to the value from the first case (that is, value1) then to the
second (value2) and so on.
let a = "1";
let b = 0;
switch (+a) {
case b + 1:
alert("this runs, because +a is 1, exactly equals b+1");
break;
default:
alert("this doesn't run");
}
Here +a gives 1, that’s compared with b + 1 in case, and the corresponding code is executed.
Type matters
Let’s emphasize that the equality check is always strict. The values must be of the same type to match.
For example, let’s consider the code:
case '2':
alert( 'Two' );
break;
case 3:
alert( 'Never executes!' );
break;
default:
alert( 'An unknown value' );
}
}
}
Function
function showMessage() {
alert( 'Hello everyone!' );
}
showMessage();
showMessage();
18
Local variables
A variable declared inside a function is only visible inside that function.
For example:
function showMessage() {
let message = "Hello, I'm JavaScript!"; // local variable
alert( message );
}
Outer variables
A function can access an outer variable as well, for example:
function showMessage() {
let message = 'Hello, ' + userName;
alert(message);
}
function showMessage() {
userName = "Bob"; // (1) changed the outer variable
showMessage();
19
let userName = 'John';
function showMessage() {
let userName = "Bob"; // declare a local variable
alert( userName ); // John, unchanged, the function did not access the outer variable
Global variables
Variables declared outside of any function, such as the outer userName in the code above, are called global.
Global variables are visible from any function (unless shadowed by locals).
It’s a good practice to minimize the use of global variables. Modern code has few or no globals. Most
variables reside in their functions. Sometimes though, they can be useful to store project-level data.
Parameters
We can pass arbitrary data to functions using parameters.
In the example below, the function has two parameters: from and text.
Here’s one more example: we have a variable from and pass it to the function. Please note: the function
changes from, but the change is not seen outside, because a function always gets a copy of the value:
// the value of "from" is the same, the function modified a local copy
alert( from ); // Ann
20
When a value is passed as a function parameter, it’s also called an argument.
In other words, to put these terms straight:
A parameter is the variable listed inside the parentheses in the function declaration (it’s a declaration time
term).
An argument is the value that is passed to the function when it is called (it’s a call time term).
We declare functions listing their parameters, then call them passing arguments.
In the example above, one might say: "the function showMessage is declared with two parameters, then
called with two arguments: from and "Hello"".
Default values
If a function is called, but an argument is not provided, then the corresponding value becomes undefined.
For instance, the aforementioned function showMessage(from, text) can be called with a single argument:
showMessage("Ann");
That’s not an error. Such a call would output "*Ann*: undefined". As the value for text isn’t passed, it
becomes undefined.
We can specify the so-called “default” (to use if omitted) value for a parameter in the function declaration,
using =:
21
Alternative default parameters
Sometimes it makes sense to assign default values for parameters at a later stage after the function
declaration.
We can check if the parameter is passed during the function execution, by comparing it with undefined:
function showMessage(text) {
// ...
alert(text);
}
function showMessage(text) {
// if text is undefined or otherwise falsy, set it to 'empty'
text = text || 'empty';
...
}
Modern JavaScript engines support the nullish coalescing operator ??, it’s better when most falsy values,
such as 0, should be considered “normal”:
function showCount(count) {
// if count is undefined or null, show "unknown"
alert(count ?? "unknown");
}
showCount(0); // 0
showCount(null); // unknown
showCount(); // unknown
Returning a value
A function can return a value back into the calling code as the result.
The simplest example would be a function that sums two values:
function sum(a, b) {
return a + b;
}
The directive return can be in any place of the function. When the execution reaches it, the function stops,
and the value is returned to the calling code (assigned to result above).
22
There may be many occurrences of return in a single function. For instance:
function checkAge(age) {
if (age >= 18) {
return true;
} else {
return confirm('Do you have permission from your parents?');
}
}
if ( checkAge(age) ) {
alert( 'Access granted' );
} else {
alert( 'Access denied' );
}
It is possible to use return without a value. That causes the function to exit immediately.
For example:
function showMovie(age) {
if ( !checkAge(age) ) {
return;
}
function doNothing() {
return;
}
return
(some + long + expression + or + whatever * f(a) + f(b))
That doesn’t work, because JavaScript assumes a semicolon after return. That’ll work the same as:
23
return;
(some + long + expression + or + whatever * f(a) + f(b))
So, it effectively becomes an empty return.
If we want the returned expression to wrap across multiple lines, we should start it at the same line as return.
Or at least put the opening parentheses there as follows:
return (
some + long + expression
+ or +
whatever * f(a) + f(b)
)
And it will work just as we expect it to.
Naming a function
Functions are actions. So their name is usually a verb. It should be brief, as accurate as possible and describe
what the function does, so that someone reading the code gets an indication of what the function does.
It is a widespread practice to start a function with a verbal prefix which vaguely describes the action. There
must be an agreement within the team on the meaning of the prefixes.
For instance, functions that start with "show" usually show something.
Function starting with…
"get…" – return a value,
"calc…" – calculate something,
"create…" – create something,
"check…" – check something and return a boolean, etc.
Examples of such names:
24
These examples assume common meanings of prefixes. You and your team are free to agree on other
meanings, but usually they’re not much different. In any case, you should have a firm understanding of what
a prefix means, what a prefixed function can and cannot do. All same-prefixed functions should obey the
rules. And the team should share the knowledge.
Ultrashort function names
Functions that are used very often sometimes have ultrashort names.
For example, the jQuery framework defines a function with $. The Lodash library has its core function
named _.
These are exceptions. Generally function names should be concise and descriptive.
Function expressions
There is another syntax for creating a function that is called a Function Expression.
It allows us to create a new function in the middle of any expression.
For example:
Function is a value
Let’s reiterate: no matter how the function is created, a function is a value. Both examples above store a
function in the sayHi variable.
We can even print out that value using alert:
function sayHi() {
alert( "Hello" );
}
In JavaScript, a function is a value, so we can deal with it as a value. The code above shows its string
representation, which is the source code.
25
We can copy a function to another variable:
alert( sum(1, 2) ); // 3
If we have only one argument, then parentheses around parameters can be omitted, making that even shorter.
For example:
alert( double(3) ); // 6
If there are no arguments, parentheses are empty, but they must be present:
26
let sayHi = () => alert("Hello!");
sayHi();
Arrow functions can be used in the same way as Function Expressions.
For instance, to dynamically create a function:
welcome();
The Object Datatype
The object data type can contain:
1. An object
2. An array
3. A date
JavaScript Objects
Real Life Objects, Properties, and Methods
In real life, a car is an object.
A car has properties like weight and color, and methods like start and stop:
All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but the methods are performed at different times.
JavaScript Objects
You have already learned that JavaScript variables are containers for data values.
This code assigns a simple value (Fiat) to a variable named car:
let car = "Fiat";
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable named car:
const car = {type:"Fiat", model:"500", color:"white"};
The values are written as name:value pairs (name and value separated by a colon).
27
It is a common practice to declare objects with the const keyword.
Learn more about using const with objects in the chapter: JS Const.
Object Definition
Example
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
Object Methods
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
What is this?
28
In JavaScript, the this keyword refers to an object.
Which object depends on how this is being invoked (used or called).
The this keyword refers to different objects depending on how it is used:
JavaScript Arrays
An array is a special variable, which can hold more than one value:
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";
Using the JavaScript Keyword new
The following example also creates an Array, and assigns values to it:
Example
const cars = new Array("Saab", "Volvo", "BMW");
The two examples above do exactly the same.
There is no need to use new Array().
For simplicity, readability and execution speed, use the array literal method.
Accessing Array Elements
You access an array element by referring to the index number:
const cars = ["Saab", "Volvo", "BMW"];
let car = cars[0];
Access entire array:
<script>
const cars = ["Saab", "Volvo", "BMW"];
document.write(cars);
</script>
29
What are Cookies?
Cookies are data, stored in small text files, on your computer.
When a web server has sent a web page to a browser, the connection is shut down, and the server forgets
everything about the user.
Cookies were invented to solve the problem "how to remember information about the user":
When a user visits a web page, his/her name can be stored in a cookie.
Next time the user visits the page, the cookie "remembers" his/her name.
Cookies are saved in name-value pairs like:
username = John Doe
Create a Cookie with JavaScript
JavaScript can create, read, and delete cookies with the document.cookie property.
With JavaScript, a cookie can be created like this:
document.cookie = "username=John Doe";
You can also add an expiry date (in UTC time). By default, the cookie is deleted when the browser is closed:
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";
With a path parameter, you can tell the browser what path the cookie belongs to. By default, the cookie
belongs to the current page.
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";
30
If you want to find the value of one specified cookie, you must write a JavaScript function that
searches for the cookie value in the cookie string.
Example explained:
The parameters of the function above are the name of the cookie (cname), the value of the cookie (cvalue),
and the number of days until the cookie should expire (exdays).
The function sets a cookie by adding together the cookiename, the cookie value, and the expires string.
A Function to Get a Cookie
Then, we create a function that returns the value of a specified cookie:
Example
function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for(let i = 0; i <ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
Function explained:
Take the cookiename as parameter (cname).
31
Create a variable (name) with the text to search for (cname + "=").
Decode the cookie string, to handle cookies with special characters, e.g. '$'
Split document.cookie on semicolons into an array called ca (ca = decodedCookie.split(';')).
Loop through the ca array (i = 0; i < ca.length; i++), and read out each value c = ca[i]).
If the cookie is found (c.indexOf(name) == 0), return the value of the cookie (c.substring(name.length,
c.length).
If the cookie is not found, return "".
A Function to Check a Cookie
Last, we create the function that checks if a cookie is set.
If the cookie is set, it will display a greeting.
If the cookie is not set, it will display a prompt box, asking for the name of the user, and stores the username
cookie for 365 days, by calling the setCookie function:
Example
function checkCookie() {
let username = getCookie("username");
if (username != "") {
alert("Welcome again " + username);
} else {
username = prompt("Please enter your name:", "");
if (username != "" && username != null) {
setCookie("username", username, 365);
}
}
}
32