JS Introduction
Telerik Academy Alpha

 

Front-End

 Table of contents

  • What is JavaScript?

  • JavaScript Tools

  • Data Types

  • Functions

  • Objects

  • Array

What is JavaScript?

 JavaScript

  • JavaScript is a front-end scripting language developed by Netscape for dynamic content

    • Lightweight, but with limited capabilities
      Can be used as object-oriented language

    • Embedded in your HTML page

    • Interpreted by the Web browser

  • Client-side, mobile and desktop technology

  • Simple and flexible

  • Powerful to manipulate the DOM

 JavaScript

  • JavaScript allows interactivity such as:

  • Implementing form validation

  • React to user actions, e.g. handle keys

  • Changing an image on moving mouse over it

  • Sections of a page appearing and disappearing

  • Content loading and changing dynamically

  • Performing complex calculations

  • Custom HTML controls, e.g. scrollable table

  • Implementing AJAX functionality

 JavaScript superpowers

  • JavaScript can:

    • handle events

    • read and write HTML elements and modify the DOM tree

    • validate form data

    • access / modify browser cookies

    • detect the user's browser and OS

    • be used as object-oriented language

    • handle exceptions

    • perform asynchronous server calls (AJAX)

 Using JavaScript

  • The JavaScript code can be placed in:

    • <script> tag in the head

    • <script> tag in the body - not recommended

    • External files, linked via <script> tag the head

      • Files usually have .js extension

      • Highly recommended

      • The .js files get cached by the browser

<scriрt type="text/javascript">
    console.log('Hello World!');
</scriрt>

 When is Executed?

  • JavaScript code is executed during the page loading or when the browser fires an event

    • All statements are executed at page loading

    • Some statements just define functions that can be called later

    • No compile time checks

  • Function calls or code can be attached as "event handlers" via tag attributes

    • Executed when the event is fired by the browser

<img src="logo.gif" onclick="alert('clicked!')" />

 External script files

  • Using external script files

<html>
<head>
  <scriрt src="sample.js" type="text/javascript">
  </scriрt>
</head>
<body>
  <button onclick="hello()" value="Call JavaScript
    function from sample.js"></button>
</body>
</html>
  • Contents of the external file sample.js

function hello() {
  alert('Hello from sample.js!')
}

 JavaScript Syntax

  • The JavaScript syntax is kind of similar to C#

    • Operators (+, *, =, !=, &&, ++, …)

    • Variables (weakly typed)

    • Conditional statements (if, else)

    • Loops (for, while)

    • Arrays (my_array[]) and associative arrays (my_array['abc'])

    • Functions (can return value)

JavaScript Tools

 JavaScript Tools

  • JavaScript is an interpreted language

    • It can be ran on the browser or locally

    • The means to acquire the JavaScript code are trivial

      • No matter how or where it is coded

      • You can even code it in Notepad

  • Yet, there are many tools that make JavaScript coding eaiser

    • Like editors, debuggers, etc…

 Node.js

  • Node.js is a server-side platform that uses JavaScript

    • Runs the V8 JS interpreter

    • Allows creating end-to-end apps with JavaScript

    • Usable to test & learn JavaScript Syntax

  • Visit the Node.js website: https://nodejs.org/

    • Install via the Installer or NVM

    • Node.js once installed on the machine and can be used through the CMD/Terminal

      • In the CMD/Terminal run node -v

 Development Environment

  • All a developer needs for writing JavaScript is a text editor - could be even Notepad/Notepad++, yet, there are lots of options:

    • Text editors with plugins

      • VS Code

      • Sublime

      • Atom

    • IDEs

      • Visual Studio with Web Essentials plugin

      • Jetbrains Webstorm

 Debugging JavaScript

  • There is no universal way of debugging client-side JavaScript

    • The only reliable way to debug client-side JavaScript is through the browser

  • Fortunately all browsers have their own debugging tool/plugin that makes it easier

    • Firefox has Firebug

    • Chrome and Opera have Web developer tools

    • Internet Explorer and Edge have F12

 Utilities

Data Types

 Local and Global Variables

  • Local variables - declared with the keywords var, let or const

    • var - the variable lives in the scope of the current function or in the global scope

    • let - the variables lives in the current scope

    • const - like let, but cannot be reassigned

  • Global variables

    • Declared without any keyword

    • Bad practice - never do this!

 JavaScript Data Types

  • JavaScript is weakly typed language

    • allows most operations on values without regards to type

    • values have types, variables don't

    • variables can hold any type of value

