Introduction to Javascript

Useful Pointers

We will cover the following:

What is JavaScripts?


My First Program


<!DOCTYPE HTML>
<html>

<body>

  <p>Before the script...</p>

  <script type="text/javascript">
    alert( 'Welcome to the JavaScript Tutorial!' );
  </script>

  <p>...After the script.</p>

</body>

</html>
<script src="/path/to/script.js"></script>

<script src="/js/script1.js"></script>
<script src="/js/script2.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.2.0/lodash.js"></script>

Code Structure


Statements

alert('Hello Class.'); alert('Welcome!');

Semicolons

alert('Hello Class.')
alert('Welcome!')

alert(3 +
1
+ 2);

Comments

// This comment occupies a line of its own
alert('Hello Class.');

alert('Welcome!'); // This comment follows the statement

/* An example with two messages.
This is a multiline comment.
*/
alert('Hello Class.');
alert('Welcome!');

“use strict”

"use strict";

// this code works the modern way
...

Variables


let message;
message = 'Hello!';

alert(message); // shows the variable content
let user = 'John', age = 25, message = 'Hello';

let user = 'John';
let age = 25;
let message = 'Hello';

let user = 'John',
  age = 25,
  message = 'Hello';
  
let user = 'John'
  , age = 25
  , message = 'Hello';
const firstAppoloLaunch = '16.07.1969';

const COLOR_RED = "#F00";
const COLOR_GREEN = "#0F0";
const COLOR_BLUE = "#00F";
const COLOR_ORANGE = "#FF7F00";

// ...when we need to pick a color
let color = COLOR_ORANGE;
alert(color); // #FF7F00

Exercise

  1. Declare two variables: old_topic and new_topic.
  2. Assign the value “JavaScript” to new_topic.
  3. Copy the value from new_topic to old_topic.
  4. Show the value of old_topic using alert.

Data Types


Numbers

let n = 123;
n = 12.345;

alert( 1 / 0 ); // Infinity
alert( Infinity ); // Infinity

alert( "not a number" / 2 ); // NaN, such division is erroneous
alert( "not a number" / 2 + 5 ); // NaN
// No effect on numbers
let x = 1;
alert( +x ); // 1

let y = -2;
alert( +y ); // -2

// Converts non-numbers
alert( +true ); // 1
alert( +"" );   // 0
alert( 5 % 2 ); // 1 is a remainder of 5 divided by 2
alert( 8 % 3 ); // 2 is a remainder of 8 divided by 3
alert( 6 % 3 ); // 0 is a remainder of 6 divided by 3
alert( 2 ** 2 ); // 4  (2 * 2)
alert( 2 ** 3 ); // 8  (2 * 2 * 2)
alert( 2 ** 4 ); // 16 (2 * 2 * 2 * 2)
let counter = 2;
counter++;      // works the same as counter = counter + 1, but is shorter
alert( counter ); // 3

counter--;      // works the same as counter = counter - 1, but is shorter
alert( counter ); // 2
let n = 2;
n += 5; // now n = 7 (same as n = n + 5)
n *= 2; // now n = 14 (same as n = n * 2)
alert( n ); // 14
let a = (1 + 2, 3 + 4);
alert( a ); // 7 (the result of 3 + 4)

Strings

let str = "Hello";
let str2 = 'Single quotes are ok too';
let phrase = `can embed ${str}`;
let name = "Jules";

// embed a variable
alert( `Hello, ${name}!` ); // Hello, Jules!

// embed an expression
alert( `the result is ${1 + 2}` ); // the result is 3
let s = "my" + "string";
alert(s); // mystring

alert( '1' + 2 ); // "12"
alert( 2 + '1' ); // "21"

alert(2 + 2 + '1' ); // "41" and not "221"
alert( 'Z' > 'A' ); // true
alert( 'Glow' > 'Glee' ); // true
alert( 'Bee' > 'Be' ); // true

Booleans

