Javascript 101

Temel kavramlar ve kültür

Kod Gemisi, Nisan 2017
destan@kodgemisi.com

Ben Kimim

  • Destan Sarpkaya
  •  
  • Java (Spring Framework, JavaEE)
  • Javascript (React, Angular, jQuery)
  • destan@kodgemisi.com

Web Nasıl Çalışır

client - server

Yalnızca Önemli Noktalar

Teach Yourself Programming in Ten Years

Bir programlama dili birkaç saatte/günde öğrenilemez.

Javascript Nedir?

  • Dinamik, yorumlanan bir betik (scripting) dili
  • Brendan Eich, Netscape 1995
  • Java ve C++ ile benzer söz dizimi (syntax)
  • ECMAScript: standart, specification

Java

 

Car

Javascript

 

Carpet

vs

vs

// one line comment 
if (iceCreamVanOutside || houseStatus === 'on fire') {
  console.log('You should leave the house quickly.');
}
else {
  console.log('Probably should just stay in then.')
}

/* multi
  line
  comment
*/
switch (choice) {
  case 'sunny':
    textContent = 'Wear shorts! Go to the beach.';
    break;
  case 'rainy':
    textContent = 'Stay inside.';
    break;
  default:
    textContent = '';
}


var i = 0;

while (i < cats.length) {
  if (i === cats.length - 1) {
    info += 'and ' + cats[i] + '.';
  } else {
    info += cats[i] + ', ';
  }

  i++;
}

';' zorunlu değil

Genel olarak Java, C ve C++'tan alışkın olduğumuz söz dizimi

// define a function
var fn = function () {
    //...
} // semicolon missing at this line

// then execute some code inside a closure
(function () {
    //...
})();






// Ternary operator
var greeting = isBirthday ? 'Happy birthday!' : 'Good morning.'

';' nadiren gerçekten gerekli

  • Number
  • String
  • Boolean
  • Symbol (new in ES2015)
  • Object
    • Function
    • Array
    • Date
    • RegExp
  • null
  • undefined

Javascript'te Tipler

Değişkenler

var name  // value is undefined
var city = "izmir"
var year = 2017
planet = "earth" // global







// ES6 features 
// IE11+
// http://caniuse.com/#search=let

let language = "javascript"


const PI = 3.14
PI = 3 // Uncaught TypeError: Assignment to constant variable.





console.log(name) // undefined

console.log(city) // izmir

console.log(country) // Uncaught ReferenceError: country is not defined

 in JavaScript, blocks do not have scope; only functions have scope.

// There's no such thing as an integer in JavaScript
0.1 + 0.2 == 0.30000000000000004

var r = 2
var circumference = Math.PI * (r + r)

var i = 010 // binary
// i == 8

var j = 0x10 // hexadecimal
// j == 16

var someNumber = "250"
var n = parseInt(someNumber)
// n == 250

someNumber = "250.5"
parseInt(someNumber) // 250
parseFloat(someNumber) // 250.5

parseInt("naber") // NaN

NaN + 5; // NaN

isNaN(NaN); // true

1 / 0; //  Infinity
-1 / 0; // -Infinity

isFinite(1 / 0); // false
isFinite(-Infinity); // false
isFinite(NaN); // false

Numbers

// Strings in JavaScript are sequences of Unicode characters. UTF-16

var greeting = "hello"

greeting == 'hello' // true

"hello" == 'hello' // true


// BEWARE JSON standard needs (")


'hello'.length; // 5

'hello'.charAt(0); // "h"

'hello, world'.replace('hello', 'goodbye'); // "goodbye, world"

'hello'.toUpperCase(); // "HELLO"

'hello, world'.split(',') // ["hello", " world"]

"\"hello\""

'"hello"'

Strings

JavaScript için null ve undefined farklıdır.

null: Özellikle değeri olmadığı belirtilmiş

undefined: initialize edilmemiş, boş

Boolean();      // false
Boolean('');    // false
Boolean(false); // false

Boolean(true);  // true
Boolean(234);   // true

false
true

var isAdmin = true

Boolean

// Falsy
if (false)
if (null)
if (undefined)
if (0)
if (NaN)
if ('')
if ("")
if (document.all)


// Truthy
if (true)
if (-1)
if ({})
if ([])
if (42)
if ("foo")
if (new Date())
if (-42)
if (3.14)
if (-3.14)
if (Infinity)
if (-Infinity)