var count = 5; // variable holds an integer value
count = 'hello'; // the same variable now holds a string

var name = 'Telerik Academy'; // variable holds a string

let mark = 5.25 // mark holds a floating-point number
mark = true; // mark now holds a boolean value

const MAX_COUNT = 250; // name is a constant variable that holds a string
MAX_COUNT = 0; // error, cannot assign to a constant variable

 JavaScript Data Types

  • JavaScript is a weakly typed language

    • Variables don’t have type, but their values do

  • JavaScript has seven different types:

    • Number, String, Boolean, Symbol, Null, Undefined and Object (yes, Arrays are of type Object)

  • Object is the only reference type

    • It is passed by reference (every time an object's value is used, it's used through a reference)

  • Number, String, Boolean, Symbol, Null, Undefined are primitive types, passed by value (they're copied each time their value is used)

 Loose and strict equality

  • Seemingly different values equate to true when compared with == (loose or abstract equality)

    • JavaScript (effectively) converts each to a string representation before comparison:

// all true
1 == '1';
1 == [1];
'1' == [1];
  • A more obvious false result occurs when comparing with === (strict equality) because the type is also considered:

// all false
1 === '1';
1 === [1];
'1' === [1];

 Truthy and Falsy Values

  • The following values are always falsy (false-like):

    • false, 0, '' or "" (empty string)

    • null, undefined, NaN (e.g. the result of 1/0)

  • Everything else is truthy. That includes:

    • '0' (a string containing a single zero)

    • 'false' (a string containing the text “false”)

    • [] (an empty array)

    • {} (an empty object)

    • function(){} (an “empty” function)

 Undefined and Null Values

  • JavaScript has a special value undefined

    • It means the variable has not been defined (no such variable in the current context)

  • undefined is different than null

    • null represents an empty value

let x;
console.log(x); // undefined

x = 5;
console.log(x); // 5

x = undefined;
console.log(x); // undefined

x = null;
console.log(x); // null

Functions

 Declaring and Creating functions

  • Each function has a name

    • It is used to call the function

    • Describes its purpose

  • Functions in JavaScript do not explicitly define return type

    • Each function always returns a value

function print(dataToPrint) {
    console.log(dataToPrint);
}

 Ways of defining a function

  • Functions can be defined in several ways:

// By function declaration

function print(data) { console.log(data) };

// By function expression 

var print = function (data) { console.log(data) };

// By using arrow functions

var print = (data) => console.log(data); 

 Defining a function with parameters

  • Functions can have as many parameters as needed:

function printMax(x, y) {
  var max;
  x = +x; y = +y;
  max = x;

  if (y > max) {
    max = y;
  }

  console.log(`Maximal number: ${max}`);
}

 The arguments object

  • Every function in JavaScript has an implicit parameter arguments

    • It holds information about the function and all the parameters passed to the function

    • No need to be explicitly declared

      • It exists in every function

function printArguments() {
  for(let i in arguments) {
    console.log(arguments[i]);
  }
}

printArguments(1, 2, 3, 4); // will print 1, 2, 3, 4

 Returning values

  • Every function in JavaScript returns a value

    • Returns undefined implicitly

    • Can be set explicitly

      • The return value can be of any type

      • Number, String, Object, Function..

    • Use return keyword to return a result

       

function multiply (firstNum, secondNum) {
    return firstNum * secondNum;
}

Objects

 Objects Overview

  • JavaScript is designed on a simple object-based paradigm

    • An object is a collection of properties

  • An object property is association between a name and a value

    • A value of property can be either a method (function) or a field (variable)

  • Lots of predefined objects available in JS

    • Math, document, window, etc…

  • Objects can be created by the developer

 Object Properties

  • Each object has properties

    • Properties are values attached to the object

    • Properties of an object can be accessed with a dot-notation (. operator) or with [] - indexer:

let arrStr = arr.join(', '); // property join of Array
let length = arr.length;  // property length of Array
let words = text.split(' ');
let words = text['split'](' ');

 Object Literal

  • JavaScript object literal is a simplified way to create objects

    • Using curly brackets:

let person = {
  firstName: 'Viktor',
  lastName: 'Tsvetkov',
  toString: function () {
    return this.firstName + ' ' + this.lastName;
  }
};

// object properties can be used:
console.log(person.toString());
// writes 'Viktor Tsvetkov'

 Object Literal - Example

  • Lets make two people:

let minkov = {
  fname: 'Doncho',
  lname: 'Minkov',
  toString: function() {
    return this.fname + ' ' + this.lname;
  }
};
let georgiev = {
  fname: 'Georgi',
  lname: 'Georgiev',
  toString: function() {
    return this.fname + ' ' + this.lname;
  }
};
  • Object notations are great, but repeating code is not, right?

 Object Building Function

  • Using a function for building objects

    • Just pass first and last name and get a object

      • Something like a constructor

function makePerson(fname, lname) {
  return {
    fname: fname,
    lname: lname,
    toString: function () {
      return this.fname + ' ' + this.lname;
    }
  }
}

let minkov = makePerson('Doncho', 'Minkov');
let georgiev = makePerson('Georgi', 'Georgiev');

 Object Building - The cool new way

  • Using ES6, we can create objects from a class:

class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  toString() {
    return this.firstName + ' ' + this.lastName;
  }
}

