5 JavaScript
5 JavaScript
What is JavaScript?
JavaScript was initially created to “make web pages alive”.
They can be written right in a web page’s HTML and run automatically as the page loads.
Scripts are provided and executed as plain text. They don’t need special preparation or
compilation to run.
In this aspect, JavaScript is very different from another language called Java.
Why JavaScript?
When JavaScript was created, it initially had another name: “LiveScript”.
But as it evolved, JavaScript became a fully independent language with its own specification
called ECMAScript, and now it has no relation to Java at all.
Today, JavaScript can execute not only in the browser, but also on the server, or actually on any
device that has a special program called the JavaScript engine. The browser has an embedded
engine sometimes called a “JavaScript Virtual Machine”.
JavaScript is the only browser technology that combines these three things. That’s what makes
JavaScript unique. That’s why it’s the most widespread tool for creating browser interfaces.
That said, JavaScript also allows to create servers, mobile applications, etc.
CODE EDITORS
Code editors
A code editor is the place where programmers spend most of their time.
There are two main types of code editors: IDEs and lightweight editors. Many people use one
tool of each type.
External scripts
<script src=“/path/to/script.js”></script>
CODE STRUCTURE
Statements
We can have as many statements in our code as we want. Statements can be separated with a
semicolon.
1 . alert(‘Hello’); alert(‘World’);
Usually, statements are written on separate lines to make the code more readable:
1 . alert(‘Hello’);
2 . alert(‘World’);
Semicolons
A semicolon may be omitted in most cases when a line break exists.
1 . alert(‘Hello’)
2 . alert(‘World’)
Here, JavaScript interprets the line break as an “implicit” semicolon. This is called an automatic
semicolon insertion.
OUTPUT
JavaScript Display
JavaScript can "display" data in different ways:
● Console
● Document Write
● Inner HTML
● Window popup boxes
Console
Writing into the browser console.
1 . console.log(“Hello World”);
Document write
Writing into the HTML output..
1 . document.write(“Hello World”);
Inner HTML
Writing into an HTML element.
1 . <h1 id=“heading”></h1>
2 . document.getElementById(“heading”).innerHTML = “Hello World”;
Window popup boxes
Alert
1 . alert(“Hello World”);
Confirm
1 . var boss = confirm(“Are you the boss?”);
2 . alert(boss);
Prompt
1 . var age = prompt(“How old are you?”);
2 . alert(`You are ${age} years old.`);
VARIABLES
Variable naming
There are two limitations on variable names in JavaScript:
1. The name must contain only letters, digits, or the symbols $ and _.
2. The first character must not be a digit.
let
1 . let firstName = ‘John’, lastName = ‘Doe’;
var
1 . var firstName = ‘John’, lastName = ‘Doe’;
const
1 . const PI = 3.14;
Uppercase constants
There is a widespread practice to use constants as aliases for difficult-to-remember values that
are known prior to execution.
Besides regular numbers, there are so-called “special numeric values” which also belong to this
data type: Infinity and NaN.
1 . alert(1/0); // Infinity
2 . alert(‘not a number’ / 2); // NaN
A string
A string in JavaScript must be surrounded by quotes.
1 . var str1 = “Hello World”;
2 . var str2 = ‘Single quotes are ok too’;
3 . var str3 = `can embed ${str1}`;
Backticks are “extended functionality” quotes. They allow us to embed variables and
expressions into a string by wrapping them in ${…}.
1 . var userName = “John Doe”;
2 . alert(`Hello, ${userName}`);
A boolean
The boolean type has only two values: true and false.
This type is commonly used to store yes/no values: true means “yes, correct”, and false means
“no, incorrect”.
In JavaScript, null is not a “reference to a non-existing object” or a “null pointer” like in some
other languages.
It’s just a special value which represents “nothing”, “empty” or “value unknown”.
The code above states that age is unknown or empty for some reason.
The “undefined” value
The special value undefined also stands apart. It makes a type of its own, just like null. The
meaning of undefined is “value is not assigned”. If a variable is declared, but not assigned,
then its value is undefined:
1 . var num;
2 . alert(num); // shows “undefined”
1 . var userName;
2 . console.log(userName); // shows “undefined”
OPERATORS
JavaScript | Operators
An operator is capable of manipulating a certain value or operand. Operators are used to
perform specific mathematical and logical computations on operands. In other words, we can
say that an operator operates the operands. In JavaScript operators are used for compare
values, perform arithmetic operations etc.
An operator is unary if it has a single operand. For example, the unary negation - reverses the
sign of a number:
1 . var x = 1;
2 . x = -x;
3 . alert( x ); // -1, unary negation was applied
An operator is binary if it has two operands. The same minus exists in binary form as well:
1 . var x = 5, y = 10;
2 . alert( y-x ); // 5, binary minus subtracts values
String concatenation, binary +
Usually, the plus operator + sums numbers.
Note that if one of the operands is a string, the other one is converted to a string too.
1 . alert(‘1’ + 2); // “12”
2 . alert(2 + ‘1’); // “21”
String concatenation and conversion is a special feature of the binary plus +. Other arithmetic
operators work only with numbers and always convert their operands to numbers.
1 . alert(2 - ‘1’); // 1
2 . alert(‘6’ / 2); // 3
3 . alert(‘6’ * ‘6’); // 36
Operator precedence
We all know that the multiplication in the expression 1 + 2 * 3 should be calculated before the
addition. That’s exactly the precedence thing.
The multiplication is said to have a higher precedence than the addition. Parentheses override
any precedence, so if we’re not satisfied with the default order, we can use them to change it.
For example, write (1 + 2) * 3.
Name Sign
unary plus +
unary negation -
multiplication *
division /
addition +
subtraction -
assignment =
Arithmetic operators
There are various arithmetic operators:
+= Sums up left and right operand values and assign the result to the left operand.
1 . x += 1; // x would be 11
-= Subtract right operand value from left operand value and assign the result to the left operand.
1 . x -= 1; // x would be 10
*= Multiply left and right operand values and assign the result to the left operand.
1 . x *= 5; // x would be 50
/= Divide left operand value by right operand value and assign the result to the left operand.
1 . x /= 5; // x would be 10
%= Get the modulus of left operand divide by right operand and assign resulted modulus to the left operand.
1 . x %= 2; // x would be 0
Comparison operators
There are various comparison operators:
== Compares the equality of two operands. If equal then the condition is true otherwise false.
1 . var x = 5, y = 10;
2 . alert(x == y); // false
=== Compares equality of two operands with type. If equal (type and value both) then the
condition is true otherwise false.
1 . var x = 10, y = ‘10’;
2 . alert(x === 10); // true
3 . alert(y === 10); // false
!= (Not Equal): Compares inequality of two operands. True if operands are not equal.
1 . var x = 5;
2 . alert(x != 10); // true
> (Greater than): This operator check whether the left side value is greater than the right side
value. If yes then it returns true otherwise it returns false.
1 . var x = 5;
2 . alert(x > 10); // false
< (Less than): This operator check whether the left side value is less than the right side value. If
yes then it returns true otherwise it returns false.
1 . var x = 5;
2 . alert(x < 10); // true
>= (Greater than or Equal to): This operator check whether the left side value is greater than or
equal to the right side value. If yes then it returns true otherwise it returns false.
1 . var x = 5;
2 . alert(x >= 10); // false
<= (Less than or Equal to): This operator check whether the left side value is less than or equal
to the right side value. If yes then it returns true otherwise it returns false.
1 . var x = 5;
2 . alert(x <= 5); // true
Logical operators
There are various logical operators:
&& (Logical AND): It checks whether two operands are non-zero (0, false, undefined, null or “”
are considered as zero), if yes then return 1 otherwise 0.
1 . var x = 5, y = 10;
2 . alert((x == 5) && (y == 10)); // true
|| (Logical OR): It checks whether any one of the two operands is non-zero (0, false, undefined,
null or “” is considered as zero). Thus || returns true if either operand is true and if both are false
it returns false.
1 . var x = 5, y = 10;
2 . alert((x == 50) || (y == 100)); // false
! (Logical NOT): It reverses the boolean result of the operand (or condition).
1 . var x = 5, y = 10;
2 . alert(!((x == 50) || (y == 100))); // true
Ternary operators
:? It is like the short form of the if-else condition.
Syntax:
res = ? X : Y;
Where X and Y are values and if condition is true then res = X otherwise res = Y.
1. As an operator: typeof x.
2. As a function: typeof(x).
ToString
String conversion happens when we need the string form of a value.
For instance:
1 . alert(Boolean(1)); // true
2 . alert(Boolean(0)); // false
3 . alert(Boolean(‘Hello’)); // true
4 . alert(Boolean(‘ ’)); // spaces, also true
5 . alert(Boolean(‘’)); // false
Conditional Statements
IF, SWITCH
The “if” statement
The if(...) statement evaluates a condition in parentheses and, if the result is true, executes a
block of code {}.
3 . if(year == 2019) {
4 . alert(‘You are right!’);
5 . }
1 . var accessAllowed;
2 . var age = prompt(“How old are you?”);
3 .
11 . alert(accessAllowed);
1 . var today = prompt(‘ENTER TODAY’);
2 .
3 . if(today == ‘Monday’)
4 . alert(‘Today’s Monday’);
5 . else if(today == ‘Tuesday’)
6 . alert(‘Today’s Tuesday’);
7 . else
8 . alert(‘Wrong day!’);
Multiple ‘?’
A sequence of question mark operators ? can return a value that depends on more than one
condition. It is like the short form of the ternary operator.
8 . alert(message);
The “switch” statement
A switch statement can replace multiple if checks. It gives a more descriptive way to compare
a value with multiple variants.
3 . switch (browser) {
4 . case ‘edge’: alert(‘You have got the microsoft edge.’); break;
5 . case ‘firefox’: alert(‘You have got the firefox.’); break;
6 . case ‘chrome’: alert(‘You have got the google chrome.’); break;
7 . case ‘safari’: alert(‘You have got the safari.’); break;
8 . default: alert(‘Wrong browser!’);
9 . }
Loops
WHILE, DO...WHILE, FOR
The “while” loop
We often need to repeat actions. Loops are a way to repeat the same code multiple times.
While the condition is truthy, the code from the loop body is executed.
1 . var x = 0;
2 .
3 . while (x < 5) {
4 . console.log(x);
5 . x++;
6 . }
1 . var x = 5;
2 .
3 . while (x) {
4 . alert(x);
5 . x--;
6 . }
The “do...while” loop
The loop will first execute the body, then check the condition, and, while it’s truthy, execute it
again and again.
1 . var x = 0;
2 .
3 . do {
4 . alert(x);
5 . x++;
6 . } while (x < 5);
Function Declaration
To create a function we can use a function declaration.
1 . function functionName(parameters) {
2 . ...body...
3 . }
Our new function can be called by its name: showMessage().
1 . function showMessage() {
2 . alert(‘Hello World!’);
3 . }
4 .
Local variables
A variable declared inside a function is only visible inside that function.
1 . function showMessage() {
2 . var message = ‘Hello’; // local variable
3 . alert(message);
4 . }
5 .
6 . showMessage(); // Hello
7 .
The function has full access to the outer variable. It can modify it as well.
1 . var userName = ‘John Doe’;
2 .
3 . function showMessage() {
4 . userName = ‘Will Smith’; // changed the outer variable
5 .
3 . function showMessage() {
4 . var userName = ‘Will Smith’; // declare a local variable
5 .
Default values
If a parameter is not provided, then its value becomes undefined.
Returning a value
A function can return a value back into the calling code as the result.
1 . function calcSum(x, y) {
2 . return x + y;
3 . }
4 .
7 . alert(result); // 20
Evaluation of default parameters
In JavaScript, a default parameter is evaluated every time the function is called without the
respective parameter.
For example, anotherFunction() is called every time showMessage() is called without the
text parameter.
5 . function anotherFunction() {
6 . return ‘Welcome!’;
7 . }
8 .
1 . function checkAge(age) {
2 . if (age > 18) {
3 . return true;
4 . }
5 . else {
6 . return false;
7 . }
8 . }
9 .
14 . if (result) {
15 . alert(‘Access granted’);
16 . }
17 . else {
18 . alert(‘Access denied!’);
19 . }
Naming a function
Functions are actions. So their name is usually a verb. It should be brief. 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.
Function Declaration:
1 . function sayHi() {
2 . alert(‘Hi’);
3 . }
4 .
5 . sayHi();
Function Expression: “create a function and put it into the variable sayHi".
1 . var sayHi = function() { // create
2 . alert(‘Hi’);
3 . };
4 .
5 . sayHi(); // run
6 .
question
Text of the question
yes
Function to run if the answer is “Yes”
no
Function to run if the answer is “No”
The function should ask the question and, depending on the user’s answer, call yes() or no():
The arguments showOk and showCancel of ask are called ‘callback functions’ or ‘just
callbacks’.
8 . function showOk() {
9 . alert(‘You agreed.’);
10 . }
11 .
12 . function showCancel() {
13 . alert(‘You canceled the execution.’);
14 . }
15 .
Here, functions are declared right inside the ask(...) call. They have no name, and so are
called anonymous.
8 . ask(
9 . ‘Do you agreed?’,
10 . function() { alert(‘You agreed.’); },
11 . function() { alert(‘You canceled the execution.’); }
12 . );
Function Expression vs Function Declaration
Let’s formulate the key differences between Function Declarations and Expressions.
First, the syntax: how to differentiate between them in the code.
1 . // Function Declaration
2 . function calcSum(x, y) {
3 . return x + y;
4 . }
1 . // Function Expression
2 . var calcSum = function(x, y) {
3 . return x + y;
4 . };
A Function Declaration can be called earlier than it is defined. And after all Function
Declarations are processed, the code is executed. So it has access to these functions.
3 . function sayHi(name) {
4 . alert(`Hello, ${name}`);
5 . }
9 . alert(calcSum(5, 10)); // 15
If we have only one argument, then parentheses around parameters can be omitted, making
that even shorter:
1 . /* same as
2 . let double = function(n) {
3 . return n * 2;
4 . };
5 . */
6 .
9 . alert(double(5)); // 10
If there are no arguments, parentheses should be empty (but they should be present):
3 . sayHi();
Arrow functions can be used in the same way as Function Expressions.
9 . result();
OBJECTS
Objects
Objects are used to store keyed collections of various data and more complex entities. In
JavaScript, objects penetrate almost every aspect of the language.
An object can be created with figure brackets {...} with an optional list of properties.
A property is a “key: value” pair, where key is a string (also called a “property name”), and
value can be anything.
Declaration
An empty object (“empty cabinet”) can be created using one of two syntaxes:
Usually, the figure brackets {...} are used. That declaration is called an object literal.
Literals and properties
We can immediately put some properties into {...} as “key: value” pairs:
1 . var user = { // an object
2 . name: “John Doe”, // by key “name” store value “John Doe”
3 . age: 25 // by key “age” store value 30
4 . };
Read properties
Property values are accessible using the ‘dot notation’:
1 . // get property values of the object:
2 . console.log(user.name); // John Doe
3 . console.log(user.age); // 30
4 .
1 . user.isAdmin = true;
Remove properties
To remove a property, we can use delete operator:
1 . delete user.name;
Quoted properties
We can also use multiword property names, but then they must be quoted:
1 . “first name”: “Will”, // The last property in the list may end with
2 . // a comma
Property value shorthand
In real code we often use existing variables as values for property names.
For instance:
1 . var userInfo = { name: “John Doe”, age: 30 };
2 . console.log(“names” in userInfo); // true
Methods
For a start, let’s teach the userInfo to say Hi:
1 . var userInfo = {
2 . name: “John Doe”,
3 . age: 30,
4 . sayHi: function() {
5 . alert(“Hi”);
6 . }
7 . };
8 .
9 . userInfo.sayHi(); // Hi
Method shorthand
There exists a shorter syntax for methods in an object literal:
1 . var userInfo = {
2 . name: “John Doe”,
3 . age: 30,
4 . sayHi() { // same as “sayHi: function()”
5 . alert(“Hi”);
6 . }
7 . };
8 .
9 . userInfo.sayHi(); // Hi
10 . // Expression
11 . var sayHi2 = function() {
12 . alert(“Function expression”);
13 . };
14 .
15 . // Arrow
16 . var sayHi3 = () => alert(“Arrow function”);
17 .
18 . // Add as a method
19 . userInfo.sayHi1 = sayHi1;
20 . userInfo.sayHi2 = sayHi2;
21 . userInfo.sayHi3 = sayHi3;
22 .
1 . var userInfo = {
2 . name: “John Doe”,
3 . age: 30,
4 . getName() {
5 . return this.name;
6 . },
7 . setName(name) {
8 . this.name = name;
9 . }
10 . };
11 .
But quite often we find that we need an ordered collection, where we have a 1st, a 2nd, a
3rd element and so on.
Declaration
There are two syntaxes for creating an empty array:
Array elements are numbered, starting with zero. We can get an element by its number in
square brackets:
1 . console.log(fruits[0]); // Apple
1 . var arr = [
2 . “Apple”,
3 . “Orange”,
4 . { name: “John Doe” },
4 . { age: 30 },
5 . true,
6 . function() {
7 . alert(“Hello World”);
8 . }
9 . ];
10 .
11 . console.log(arr[1]); // Orange
12 .
11 . console.log(arr[3].age); // 30
12 .
There’s another use case for arrays – the data structure named stack.
It supports two operations:
● push adds an element to the end.
● pop takes an element from the end.
For stacks, the latest pushed item is received first, that’s also called LIFO (Last-In-First-Out)
principle. For queues, we have FIFO (First-In-First-Out).
pop
Extracts the last element of the array and returns it:
1 . var fruits = [“Apple”, “Orange”, “Lemon”, “Banana”];
2 .
push
Append the element to the end of the array:
1 . var fruits = [“Apple”, “Orange”, “Lemon”];
2 .
shift
Extracts the first element of the array and returns it:
1 . var fruits = [“Apple”, “Orange”, “Lemon”, “Banana”];
2 .
unshift
Add the element to the beginning of the array:
1 . var fruits = [“Orange”, “Lemon”, “Banana”];
2 .
Multidimensional arrays
Arrays can have items that are also arrays. We can use it for multidimensional arrays:
1 . var matrix = [
2 . [ 1, 2, 3 ];
3 . [ 4, 5, 6 ];
4 . [ 7, 8, 9 ];
5 . ];
6 . alert(matrix[1][1]); // 5
JSON
JSON
The JSON (JavaScript Object Notation) is a general format to represent values and
objects. It is described as in RFC 4627 standard. Initially it was made for JavaScript, but many
other languages have libraries to handle it as well.
JSON for data exchange when the client uses JavaScript and the server is written on
Ruby/PHP/Java/Whatever.
The method JSON.stringify(userInfo) takes the object and converts it into a string.
JSON supports following data types: Some properties are skipped by JSON.stringify:
● Objects {...} ● Function properties (methods).
● Arrays [...] ● Symbolic properties.
● Primitives: ● Properties that store undefined.
● strings,
● numbers,
● boolean values true/false,
● null.
JSON.parse
For instance: