JavaScript is ...

 JavaScript is a high-level, dynamic, untyped interpreted programming language that is well-suited to object-oriented and functional programming styles. JavaScript derives its syntax from Java, its first-class functions from Scheme, and its prototype-based inheritance from Self.

History

  • developed in 10 days in May 1995 by Brendan Eich
  •  first shipped in beta releases of Netscape Navigator 2.0 in September 1995
  • In November 1996, Netscape submitted JavaScript to Ecma International for consideration
  • In June 1997, Ecma International published the first edition of the ECMA-262 specification
  • In June 1998 the second edition was released
  • The third edition of ECMA-262 was published on December 1999
  • The fifth edition was released in December 2009
  • The current edition of the ECMAScript standard is 6, released in June 2015

* fourth edition was never released

JS main tasks

JavaScript does:

  • Creating visual effects on the page.

  • Calculation.

  • Working with text, arrays, dates, and regular expressions

  • Input data validation.

  • Dynamically change page content.

  • Interaction with the server without reloading the page(AJAX).

JavaScript does not:

  • Input and Output
  • Networking
  • Storage
  • Graphics

JavaScript can be used for

  • Server Side development (NodeJS)
  • Mobile development (PhoneGap or NativeScript)
  • Robotics and so on ...

Lexical Structure

Case Sensivity

var online = true;

var Online = false;

console.log(online);

Whitespace and Line Breaks

var number     = 12;



number = number +   15;

console.log(number );

Semicolons

var number = 12;

number = number + 15

console.log(number)

Comments

// Declare a number
var number = 12;

/*
 * Add 15 to a number
 */
number = number + 15

console.log(number)

JavaScript Data Types

6 Main Data types

  • 5 primitive types 
  • Object

Use typeof to detect data type

ES6 introduce new type

  • Symbol

Main area of usage - defining object system properties, because:

 

  • Symbols are unique
  • Object properties defined as Symbols are enumerable
  • Possible to interact with Global Symbol Register

Primitive Data Types

  • boolean (true or false)
  • number (0, 1, 2, -24, 45.5, NaN, +/-Infinity)
  • string ('', 'hello', '45')
  • null
  • undefined

Primitive Special Types

Object Data Type

  • Ordinary objects 
  • Arrays
  • Functions

3 kinds of Objects

Boolean

  • simplest primitive value
  • true of false