let minkov = new Person('Doncho', 'Minkov');
let georgiev = new Person('Georgi', 'Georgiev');

Arrays

 What are Arrays?

  • An array is a sequence of elements

    • The order of the elements is fixed

    • Does not have fixed size

// Array holding numbers
let numbers = [1, 2, 3, 4, 5];

// Array of different types
let mixedArr = [1, new Date(), 'hello'];

// Array of arrays (matrix)
let matrix = [
  ['0,0', '0,1', '0,2'],
  ['1,0', '1,1', '1,2'],
  ['2,0', '2,1', '2,2']
];

 Inserting and Removing Elements 

  • All arrays in JavaScript are dynamic

    • Their size can be changed at runtime

    • New elements can be inserted to the array

    • Elements can be removed from the array

 Inserting and Removing Elements

  • [].push(element)

    • Inserts a new element at the tail of the array

  • [].pop()

    • Removes the element at the tail

    • Returns the removed element

  • [].unshift(element)

    • Inserts a new element at the head of the array

  • [].shift()

    • Removes the element at the head

    • Returns the remove element

 Other methods

  • [].reverse()

    • Reverses the elements of the array

    • Returns a new arrays

var items = [1, 2, 3, 4, 5, 6];
var reversed = items.reverse();
//reversed = [6, 5, 4, 3, 2, 1]
  • [].join(separator)

    • Concatenates the elements with a separator

    • Returns a string

var names = ["John", "Jane", "George", "Helen"];
var namesString = names.join(", ");
//namesString = "John, Jane, George, Helen"

 Concatenating Arrays

  • arr1.concat(arr2)

    • Inserts the elements of arr2 at the end of arr1

    • Returns a new array

    • arr1 and arr2 remain unchanged!

var arr1 = [1, 2, 3];
var arr2 = ["one", "two", "three"];
var result = arr1.concat(arr2);
//result = [1, 2, 3, "one", "two", "three"]
  • Adding the elements of an array to other array

var arr1 = [1, 2, 3];
var arr2 = ["one", "two", "three"];
[].push.apply(arr1, arr2);
//arr1 = [1, 2, 3, "one", "two", "three"]

 Slicing Arrays

  • [].slice(fromIndex [, toIndex])

    • Returns a new array

      • A shallow copy of a portion of the array

    • The new array contains the elements from indices fromIndex to to (excluding toIndex)

    • Can be used to clone an array

var items = [1, 2, 3, 4, 5];
var part = items.slice(1, 3);
//part = [2, 3]
var clonedItems = items.slice();

 Splicing Arrays

  • [].splice(index, count, elements)

    • Removes count elements, starting from index position

    • Adds elements at position index

    • Returns a new array, containing the removed elements

var numbers = [1, 2, 3, 4, 5, 6, 7];
var result = numbers.splice(3, 2, "four", "five", "five.five");
//result = [4, 5]
//numbers = [1, 2, 3, "four", "five", "five.five", 6, 7];

 Searching in Arrays

  • [].indexOf(element [, rightOf])

    • Returns the index of the first match in the array

    • Returns -1 is the element is not found

  • [].lastIndexOf(element, [leftOf])

    • Returns the index of the first match in the array

    • Returns -1 is the element is not found

  • [].indexOf() and [].lastIndexOf() do not work in all browsers

    • Need to be shimmed

Questions?

[FE] JS Introduction

By telerikacademy

[FE] JS Introduction

  • 1,287