false degerler (Falsy Values)

var value = 0

if( value && value==false ) {
  alert("huh?")
}


value = '0' // now what?
var obj = new Object()

var obj2 = {} // object literal

var obj3 = {
  name: 'Carrot',
  'for': 'Max',
  details: {
    color: 'orange',
    size: 12
  }
}

obj3.details.color; // orange
obj3['details']['size']; // 12


Nesne (Object)

  • Dictionaries in Python.
  • Hashes in Perl and Ruby.
  • Hash tables in C and C++.
  • HashMaps in Java.
  • Associative arrays in PHP.
function Person(name, age) {
  this.name = name;
  this.age = age;
}

// Define an object
var me = new Person('Destan', 30);

me.name // "Destan"
me.age  // 30

me instanceof Person // true
me instanceof Object // true
me instanceof Window // false



me.name = 'John'
me['name'] = 'John'




// [ ] is good for dynamic property access
var prop = 'name'
console.log(me[prop])

Nesne (Object)

x = 1

x += 5    // 6

x = x + 5 // 11

x++       // 12

++x       // 11



'hello' + ' world'; // "hello world"

'3' + 4        // "34"

'3' + 4 + 5   // "345"

3 + 4 + '5'   // "75"




123 == '123'; // true
1 == true;    // true

123 === '123'; // false
1 === true;    // false

Operators

// Abstract Equality Comparison (==)
// Strict Equality Comparison (===)
// For more https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness



null == undefined  // true
null === undefined // false

0 == '0'  // true
0 === '0' // false



var num = 0;
var obj = new String('0');
var str = '0';

console.log(num === num); // true
console.log(obj === obj); // true
console.log(str === str); // true

console.log(num === obj); // false
console.log(num === str); // false
console.log(obj === str); // false
console.log(null === undefined); // false
console.log(obj === null); // false
console.log(obj === undefined); // false



== vs ===

var a = new Array();
a[0] = 'dog';
a[1] = 'cat';
a[2] = 'hen';
a.length; // 3


var b = ['dog', 'cat', 'hen'];
b.length; // 3

b[0] // 'dog'
b[1] // 'cat'


// Beware: No error!
b[30] // undefined


// Beware
var a2 = ['dog', 'cat', 'hen'];
a2[100] = 'fox';
a2.length; // 101


var arr = [1, 2, 'no type', 'check', true, 'here']

typeof arr // "object"

Array.isArray(arr) // true 

Array.isArray() //IE9+

Array

var a = ['dog', 'cat', 'hen']

a.push('fish');
var animal = a.pop() //Removes and returns the last item.

a.join(', ') // "dog, cat, hen"


for (var i = 0; i < a.length; i++) {
  // Do something with a[i]
}


// ECMAScript 5  (IE9+)
a.forEach(function(currentValue, index, array) {
  // Do something with currentValue or array[index]
});

Array operations

function add(x, y) {
  var total = x + y;
  return total;
}

add(); // NaN 


add(2, 3, 4); // 5. Added the first two; 4 was ignored


// arguments
function add() {
  var sum = 0;
  for (var i = 0, j = arguments.length; i < j; i++) {
    sum += arguments[i];
  }
  return sum;
}

add(2, 3, 4, 5); // 14


add.apply(null, [2, 3, 4, 5]) // 14


// anonymous functions
var add = function() {
  var sum = 0;
  for (var i = 0, j = arguments.length; i < j; i++) {
    sum += arguments[i];
  }
  return sum;
}

Functions

// Built-in browser functions
var myText = 'I am a string';
var newString = myText.replace('string', 'sausage');
console.log(newString);


// Custom functions
function toFullName(name, surname) {
  return name.trim() + ' ' + surname.trim();
}


var fullName = toFullName('javadays', '2017')

Functions

Functions vs methods

var a = 1;
var b = 2;

(function() {
  var b = 3;
  a += b;
})();

a; // 4
b; // 2



var fn = function() {
  var b = 3;
  a += b;
}

(fn)()

Anında çağırılan fonksiyon tanımları

Immediately invoked function expressions (IIFE)

"b" için scope'a dikkat!

function makePerson(first, last) {
  return {
    first: first,
    last: last
  }
}

var p = makePerson('Simon', 'Willison');

