You are on page 1of 96

JAVASCRIPT

What is JavaScript?
JavaScript was initially created to “make web pages alive”.

JavaScript(JS) is a lightweight, interpreted, or just-in-time compiled programming language.


The programs in this language are called scripts. While it is most well-known as the scripting
language.

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”.

● V8 - in Chrome and Opera ● Chakra - in IE


● SpiderMonkey - in Firefox ● Nitro - in Safari
How do engines work?
Engines are complicated. But the basics are easy.
1. The engine (embedded if it’s a browser) reads (“parses”) the script.
2. Then it converts (“compiles”) the script to the machine language.
3. And then the machine code runs, pretty fast.
What can in-browser JavaScript do?
In-browser JavaScript can do everything related to web page manipulation, interaction with the
user, and the web server.

For instance, in-browser JavaScript is able to:


● Add new HTML to the page, change the existing content, modify styles.
● React to user actions, run on mouse clicks, pointer movements, key presses.
● Send requests over the network to remote servers, download and upload files (so-called
AJAX and COMET technologies).
● Get and set cookies, ask questions to the visitor, show messages.
● Remember the data on the client-side (“local storage”).
What makes JavaScript unique?
There are at least three great things about JavaScript:
● Full integration with HTML/CSS.
● Simple things are done simply.
● Support by all major browsers and enabled by default.

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.

IDE Lightweight editors


● IntelliJ IDEA ● Atom
● Eclipse ● Notepad++
● NetBeans ● Visual Studio Code
● Microsoft Visual Code ● Sublime Text
SCRIPT-TAG
The “script” tag
JavaScript programs can be inserted into any part of an HTML document with the help of the
<script> tag. The <script> tag has a few attributes that are rarely used nowadays but can still
be found in old code:

<script type=“text/javascript” language=“JavaScript”></script>

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.

Examples of valid names:


1 . let firstName;
2 . let num123;
3 . let $;
4 . let _;

Examples of incorrect variable names:


1 . let 123num;
2 . let first-name;
Variables
We can declare variables to store data by using the var, let, or const keywords.
1. let – is a modern variable declaration.
2. var – is an old-school variable declaration.
3. const – is like let, but the value of the variable can’t be changed.

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.

Such constants are named using capital letters and underscores.

1 . const COLOR_RED = ‘#F00’;


2 . const COLOR_GREEN = ‘#0F0’;
3 . const COLOR_BLUE = ‘#00F’;
4 . const COLOR_ORANGE = ‘#FF7F00’;
DATA TYPES
Data Types
Programming languages that allow such things are called “dynamically typed”, meaning
that there are data types, but variables are not bound to any of them.

There are seven basic data types in JavaScript.


● Number
● String
● Boolean
● null
● undefined
● Object - (More complex data structure.)
● Symbol - (Create unique identifiers for objects.)
A number
The number type represents both integer and floating point numbers.

1 . var num = 123;