let nameFieldChecked = true; // yes, name field is checked
let ageFieldChecked = false; // no, age field is not checked
let isGreater = 4 > 1;
alert( isGreater ); // true (the comparison result is "yes")
alert( 2 > 1 );  // true (correct)
alert( 2 == 1 ); // false (wrong)
alert( 2 != 1 ); // true (correct)

The “null” Value

let age = null;

The “undefined” Value

let x;

alert(x); // shows "undefined"
let x = 123;

x = undefined;

alert(x); // "undefined"

The typeof operator

typeof undefined // "undefined"
typeof 0 // "number"
typeof true // "boolean"
typeof "foo" // "string"
typeof null // "object" 
typeof alert // "function"

Exercise

What is the output of?

let name = "Ilya";
alert( `hello ${1}` ); // ?
alert( `hello ${"name"}` ); // ?
alert( `hello ${name}` ); // ?

Type Conversion

let value = true;
alert(typeof value); // boolean

value = String(value); // now value is a string "true"
alert(typeof value); // string
alert( "6" / "2" ); // 3, strings are converted to numbers

alert( Number("   123   ") ); // 123
alert( Number("123z") );      // NaN (error reading a number at "z")
alert( Number(true) );        // 1
alert( Number(false) );       // 0
alert( Boolean(1) ); // true
alert( Boolean(0) ); // false

alert( Boolean("hello") ); // true
alert( Boolean("") ); // false

Interaction


alert

prompt

let age = prompt('How old are you?', 100);
alert(`You are ${age} years old!`); // You are 100 years old!

confirm

let isBoss = confirm("Are you the boss?");
alert( isBoss ); // true if OK is pressed

Conditional Statements


if (0) { // 0 is falsy
  ...
}

if (1) { // 1 is truthy
  ...
}
let year = prompt('In which year was the ECMAScript-2015 specification published?', '');

if (year < 2015) {
  alert( 'Too early...' );
} else if (year > 2015) {
  alert( 'Too late' );
} else {
  alert( 'Exactly!' );
}

Conditional operator ‘?’

let result = condition ? value1 : value2;

The condition is evaluated:

let accessAllowed = (age > 18) ? true : false;
let age = prompt('age?', 18);
let message = (age < 3) ? 'Hi, baby!' :
  (age < 18) ? 'Hello!' :
  (age < 100) ? 'Greetings!' :
  'What an unusual age!';

alert( message );

The “switch” Statement

switch(x) {
  case 'value1':  // if (x === 'value1')
    ...
    [break]

  case 'value2':  // if (x === 'value2')
    ...
    [break]

  default:
    ...
    [break]
}
let a = 2 + 2;

switch (a) {
  case 3:
    alert( 'Too small' );
    break;
  case 4:
    alert( 'Exactly!' );
    break;
  case 5:
    alert( 'Too large' );
    break;
  default:
    alert( "I don't know such values" );
}

If there is no break then the execution continues with the next case without any checks.

let a = 2 + 2;

switch (a) {
  case 3:
    alert( 'Too small' );
  case 4:
    alert( 'Exactly!' );
  case 5:
    alert( 'Too big' );
  default:
    alert( "I don't know such values" );
}
// In the example above we’ll see sequential execution of three alerts
alert( 'Exactly!' );
alert( 'Too big' );
alert( "I don't know such values" );

Loops


The “while” Loop

// Syntax
while (condition) {
  // code
  // so-called "loop body"
}
// An example
let i = 0;
while (i < 3) { // shows 0, then 1, then 2
  alert( i );
  i++;
}
// Another example
let i = 3;
while (i) { // when i becomes 0, the condition becomes falsy, and the loop stops
  alert( i );
  i--;
}

The “do…while” Loop

// Syntax
do {
  // loop body
} while (condition);

The loop will first execute the body, then check the condition, and, while it’s truthy, execute it again and again.

// An example
let i = 0;
do {
  alert( i );
  i++;
} while (i < 3);

The “for” Loop

// Syntax
for (begin; condition; step) {
  // ... loop body ...
}
// An example
for (let i = 0; i < 3; i++) { // shows 0, then 1, then 2
  alert(i);
}
// Another example
var myArray = ["A", "B", "C"];
for (var i = 0; i < myArray.length; i++)
{
    console.log("The member of myArray in index " + i + " is " + myArray[i]);
}

