JavaScript basics

JS

Javascript

Is a high level, dynamic, untyped, and interpreted programming language. It has been standardized in the ECMAScript language specification. Alongside HTML and CSS, it is one of the three essential technologies of World Wide Web 

What is JavaScript

  • JavaScript is a Scripting Language
  • A scripting language is a lightweight programming language.
  • JavaScript is programming code that can be inserted into HTML pages.
  • JavaScript inserted into HTML pages, can be executed by all modern web browsers.  

About

  • Created by Brendan Eich for Netscape Navigator in only ten days!
  • Mocha ⇒ LiveScript ⇒ JavaScript ⇒ ECMAScript
  • Influenced by:
    • C/Java ⇒ Syntax
    • Scheme ⇒ Functional Programming
    • Self ⇒ Prototype inheritance
  • Adopted by Microsoft with the name JS for IE 3.0 ...
    • First browser wars!
  • Standarized by ECMA International.

Why JavaScript?

  • The name suggests that it should be similar to Java, but it is a different beast
  • The language was created too quickly and has errors that many programmers do not care to avoid
  • Still exists the idea that serious programming is done on the server and many programmers do not bother to learn JavaScript seriously
  • It supports multiple paradigms: imperative or functional
  • It is very flexible and expressive
  • ​There have been significant improvements in performance
  • The language is improving with the latest versions
  • ​Whenever there are better books, tools, libraries, etc

JavaScript is a misunderstood language

But in JavaScript there are great ideas too

WHAT CAN I DO WITH JAVASCRIPT?

  • Respond to the users actions (click, hover over etc.)
  • Change HTML&CSS properties of elements on the page
  • Sophisticated animations
  • Dynamically get new data from the server without reloading the entire page (AJAX)

EMBEDDING JAVASCRIPT IN HTML

inner script code

<!DOCTYPE html>
<html>

  <head>
    <title>My first page</title>
  </head>
  
  <body>
    <h1>Example</h1>

    <script language="javascript" type="text/javascript">
        var a = "Hello World!";
        alert(a); 
    </script>
  </body>

</html>

EMBEDDING JAVASCRIPT IN HTML

External script code

index.html

<!DOCTYPE html>
<html>

  <head>
    <title>My first page</title>
  </head>
  
  <body>
    <h1>Example</h1>

    <script language="javascript" type="text/javascript" src="script.js">
    </script>
  </body>

</html>
var a = "Hello World!";
alert(a); 

script.js

EMBEDDING JAVASCRIPT IN HTML

Inline script code

<!DOCTYPE html>
<html>

  <head>
    <title>My first page</title>
  </head>
  
  <body>
    <h1>Example</h1>
    <p onclick="alert('Hello World!')">Say hello</p>
  </body>

</html>

Basics

  • JavaScript is case sensitive
  • Spaces do not matter
  • Statements end with semi-columns (;)
  • No strict data types

Variable Declaration

  • Variables contain values and use the equal sign to specify their value
  • Variables are created by declaration using the var command with or without an initial value state
  • No need to specify a type

Declare variable without initial value:

var a;
var oneMore;
var anotherVar;
var awesomeVariable;

Declare variable with initial value:

var b = 10;
var name = "Leonardo";
var price = 10.4;

Set value to variable

  • To set new value to a variable you are to use the equal sign "="
  • New data overwrites the previous one
  • No strict data type. It means that you can set any value with any type to a variable
//Declaration of a new variable with initial value below
var greeting = "Say hello to the new world of programming!" 

var a;
a = 10; //You can set the value after the variable declaration

var name = "Raphael";
name = "Donatello"; //It will overwrites the content of the "name" variable

var age = 10;
age = "Teenager"; //No type checking

Arithmetics

Operator Description Example
+ Addition var x = 10 + 2;
- Subtraction var x = 5 - 3;
* Multiplication var x  = 2 * 2;
/ Division var x = 20 / 5;
% Modulus var x = 10 % 4;
++ Increment x++;
-- Decrement x--;
var a = 10; 
a++; 
var b = a * 2;
b = b - 1;
b--;
var c = b / 2;
c = c - a;
var x = b & 8;
//a == 10;
//a == 11;
//b == 22; a == 11;
//b == 21;
//b == 20;
//c == 10;
//c == -1;
//x = 4;

Comments

 Commentaries are not for the computer but for the humans. It helps them to understand the code

Block (multiline)

code goes here  /*  comment goes here,  
                    and here
                */ 

Single-line comments

code goes here //comment goes here 
/*
    My first program:
    Hello World!
*/
var a = "Hello World!"; //Declare new variable with initial value
alert(a); //Show message window with the content of the "a" variable

Example

I/O

JavaScript can "display" data in different ways:

  • Writing into an alert box, using window.alert().
  • Writing into the HTML output using document.write().
  • Writing into the browser console, using console.log().

To recive data from user the simpliest way is to use window.prompt()

String

  • JavaScript strings are used for storing and manipulating text
  • A JavaScript string simply stores a series of characters like "John Doe"
  • A string can be any text inside quotes. You can use single or double quotes
  • To escape symbol use backslash \

Typeof

You can use the JavaScript typeof operator to find the type of a JavaScript variable

var a = "John";
typeof a // "string"
// Or
typeof(a) // "string"

Syntax

Boolean

A JavaScript Boolean represents one of two values: true or false.

Very often, in programming, you will need a data type that can only have one of two values, like

  • YES / NO
  • ON / OFF
  • TRUE / FALSE

For this, JavaScript has a Boolean data type. It can only take the values true or false.