2 . num = 123.45;

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}`;

In JavaScript, there are 3 types of quotes.


1. Double quotes: “Hello”.
2. Single quotes: ‘Hello’.
3. Backticks: `Hello`.
Double and single quotes are “simple” quotes. There’s no difference between them in JavaScript.

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”.

1 . var switchOn = true; // yes, switch on


2 . var switchOff = false; // no, switch off

Boolean values also come as a result of comparisons:

1 . var isGreaterThan = 10 > 5;


2 . alert(isGreaterThan); // true, (the comparison result is ‘yes’)
The “null” value
The special null value does not belong to any of the types described above. It forms a
separate type of its own which contains only the null value:

1 . var age = null;

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.

There are various operators supported by JavaScript:


● Arithmetic Operators
● Assignment Operators
● Comparison Operators
● Logical Operators
● Ternary Operators
● typeof Operators
Terms: “unary”, “binary”, “operand”
An operand – is what operators are applied to. For instance, in the multiplication of 5 * 2
there are two operands: the left operand is 5 and the right operand is 2. Sometimes, people call
these “arguments” instead of “operands”.

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.

But, if the binary + is applied to strings, it merges (concatenates) them:


1 . var str = “my” + “string”;
2 . alert(str); // mystring

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:

+ (Addition): Performs addition on two operands.


1 . var x = 5 + 10; // x = 15

- (Subtraction): Performs subtraction on two operands.


1 . var x = 10 - 5; // x = 5

* (Multiplication): Performs multiplication on two operands.


1 . var x = 5 * 5; // x = 25

/ (Division): Performs division on two operands.


1 . var x = 5 / 5; // x = 1

% (Modulus): Gives remainder of an integer division.


1 . var x = 5 % 4; // x = 1
Increment/Decrement
Increasing or decreasing a number by one is among the most common numerical operations.

Increment ++ increases a variable by 1:


1 . var counter = 5;
2 . counter++; // works the same as counter = counter + 1
3 . alert(counter); // 6

Decrement -- decreases a variable by 1:


1 . var counter = 5;
2 . counter--; // works the same as counter = counter - 1
3 . alert(counter); // 4
Assignment operators
var x = 5, y = 10;

= Assigns right operand value to left operand.


1 . x = y; // x would be 10

+= 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 . var res = (5 > 10) ? “true" : “false";


2 . alert(res); // false
The typeof operator
The typeof operator returns the type of the argument. It’s useful when we want to process
values of different types differently or just want to do a quick check.

It supports two forms of syntax:

1. As an operator: typeof x.
2. As a function: typeof(x).

1 . console.log(typeof 10); // “number”


2 . console.log(typeof true); // “boolean”
3 . console.log(typeof “John Doe”); // “string”
4 . console.log(typeof Math); // “object (1)”
5 . console.log(typeof null); // “object (2)”
6 . console.log(typeof alert); // “function”
TYPE CONVERSIONS
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.

ToString
String conversion happens when we need the string form of a value.

1 . var value = true;


2 . alert(typeof value); // boolean
3 .

4 . value = String(value); // now value is a string “true”


5 . alert(typeof value); // string
ToNumber
Numeric conversion happens in mathematical functions and expressions automatically.
When division / is applied to non-numbers:

1 . alert(“10” / “5”); // 2, strings are converted to numbers

We can use the Number(value) function to explicitly convert a value to a number:

1 . var str = “123”;


2 . alert(typeof str); // string
3 .

4 . var num = Number(str); // becomes a number 123


5 . alert(typeof num); // number
ToBoolean
Boolean conversion is the simplest one.

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:

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 {}.

1 . var year = prompt(‘ENTER YEAR’);


2 .

3 . if(year == 2019) {
4 . alert(‘You are right!’);
5 . }

1 . var accessAllowed;
2 . var age = prompt(“How old are you?”);
3 .

4 . if(age > 18) {


5 . accessAllowed = true;
6 . }
7 . else {
8 . accessAllowed = false;
9 . }
10 .

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.

1 . var fruit = prompt(‘Enter Fruit’, ‘lemon’);


2 .

3 . var message = (fruit == ‘apple’) ? ‘Your favourite fruit is apple’ :


4 . (fruit == ‘orange’) ? ‘Your favourite fruit is orange’ :
5 . (fruit == ‘lemon’) ? ‘Your favourite fruit is lemon’ :
6 . ‘Wrong fruit!’;
7 .

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.

1 . var browser = ‘chrome’;


2 .

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 . }

A shorter way to write while (x != 0) is while (x):

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);

The “for” loop


The loop will first execute the body, then check the condition, and, while it’s truthy, execute it
again and again.
1 . for (var x = 0; x < 5; x++ ) {
2 . console.log(x);
3 . }
Breaking the loop
1 . for (var x = 0; x < 10; x++ ) {
2 . if (x == 5)
3 . break;
4 . console.log(x);
5 . }

Continue to the next iteration


1 . for (var x = 0; x < 10; x++ ) {
2 . if (x%2 == 0)
3 . continue;
4 . console.log(x);
5 . }
FUNCTIONS
Functions
Functions are the main “building blocks” of the program. They allow the code to be called many
times without repetition.

We’ve already seen examples of built-in functions, like alert(value), confirm(question)


and prompt(message, default).

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 .

5 . showMessage(); // Hello World


6 . showMessage(); // Hello World

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 .

8 . alert(message); // Error! The variable is local to the function


Outer variables
A function can access an outer variable as well, for example:
1 . var userName = ‘John Doe’;
2 . function showMessage() {
3 . var message = ‘Hello, ’ + userName;
4 . alert(message);
5 . }
6 . showMessage(); // Hello, John Doe

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 .

6 . var message = ‘Hello, ’ + userName;


7 . alert(message);
8 . }
9 .

10 . alert(userName); // John Doe, before the function call


11 . showMessage();
12 . alert(userName); // Will Smith, value was modified by the function
If a same-named variable is declared inside the function then it shadows the outer one. For
instance, in the code below the function uses the local userName. The outer one is ignored:

1 . var userName = ‘John Doe’;


2 .

3 . function showMessage() {
4 . var userName = ‘Will Smith’; // declare a local variable
5 .

6 . var message = ‘Hello, ’ + userName; // Will Smith


7 . alert(message);
8 . }
9 .

10 . // the function will create and use its own userName


11 . showMessage();
12 .

13 . alert(userName); // John Doe, unchanged, the function did not access


14 . // the outer variable
Parameters
We can pass arbitrary data to functions using parameters(also called function arguments).
The function has two parameters: from and text.

1 . function showMessage(from, text) {


2 . console.log(from + ‘: ’ + text);
3 . }
4 .

5 . showMessage(‘Hello’, ‘World!’); // Hello: World!

Default values
If a parameter is not provided, then its value becomes undefined.

1 . function showMessage(from, text) {


2 . console.log(from + ‘: ’ + text);
3 . }
4 .

5 . showMessage(‘Hello’); // Hello: undefined


If we want to use a “default” text in this case, then we can specify it after =:

1 . function showMessage(from, text = ‘no text given’) {


2 . console.log(from + ‘: ’ + text);
3 . }
4 .

5 . showMessage(‘Hello’); // Hello: no text given

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 .

5 . var result = calcSum(15, 5);


6 .

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.

1 . function showMessage(from, text = anotherFunction()) {


2 . console.log(from + ‘: ’ + text);
3 . }
4 .

5 . function anotherFunction() {
6 . return ‘Welcome!’;
7 . }
8 .

9 . showMessage(‘Hello’); // Hello: Welcome!


10 .

11 . showMessage(‘Hello’, ‘World’);// Hello: World


For example:

1 . function checkAge(age) {
2 . if (age > 18) {
3 . return true;
4 . }
5 . else {
6 . return false;
7 . }
8 . }
9 .

10 . var age = prompt(‘How old are you?’);


11 .

12 . var result = checkAge(age);


13 .

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 starting with...


● “get...” - return a value,
● “calc...” - calculate something,
● “create...” - create something,
● “check...” - check something and return a boolean, etc.,

Examples of such names:


1 . showMessage(...) // show a message
2 . getAge(...) // returns the age
3 . calcSum(...) // calculates a sum and returns the result
4 . createForm(...) // creates a form (and usually returns it)
5 . checkPermission(...)// checks a permission, returns true/false
FUNCTION
Expressions And Arrows
Function expressions and arrows
In JavaScript, a function is not a “magical language structure”, but a special kind of value.

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 .

7 . var sayHi2 = sayHi; // copy


8 .

9 . sayHi2(); // copy run


Callback functions
Let’s look at more examples of passing functions as values and using function expressions.

We’ll write a function ask(question, yes, no) with three parameters:

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’.

1 . function ask(question, yes, no) {


2 . if(confirm(question))
3 . yes();
4 . else
5 . no();
6 . }
7 .

8 . function showOk() {
9 . alert(‘You agreed.’);
10 . }
11 .

12 . function showCancel() {
13 . alert(‘You canceled the execution.’);
14 . }
15 .

16 . ask(‘Do you agreed?’, showOk, showCancel);


Anonymous functions
We can use Function Expressions to write the same function much shorter.

Here, functions are declared right inside the ask(...) call. They have no name, and so are
called anonymous.

1 . function ask(question, yes, no) {


2 . if(confirm(question))
3 . yes();
4 . else
5 . no();
6 . }
7 .

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.

● Function Declaration: a function, declared as a separate statement

1 . // Function Declaration
2 . function calcSum(x, y) {
3 . return x + y;
4 . }

● Function Expression: a function, created inside an expression or inside another syntax


construct. The function is created at the right side of the “assignment expression” =:

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.

1 . sayHi(‘John Doe’); // John Doe


2 .

3 . function sayHi(name) {
4 . alert(`Hello, ${name}`);
5 . }

If it were a Function Expression, then it wouldn’t work.

1 . sayHi(‘John Doe’); // error!


2 .

3 . var sayHi = function(name) { // (*) no magic any more


4 . alert(`Hello, ${name}`);
5 . };
Arrow functions
There’s one more very simple and concise syntax for creating functions, that’s often better than
Function Expressions. It’s called “arrow functions”, because it looks like this:

Let’s see an example:

1 . /* The arrow function is a shorter form of:


2 . var calcSum = function(x, y) {
3 . return x + y;
4 . };
5 . */
6 .

7 . var calcSum = (x, y) => x + y;


8 .

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 .

7 . var double = n => n * 2;


8 .

9 . alert(double(5)); // 10

If there are no arguments, parentheses should be empty (but they should be present):

1 . var sayHi = () => alert(‘Hi’);


2 .

3 . sayHi();
Arrow functions can be used in the same way as Function Expressions.

For instance, here’s the rewritten example with result():

1 . var mark = prompt(‘Enter your mark?’);


2 .

3 . var result = (mark <= 40) ? () => alert(‘Grade D’) :


4 . (mark <= 60) ? () => alert(‘Grade C’) :
5 . (mark <= 80) ? () => alert(‘Grade B’) :
6 . (mark <= 100) ? () => alert(‘Grade A’) :
7 . () => alert(‘Wrong age!’);
8 .

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:

1 . var user = new Object();


2 . var user = {}; // ‘object literal’ syntax

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 . };

We can add, remove and read files from it any time.

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 .

5 . console.log(user[“name”]); // John Doe


6 . console.log(user[“age”]); // 30
Add properties
The value can be of any type. Let’s add a boolean one:

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.

1 . function userInfo(name, age) {


2 . return {
3 . name: name, // name,
4 . age: age // age
5 . };
6 . }
7 .

8 . var user = userInfo(“John Doe”, 30);


9 .

10 . console.log(user.name); // John Doe


Existence check, “in”
The syntax is:
1 . “key” in Object;

For instance:
1 . var userInfo = { name: “John Doe”, age: 30 };
2 . console.log(“names” in userInfo); // true

The “for...in” loop


To walk over all keys of an object, there exists a special form of the loop: for..in.
1 . var userInfo(name, age) {
2 . name: “John Doe”,
2 . age: 30
6 . };
7 .

8 . for (var key in userInfo) {


9 . console.log(key); // name, age
9 . console.log(userInfo[key]); // John Doe, 30
6 . };
Object methods, “this”
Objects are usually created to represent entities of the real world, like users, orders and etc.,
1 . var userInfo = {
2 . name: “John Doe”,
3 . age: 30
4 . };

Actions are represented in JavaScript by functions in properties.

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

We could use a pre-declared, expression, arrow functions as a method, like this:


1 . var userInfo = {
2 . name: “John Doe”,
3 . age: 30
4 . };
6 . // Declaration
7 . function sayHi1() {
8 . alert(“Function declaration”);
9 . }
9 .

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 .

23 . userInfo.sayHi1(); // Function declaration


24 . userInfo.sayHi2(); // Function expression
25 . userInfo.sayHi3(); // Arrow function
“this” in methods
It’s common that an object method needs to access the information stored in the object to do its
job.

To access the object, a method can use the this keyword.

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 .

12 . console.log(userInfo.getName()); // John Doe


13 . userInfo.setName(“Will Smith”);
14 . console.log(userInfo.name); // Will Smith
ARRAYS
Arrays
Objects allow you to store keyed collections of values. That’s fine.

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:

1 . var arr = new Array();


2 . var arr = [];
Almost all the time, the second syntax is used. We can supply initial elements in the brackets:
1 . var fruits = [“Apple”, “Orange”, “Lemon”, “Banana”];

Array elements are numbered, starting with zero. We can get an element by its number in
square brackets:
1 . console.log(fruits[0]); // Apple

We can replace an element:


1 . fruits[1] = “Pineapple”;

Add a new one to the array:


1 . fruits[4] = “Kiwi”;

The total count of the elements in the array is its length:


1 . var fruits = [“Apple”, “Orange”, “Lemon”, “Banana”];
2 . console.log(fruits.length); // 4
An array can store elements of any type.

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 .

13 . arr[5](); // Hello World


Methods pop/push, shift/unshift
A queue is one of the most common uses of an array. In computer science, this means an
ordered collection of elements which supports two operations:
● push appends an element to the end.
● shift get an element from the beginning, advancing the queue, so that the 2nd element
becomes the 1st.

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).

Arrays in JavaScript can work both as a queue and as a stack.


Methods that work with the end of the array:

pop
Extracts the last element of the array and returns it:
1 . var fruits = [“Apple”, “Orange”, “Lemon”, “Banana”];
2 .

3 . fruits.pop(); // remove “Banana”


4 .

5 . console.log(fruits); // “Apple”, “Orange”, “Lemon”

push
Append the element to the end of the array:
1 . var fruits = [“Apple”, “Orange”, “Lemon”];
2 .

3 . fruits.push(“Banana”); // add “Banana” to the end


4 .

5 . console.log(fruits); // “Apple”, “Orange”, “Lemon”, “Banana”


Methods that work with the beginning of the array:

shift
Extracts the first element of the array and returns it:
1 . var fruits = [“Apple”, “Orange”, “Lemon”, “Banana”];
2 .

3 . fruits.shift(); // remove “Apple”


4 .

5 . console.log(fruits); // “Orange”, “Lemon”, “Banana”

unshift
Add the element to the beginning of the array:
1 . var fruits = [“Orange”, “Lemon”, “Banana”];
2 .

3 . fruits.unshift(“Apple”); // add “Apple” to the beginning


4 .

5 . console.log(fruits); // “Apple”, “Orange”, “Lemon”, “Banana”


Loops
One of the oldest ways to cycle array items is the for loop over indexes:

1 . var fruits = [“Apple”, “Orange”, “Lemon”, “Banana”];


2 .

3 . for (var x=0; x<fruits.length; x++) {


4 . console.log(fruits[x]); // “Apple”, “Orange”, “Lemon”, “Banana”
5 . }

But for arrays there is another form of loop, for..of:

1 . var fruits = [“Apple”, “Orange”, “Lemon”, “Banana”];


2 .

3 . for (var fruit of fruits) {


4 . console.log(fruit); // “Apple”, “Orange”, “Lemon”, “Banana”
5 . }
The for..of doesn’t give access to the number of the current element, just its value, but in
most cases that’s enough. And it’s shorter.

Technically, because arrays are objects, it is also possible to use for..in:

1 . var fruits = [“Apple”, “Orange”, “Lemon”, “Banana”];


2 .

3 . for (var fruit in fruits) {


4 . alert(fruits[fruit]);// “Apple”, “Orange”, “Lemon”, “Banana”
5 . }

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.

JavaScript provides methods:


● JSON.stringify to convert objects into JSON.
● JSON.parse to convert JSON back into an object.
JSON.stringify
For instance:
1 . var userInfo = {
2 . name: “John Doe”,
3 . age: 30,
4 . isAdmin: true,
5 . address: {
6 . street: “Hledan Street”,
7 . township: “Hledan”
8 . }
9 . };
10 .

11 . var json = JSON.stringify(userInfo); // convert objects into JSON


12 . document.write(typeof json); // string
13 . document.write(json);

The method JSON.stringify(userInfo) takes the object and converts it into a string.

The resulting json string is called a JSON-encoded or serialized or stringified or


marshalled object. We are ready to send it over the wire or put into a plain data store.
Please note that a JSON-encoded object has several important differences from the object
literal:
● Strings use double quotes. No single quotes or backticks in JSON. So 'John Doe' becomes
"John Doe".
● Object property names are double-quoted also. That’s obligatory. So age:30 becomes
"age":30.

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:

1 . var user = '{“name”: “John Doe”, “age”: 30, “isAdmin”: true}';


3 .

11 . user = JSON.parse(user); // convert JSON into object


3 .

12 . document.write(typeof user); // object


3 .

13 . document.write(user.name); // John Doe

To decode a JSON-string, we need another method named JSON.parse.

You might also like