Numbers

  •  JavaScript does not make a distinction between integer values and floating-point values

  •  All numbers in JavaScript are represented as  floating-point values

  • Use +, -, *, /, % - for base arithmetic operations and Math object for advanced (Math.pow(2, 5) => // 32)
  •  Arithmetic in JavaScript does not raise errors in cases of overflow, underflow, or division by zero.

+/-Infinity, 0, NaN

var a = 258/0;
var d = -258/0;

a; // Infinity
d; // -Infinity

isFinite(a); // false

a === a, a == a, Infinity == Infinity // true
a === d //false

/*  ------------------- */

var b = 0/0;
var c = Math.sqrt(-4);

b; // NaN
c; // NaN

isNaN(b); // true

b === c, b === b, NaN === NaN // false

0.3 - 0.2 !== 0.2 - 0.1 Problem

Strings

  • A string  is an ordered sequence of 16-bit values

  •  The length  of a string is the number of 16-bit values it contains

  •  JavaScript does not have a special type that represents a single element of a string

  • String is not an Array

  • Good practice is single quotes for JS, double for HTML

Null and Undefined

  • null - special value, indicating absence of value

  • typeof null => 'object'

  • undefined - represents the value of variable that was not initialised
var a = null;

var b;
var c = {};

b; // undefined
c.a; // undefined

An ordinary JavaScript object is an unordered collection of named values

var rect = {
    x: 1,
    y: 3,
    width: 5,
    height: 4
}

Array - ordered collection of numbered values

var exampleArray = [1, "hello", {a: 10, b: 15}, null];

exampleArray[1] // "hello"

A function is an object that has executable code associated with it

var sum = function (a, b) {
    return a + b;
}

sum(1, 2) // 3
sum(4, 6) // 10

The most important thing about functions in JavaScript is that they are true values and that JavaScript programs can treat them like regular objects.

Useful JavaScript Objects

Date

Date() constructor is used for creating objects that represent dates and times. These Date objects have methods that provide an API for date maniputation.

new Date();
new Date(value);
new Date(dateString);
new Date(year, month[, day[, hour[, minute[, second[, millisecond]]]]]);

RegExp

RegExp() constructor is used for creating objects that represent textual patterns. Both strings and RegExp objects have methods
for performing pattern matching and search-and-replace operations using regular expressions.

/^HTML/ // Match the letters H T M L at the start of a string
/[1-9][0-9]*/ // Match a non-zero digit, followed by any # of digits
/\bjavascript\b/i // Match "javascript" as a word, case-insensitive

The Global Object

The global object is a regular JavaScript object with globally defined properties and methods that are available to a JavaScript program.

  • global properties like undefined, Infinity, and NaN
  • global functions like isNaN(), parseInt() and eval()
  • constructor functions like Date(), RegExp(), String(), Object(), and Array()
  • global objects like Math and JSON

Window

Global Object contains:

Mutable vs Immutable

Primitives

(number, string, booleans, undefined, null)

Are Immutable

var s = "hello"; // Start with some lowercase text
s.toUpperCase(); // Returns "HELLO", but doesn't alter s
s // => "hello": the original string has not changed

Objects

(regular objects or arrays)

Are Mutable

var o = { x:1 }; // Start with an object
o.x = 2; // Mutate it by changing the value of a property
o.y = 3; // Mutate it again by adding a new property

Primitives

Are compared by value

Objects

Are compared by reference

Conversions and Equality

null == undefined // These two values are treated as equal.
"0" == 0          // String converts to a number before comparing.
0 == false        // Boolean converts to number before comparing.
"0" == false      // Both operands convert to numbers before comparing.

== vs === ?

JavaScript Variables

Variable Definition

var

let

const

function func() {
    var a = 15;

    console.log(a); // 15 

    a = 35;

    console.log(a); // 35
}
function func() {
    let a = 15;

    console.log(a); // 15 

    a = 35;

    console.log(a); // 35
}
function func() {
  const a = 15;
  const b = { x: 10 };

  console.log(a); // 15 
  console.log(b); 
    // { x: 10 } 

  a = 35; 
    // TypeError: `a` is read-only 
  b = {z: 15};
    // TypeError: `b` is read-only

  b.y = 35;

  console.log(b); 
    // { x: 10, y: 35 }
}

Declaration

var a, b;


var a;
var b;


var a,
    b;


var a = 10,
    b = 'hello';


a = 10;
b = 15;

var, let, const

(Re)Declaration

var

let, const

// 1 
var a = 15;
var b = a + 25;
var b = 'hello';

console.log(b);

// 2
function func(arg) {
    var arg = 40;
    console.log(arg);
}
// 1 
let a = 15;
let b = a + 25;
let b = 'hello';

console.log(b);

// 2
function func(arg) {
    let arg = 40;
    console.log(arg);
}
// 1 - 25

// 2 - 40
// Identifier 'b' has 
// already been declared

Variable Scope

Scope - the region of your program source code in which a variable is defined.

global variable - has global scope; it is defined everywhere in your JavaScript code

 local variables - declared and are defined only within the body of the function and within any functions nested within that function.

Local Variable Scope

function scope - variables are visible within the function in which they are defined and
within any functions that are nested within that function.

block scope - variables are visible within the block of code wrapped with curly braces. ES6 ONLY

function tetsBlockScope() {
    if (true) {
        var b = 'hello';
        var C = 'WORLD';
    }

    console.log(b);
    console.log(C);
}

tetsBlockScope();
// 'hello'
// 'World'
function tetsBlockScope() {
    if (true) {
        let b = 'hello';
        const C = 'WORLD';
    }

    console.log(b);
    console.log(C);
}

tetsBlockScope();
// ReferenceError b is not defined
// ReferenceError C is not defined

Scope Chain

var x = 15;

function  testScopeChain() {

    function  parent() {

        function  child() {
           console.log(x);  
        }

       child();  
    }

    parent();  
}

testScopeChain();

/*
 *  child--
 *         |
 *          -->parent--
 *                     |
 *                      -->testScopeChain --
 *                                          |
 *                                           --> window
 */

Variable Scope Riddle

var scope = "global";

function checkscope() {
    return scope; 
}

checkscope();

// 'global'
var scope = "global";

function checkscope() {
    var scope = "local"; 
    return scope; 
}

checkscope();

// 'local'

Hoisting

function testFunctionScope () {
    console.log(b); // 1

    if (true) {
        console.log(b); // 2
        var b = 'hello';
        console.log(b); // 3
    }

    console.log(b); // 4
}


testFunctionScope();
function testFunctionScope () {
    var b;

    console.log(b);

    if (true) {
        console.log(b);
        b = 'hello';
        console.log(b);
    }

    console.log(b);
}


testFunctionScope();

vs

You write

JavaScript interpret

// 1 - undefined
// 2 - undefined
// 3 - 'hello'
// 4 - 'hello'

! var

Hoisting

function testFunctionScope () {
    console.log(b); // 1

    if (true) {
        console.log(b); // 2
        let b = 'hello';
        console.log(b); // 3
    }

    console.log(b); // 4
}


testFunctionScope();
function testFunctionScope () {
    console.log(b);

    if (true) {
        console.log(b);
        let b = 'hello';
        console.log(b);
    }

    console.log(b);
}


testFunctionScope();

vs

You write

JavaScript interpret

// 1 - ReferenceError: b is not defined
// 2 - ReferenceError: b is not defined
// 3 - 'hello'
// 4 - ReferenceError: b is not defined

let, const

Hoisting

mylocation = "Kyiv"; // global variable

function outputPosition() {
    console.log(mylocation); 
    var mylocation = 'New York';  
    console.log(mylocation); 
}

outputPosition(); 
// undefined
// New-York

Scoping Hoisting Riddle

function test() {
    var i = 0; 
    if (true) {
        let j = 0; 
        for(var k=0; k < 10; k++) { 
            console.log(k); 
        }
        console.log(k);
        console.log(j);
    }
    console.log(j);
}

// 0
// 1
// 2
// 3
// 4
// 5
// 6
// 7
// 8
// 9

// 10

//0

// ReferenceError

Function

  • are function-scoped, like var.

  • create properties in the global object (while in global scope), like var.

  • are hoisted: independently of where a function declaration is mentioned in its scope, it is always created at the beginning of the scope.

Class

Class declarations…

  • are block-scoped.

  • don’t create properties on the global object.

  • are not hoisted.

Declarations

Garbage collection

Garbage collection

In more high-level programming languages, like JavaScript, garbage-collector is standalone piece of software, shipped with browser, that detects "an object is unreachable" and removes them to free memory.

 

As a result, developer don`t need to manually track unused variables and remove them.

Garbage collection

But still developer needs to avid situation, that won`t allow GC to remove unused variable

  • don`t create objects that are "reachable" but not used
  • don`t create circular references
  • remove unneeded event handlers
  • remove event handlers for DOM elements you plan to remove

Strict Mode

  • was introduced in ES5
  • makes JS Engine react to some exceptions that previously were ignored
  • allows better code optimization
  • helps early error detection
  • makes JavaScript more safe
  • can be activated for 'all script file' or 'function'
  • Enabled by default in ES6

Modules

JS Modules

Common JS

Asynchronous Module Definition (AMD)​

  • Standard in Node.js
  • Compact syntax
  • Synchronous loading
  • Designed for browser
  • More complicated syntax
  • Asynchronous loading
//------ lib.js ------
var sqrt = Math.sqrt;
function square(x) {
    return x * x;
}
function diag(x, y) {
    return sqrt(square(x) + square(y));
}
module.exports = {
    sqrt: sqrt,
    square: square,
    diag: diag,
};

//------ main.js ------
var square = require('lib').square;
var diag = require('lib').diag;
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5
//------ lib.js ------
define('lib', [], 
    function () {
        var lib = {
            sqrt: Math.sqrt,
            square(x) {
                return x * x;
            },
            diag(x, y) {
                return sqrt(square(x) + square(y));
            }
        }

        return lib;
});

//------ main.js ------
define('main', 
    ['lib'], 
    function ( lib ) {
        var square = lib.square;
        var diag = lib.diag;
        console.log(square(11)); // 121
        console.log(diag(4, 3)); // 5
    }
);

ES6 Modules

Why?

ES6 Modules

  • Are static.
  • Imports are hoisted (raised to the top of file)
  • Imports are read-only views on exports
//------ lib.js ------
export var sqrt = Math.sqrt;

export function square(x) {
    return x * x;
}

function diag(x, y) {
    return sqrt(square(x) + square(y));
}

export default lib {
    sqrt: sqrt,
    square: square,
    diag: diag,
};

//------ main.js ------
import { sqrt, square } from './lib'; // named import

import lib from './lib'; // default import 


console.log(square(11)); // 121
console.log(lib.diag(4, 3)); // 5

How to run JavaScript in browser

Using of <script> tag

<head>
    <script type="application/javascript" src="main.js"/>
</head>

Using of ES6 modules

<head>
    <script type="module" src="main.js"/>
</head>
HTML element <script> <script type="module">
Default mode non-strict strict
Top-level variables are global local to module
Value of this at top level window undefined
Executed synchronously asynchronously
Declarative imports (import statement) no yes
Programmatic imports (Promise-based API) yes yes
File extension .js .js

Script

Module

Difference

Self Study

Practical Task

Numbers

  • проверка на бесконеченость
  • проверка на NaN
  • проверка на NaN, без использования метода пункта 2
  • преобразование в Integer
  • форматирование значения до N знаков после зяпятой
  • преобразование в строку
  • округление до ближайшего целого
  • возведение в степень
  • нахождение максимального/минимального числа

Strings

  • получение первого/последнего символа
  • получение части строки между символами
  • создание массива из строки по разделителю
  • перевод строки в верхний регистр
  • замена части строки на другую
  • убрать пробелы в начале и конце строки

Arrays

  • получение количества элементов в массиве
  • удаление 3го элемента массива
  • добавление 1го элемента в конец/начало массива
  • удаление первого/последнего элемента массива
  • преобразования массива в строку
  • реверсия массива
  • сортировка массива
  • обьединение двух массивов в один
  • возвращение части массива(с ... по ... индекс)
  • увеличение каждого элемента массива на 3(для числовых массивов)
  • проверка что все элементы массива больше 23
  • проверка что хотя бы один элемент массива больше 12
  • просумировать все элементы массива

Dates

  • получение текущей даты(обьект)
  • получение текущей даты в милисекундах
  • узнать сколько времени прошло с 10 января 2015 года
  • получения названия дня недели для заданой даты

RegExp

  • проверка наличия суб-строки в строке
  • получения номера символа вхождения суб-строки в строку
  • замена суб-строки на другую в строке

Basics JS

By Viktor Shevchenko

Basics JS

  • 1,997