Comparison and Logical Operators

Operator Description
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to

BOOLEAN

Conditional statements 

Conditional statements are used to perform different actions based on different conditions.

Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.

  • Use "if" to specify a block of code to be executed, if a specified condition is true
  • Use "else" to specify a block of code to be executed, if the same condition is false
  • Use "else if" to specify a new condition to test, if the first condition is false
  • Use "switch" to specify many alternative blocks of code to be executed

The if Statement

if (condition) {
    block of code to be executed if the condition is true
}

Use the if statement to specify a block of JavaScript code to be executed if a condition is true.

Syntax

Example

var time = 8;

if (time < 10) {
   alert("Good morning");
}

The else Statement

Use the else statement to specify a block of code to be executed if the condition is false.

if (condition) {
    block of code to be executed if the condition is true
} else { 
    block of code to be executed if the condition is false
}

Syntax

Example

var time = 22;

if (time < 10) {
   alert("Good morning");
} else {
   alert("Good evening");
}

else if Statement

Use the else statement to specify a block of code to be executed if the condition is false.

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
}

Syntax

Example

var time = 12;

if (time < 10) {
    alert("Good morning");
} else if (time < 18) {
    alert("Good day");
} else {
    alert("Good evening");
}

Switch Statement

Use the switch statement to select one of many blocks of code to be executed.

switch (expression) {
    case n:
        code block
        break;
    case n:
        code block
        break;
    default:
        some default code block
}

Syntax

Example

var time = 10;

switch (time) {
    case 10:
        console.log("Good morning");
        break;
    case 18:
        console.log("Good day");
        break;
    default:
        console.log("Good evening");
}

CONDITIONAL STATEMENTS

While Loop

while (condition) {
    code block to be executed
}

Syntax

Example

var age = 12;

while(age < 80){
    age = age + 1;
}

Do While Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

do {
    code block to be executed
} while (condition);

Syntax

Example

var age = 12;

do {
  age = age + 1;
} while(age < 80);

For Loop

for (statement 1; statement 2; statement 3) {
    code block to be executed
}

Statement 1 is executed before the loop (the code block) starts.
Statement 2 defines the condition for running the loop (the code block).
Statement 3 is executed each time after the loop (the code block) has been executed.

Syntax

Example

var age = 12;

for (var i = 0; i < 5; i++) {
    age += 2;
}

Loops can execute a block of code a number of times.

Loops

Object

var obj = {
    property: value,
    property: value,
    ...
    property: value
};

Syntax

var person = {
    name: "John",
    lastName: "Doe",
    age: 20
}

Create object with initial values

Create empty object

var obj = {}
var person = {
    name: "John",
    lastName: "Doe",
    age: 20
};

var who = person.name; // or var who = person["name"];
person.age = 30; // Change value
person.hasChildren = true; // Add value

Access object's data

Object

Function

A JavaScript function is a block of code designed to perform a particular task.

A function is executed when "something" invokes it (calls it).

function name(parameter1, parameter2, parameter3, ...) {
    code to be executed
}

Syntax

Function without arguments

function myFync() {
    alert("Inside function");
}

Function with arguments

function myFync(a, b, c) {
    alert(a * b * c);
}

Function with arguments

function myFync(a, b) {
    return a * b;
}

Call function

name(parameter1, parameter2, parameter3, ...)

Function

Array

JavaScript arrays are used to store multiple values in a single variable.

var cars = ["Lada", "Audi", "BMW"];
var anotherCars = new Array("Volvo", "Nissan");

Create array with initial values

var array-name = [item1, item2, ...];   

Syntax

Create empty array

var someArray = [];
var someAnotherArray = new Array();

Array

Access the Elements of an Array

var cars = ["Lada", "Audi", "BMW"];

//You refer to an array element by referring to the index number.
var name = cars[0]; //Lada

Adding Array Elements

var cars = ["Lada", "Audi", "BMW"];
cars.push("Volvo")
//Or
cars[3] = "Volvo";

Changing Array Element

var cars = ["Lada", "Audi", "BMW"];
cars[1] = "Nissan";

Looping Array Element

var cars = ["Lada", "Audi", "BMW"];
for(var i = 0; i < cars.length; i++){
    console.log(cars[i]);
}

Array

Special values

undefined

The undefined property indicates that a variable has not been assigned a value.

var a;
console.log(a); // undefined

null

In JavaScript null is "nothing". It is supposed to be something that doesn't exist.

var a = null;
console.log(a); // null

NaN

var a = "John" * 50;
console.log(a); // NaN

The NaN property represents "Not-a-Number" value. This property indicates that a value is not a legal number.

Infinity

  • Infinity is a numeric value that represents positive infinity.
  • -Infinity is a numeric value that represents negative infinity.
  • Infinity is displayed when a number exceeds the upper limit of the floating point numbers, which is 1.797693134862315E+308.
  • -Infinity is displayed when a number exceeds the lower limit of the floating point numbers, which is -1.797693134862316E+308.

SPECIAL VALUES

Home work

Class work

  • Declare two variables and show them
  • Write a function that can find triangle's area
  • Write a function that reverse the given array using three kind of loops
  • Explain the difference between ++i and i++ with example
  • Write a function that checks if the given arguments is positive number or negative number or is 0
  • Create a page that asks the user his name and alert it back
  • Write a function that calculates factorial

THANKS FOR YOUR ATTENTION

JAVASCRIPT BASICS

Copy of JavaScript Basics

By ilyinalada

Copy of JavaScript Basics

  • 156