Breaking the Loop

let sum = 0;

while (true) {
  let value = +prompt("Enter a number", '');
  if (!value) break; // (*)
  sum += value;
}
alert( 'Sum: ' + sum );

Continue to the Next Iteration

// An example
for (let i = 0; i < 10; i++) {
  // if true, skip the remaining part of the body
  if (i % 2 == 0) continue;

  alert(i); // 1, then 3, 5, 7, 9
}

Labels for break/continue

// An example
outer: for (let i = 0; i < 3; i++) {

  for (let j = 0; j < 3; j++) {

    let input = prompt(`Value at coords (${i},${j})`, '');

    // if an empty string or canceled, then break out of both loops
    if (!input) break outer; // (*)

    // do something with the value...
  }
}
alert('Done!');

Exercise

What is the last value alerted by this code? Why

let i = 3;

while (i) {
  alert( i-- );
}

Function Expressions and Arrows


// Simple function

function sayHi() {
  alert( "Hello" );
} 
// Function expression
// The function is created and assigned to the variable.
// No matter how the function is defined, it’s just a value 
// stored in the variable sayHi.

let sayHi = function() {
  alert( "Hello" );
};
function sayHi() {
  alert( "Hello" );
}

alert( sayHi ); // shows the function code

We can copy a function to another variable:

function sayHi() {   // (1) create
  alert( "Hello" );
}

let func = sayHi;    // (2) copy

func(); // Hello     // (3) run the copy (it works)!
sayHi(); // Hello    //     this still works too (why wouldn't it)

Callback functions

Consider a function ask(question, yes, no) with three parameters:

function ask(question, yes, no) {
  if (confirm(question)) yes()
  else no();
}

function showOk() {
  alert( "You agreed." );
}

function showCancel() {
  alert( "You canceled the execution." );
}

// usage: functions showOk, showCancel are passed 
// as arguments to ask
ask("Do you agree?", showOk, showCancel);

Arrow Functions


// Syntax
let func = (arg1, arg2, ...argN) => expression

// Is the same as:
let func = function(arg1, arg2, ...argN) {
  return expression;
};
// An example
let sum = (a, b) => a + b;

/* The arrow function is a shorter form of:

let sum = function(a, b) {
  return a + b;
};
*/

alert( sum(1, 2) ); // 3

Arrays


var myArray = [1, 2, 3];
var theSameArray = new Array(1, 2, 3);
console.log(myArray[1]);      // prints out 2
var myArray = []
myArray[3] = "hello"
console.log(myArray); 
// Will print out: [undefined, undefined, undefined, "hello"]
var myArray = ["string", 10, {}]

Array Manipulations


push and pop

var myStack = [];
myStack.push(1);
myStack.push(2);
myStack.push(3);
console.log(myStack); // 1,2,3
console.log(myStack.pop()); // 3
console.log(myStack); // 1, 2

Queues using shift and unshift

var myQueue = [];
myQueue.push(1);
myQueue.push(2);
myQueue.push(3);

console.log(myQueue.shift()); // 1
console.log(myQueue.shift()); // 2
console.log(myQueue.shift()); // 3
var myArray = [1,2,3];
myArray.unshift(0);
console.log(myArray);       // will print out 0,1,2,3

splice

var myArray = [0,1,2,3,4,5,6,7,8,9];
var splice = myArray.splice(3,7);

console.log(splice);        // will print out 3,4,5,6,7
console.log(myArray);       // will print out 0,1,2,8,9

Objects


// Initializing an object
var emptyObject = {};
var personObject = {
    firstName : "John",
    lastName : "Smith"
}
var personObject = {
    firstName : "John",
    lastName : "Smith"
}
personObject.age = 23;
personObject["salary"] = 14000;
for (var member in personObject)
{
    if (personObject.hasOwnProperty(member))
    {
        console.log("the member " + member + " of personObject is " + personObject[member])
    }
}