PROGRAMOWANIE JAVASCRIPT

Programowanie JavaScript 02

Javascript

Wprowadzenie

function

function square(number) {
  return number * number;
}
square(3) // 9
(function(number) {
  return number * number;
}(3)) // 9

Deklaracja (function expression)

const square = function(number) { return number * number }
square(3) // 9
const factorial = function fac(n) { return n < 2 ? 1 : n * fac(n - 1) }
console.log(factorial(3))

Rekurencja

function foo(i) {
  if (i < 0)
    return;
  console.log('begin: ' + i)
  foo(i - 1);
  console.log('end: ' + i)
}
foo(3)
function factorial(x) {
  // TERMINATION
  if (x < 0) return;
  // BASE
  if (x === 0) return 1;
  // RECURSION
  return x * factorial(x - 1);
}
factorial(3) //6
step x return
1 3 3 * factorial(2)
2 2 2 * factorial(1)
3 1 1 * factorial(0)
4 0 0
5 -1 return

Zagnieżdżone

function A(x) {
  function B(y) {
    function C(z) {
      console.log(x + y + z)
    }
    C(3)
  }
  B(2)
}
A(1)

Operatory

Mozilla

Number / date / string

Decimal

10
123123

Binary

0b10000000000000000000000000000000

Hexadecimal

0XA  // 10

Octal

0644 // 420

Number

biggestNum = Number.MAX_VALUE;
smallestNum = Number.MIN_VALUE;
infiniteNum = Number.POSITIVE_INFINITY;
negInfiniteNum = Number.NEGATIVE_INFINITY;
notANum = Number.NaN;

Math

Math.PI
Math.sin(3.14)

Date

Xmas95 = new Date("December 25, 1995 13:30:00")
endYear = new Date(1995, 11, 31, 23, 59, 59, 999)

Notation

  • Seconds and minutes: 0 to 59
  • Hours: 0 to 23
  • Day: 0 (Sunday) to 6 (Saturday)
  • Date: 1 to 31 (day of the month)
  • Months: 0 (January) to 11 (December)
  • Year: years since 1900

String

const hello = 'Hello, World!'
const helloLength = hello.length
hello[0] = 'L'
console.log(hello[0])

Multilines

console.log('line 1\n\
line 2');

Interpolation

const five = 5;
const ten = 10;
console.log('Fifteen is ' + (five + ten) + ' and not ' + (2 * five + ten) + '.')
console.log(`Fifteen is ` + (five + ten) + ` and not ` + (2 * five + ten) + `.`)
console.log(`Fifteen is ${five + ten} and not ${2 * five + ten}.`)

Objects

myObj = new Object()
str = 'myString'
rand = Math.random()
obj = new Object()

myObj.type              = 'Dot syntax'
myObj['date created']   = 'String with space'
myObj[str]              = 'String value'
myObj[rand]             = 'Random Number'
myObj[obj]              = 'Object'
myObj['']               = 'Even an empty string'
myObj[[]]               = new Array(10)

console.log(myObj)

Ćwiczenia

  • nodejs
  • uruchomić przykłady
  • napisać silnie silnia(4) //24
  • napisać ciąg fibonacciego fib(4) //3 fib(7) //13