// {first: "Simon", last: "Willison"}

Nesne Döndüren Fonksiyonlar

function toPerson(fullName) {
  
  function getNameArray(n) {
    return n.split(' ')
  }

  var names = getNameArray(fullName)
  return {
    firstName: names[0],
    lastName:  names[1] 
  }
}

toPerson("John Snow") // {firstName: "John", lastName: "Snow"}

İç içe Fonksiyonlar

(Inner functions)

function toPerson(fullName) {

    function getNameArray(n) {
        return n.split(' ')
    }

    var names = getNameArray(fullName)

    var result = {
        firstName: names[0],
        lastName: names[1]
    }
    return
    result
}


toPerson("John Snow") // undefined

return

var arr = [1, 2, 3]

function add() {
    var sum = 0
    for(var i = 0; i < arr.length; i++) {
        sum += arr[i]
        var lastIndex = i
    }

    console.log(sum)       // 6
    console.log(lastIndex) // 2
}

add()

console.log(sum)       // Uncaught ReferenceError: sum is not defined
console.log(lastIndex) // Uncaught ReferenceError: lastIndex is not defined



// TODO try with global "sum" variable

// TODO try with block scope "lastIndex" variable

Scope

function init() {
  var name = 'Java Days Istanbul';
  function displayName() {
    alert(name); 
  }
  displayName();    
}

init() // alert 'Java Days Istanbul'



function init() {
  var name = 'Java Days Istanbul';
  function displayName() {
    alert(name); 
  }
  return displayName;    
}

var fn = init()

fn() // alert 'Java Days Istanbul'

Closure

function init(name) {

  function displayName() {
    alert(name); 
  }

  return displayName;    
}




var fn = init('Java Days Istanbul')

fn() // alert 'Java Days Istanbul'


var fn2 = init('Linux Yaz Kampi')

fn2() // alert 'Linux Yaz Kampi'

Closure (devam)

function init() {

  console.log('init', this)

  function displayName() {
    console.log('displayName', this)
  }

  return displayName;    
}



var fn = init()

fn()



var obj = {
    myMethod: init
}

var fn2 = obj.myMethod()

fn2()



fn2.apply(new Date(), null)

this

var obj = {
    myMethod: function() {

        console.log('init', this)

        function displayName() {
            console.log('displayName', this)
        }

        return displayName;
    }
}

var fn = obj.myMethod()

fn()



var obj2 = {
  anotherMethod: fn
}


obj2.anotherMethod()

this (devam)

the value of this is determined by how a function is called

var obj = {
    myMethod: function() {

        console.log('init', this)

        function displayName() {
            console.log('displayName', this)
        }

        return displayName.bind(new Date());
    }
}

var fn = obj.myMethod()

fn()



var obj2 = {
  anotherMethod: fn
}


obj2.anotherMethod()

bind

var obj = {
    myMethod: function() {

        console.log('init', this)

        function displayName(name) {
            console.log(name, this)
        }

        return displayName.bind(new Date(), 'this is js');
    }
}

var fn = obj.myMethod()

fn()


fn('where is my param')

// =============================================

var obj = {
    myMethod: function() {

        console.log('init', this)

        function displayName(name) {
            console.log(arguments[0], arguments[1], this)
        }

        return displayName.bind(new Date(), 'this is js');
    }
}

bind (devam)

showMe()

function showMe() {

    console.log( 'c is', c )

    var c = 10;
    
    console.log( 'c is now', c )
}

Hoisting (Yukarı Çekme)

function showMe() {
    var c

    console.log( 'c is', c )

    c = 10

    console.log( 'c is now', c )
}

showMe()
num = 6
num + 7
var num

console.log(num)
var num
num = 6
num + 7

console.log(num)
console.log(showMe) // undefined

showMe()            // Uncaught TypeError: showMe is not a function

var showMe = function () {

    console.log( 'c is', c )

    var c = 10;
    
    console.log( 'c is now', c )
}

Hoisting (Function expressions)

var showMe

console.log(showMe) // undefined

showMe()            // Uncaught TypeError: showMe is not a function

showMe = function () {

    console.log( 'c is', c )

    var c = 10;
    
    console.log( 'c is now', c )
}

callbacks

Teşekkürler

Javascript 101 (tr)

By KodGemisi

Javascript 101 (tr)

  • 489