JavaScript

Core Concepts

ACMUT WWW 2018

by @theshem

TOC

  • What is JS?
  • How to
  • Variables
  • Data types
  • Value vs Reference
  • == vs ===
  • Functions

Tools

WHAT TOOLS DO YOU NEED?

  • A text editor; a program that allows you to edit plain text files. (Notepad++, Sublime Text, VS Code, Brackets, etc.)
  • A JavaScript runtime; e.g. a web browser. (Chrome, Firefox, Safari, or Opera.)

What is JS

JavaScript is a scripting language.

 

  • Client-side programming

 

 

 

  • Server-side programming
  • Updating content dynamically
  • Control audio/video
  • Handling URL changes
  • ...
  • Web servers
  • Working with databases
  • File system
  • CLI scripts
  • ...

More on MDN

How To

More on MDN

  • External JavaScript (in <head> or <body>)

 

 

  • Internal JavaScript (in <head> or <body>)

 

 

 

  • Inline JavaScript handlers
<script src="script.js"></script>
<script>
  // JavaScript goes here
</script>
<button onclick="doSomething()">Click me!</button>

Variables

Loosely typed; case-sensitive.

More on MDN

<script>
  var a = 5;
  b = 4; // Throws a ReferenceError in strict mode

  var a;
  a; //-> 5
</script>
<script>
  var a = 5;
  a = 'changed to string';
  a = [1, 2, 3];

  a; //-> [1, 2, 3]
</script>

Data Types

  • Primitives (are immutable)
    • string
    • number
    • boolean
    • null
    • undefined
    • symbol (ES2015)

  • Objects
    • Array
    • Object
    • Function
// Primitive values
var str = 'my string';
var num = 42;
var bl = true;

// Primitive types wrapper objects
var str2 = new String('my string');
var num2 = new Number(42);
var bl2 = new Boolean(true);

// Objects constructors
var arr = new Array(1, 2, 3);
var obj = new Object();

// literal form of objects
var arr2 = [1, 2, 3];
var obj2 = { key: 'value' };

function add(a, b) { return a+b };

More on MDN

Value vs reference

Primitives are passed by value.

Objects  are passed by reference.

// Primitive values
var foo = 'foo';
var bar = foo;
bar += 'bar';

foo; //-> 'foo'
bar; //-> 'foobar'

// Reference Values
var baz = [1, 2, 3]
var qux = baz;
qux.push(4);

baz; //-> [1, 2, 3, 4]
qux; //-> [1, 2, 3, 4]

== vs ===

Strict equality (x === y)

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

num === num;         // true
obj === obj;         // true
str === str;         // true

num === obj;         // false
num === str;         // false
obj === str;         // false
null === undefined;  // false
obj === null;        // false
obj === undefined;   // false

More on MDN

  1. Different types? false
  2. x is undefined or null? true
  3. Booleans, strings?
    1. ​Same value? true
    2. Otherwise; false
  4. Numbers?
    1. ​Same value? true
    2. NaN? false
    3. +0, -0? true
    4. Otherwise; false
  5. Objects?
    1. Same object (reference)? true
    2. Otherwise; false

 

== vs ===

Loose equality ==

More on MDN

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

num == num;        // true
obj == obj;        // true
str == str;        // true

num == obj;        // true
num == str;        // true
obj == str;        // true
null == undefined; // true

// both false,
// except in rare cases
obj == null;
obj == undefined;
  1. Same types? ...
  2. undefined or null? true
  3. ...
  4. ...
  5. ...
  6. ...
  7. ...
  8. ...
  9. ...
  10. ...

 

You really don't want to know all the conditions!

Functions: Declaration vs Expression

More on MDN

// Function Declaration
function square(number) {
  return number * number;
}


// Function Expression
var square = function(number) {
  return number * number;
};


var x = square(4); // x gets the value 16

Scope

More on MDN

// The following variables
// are defined in
// the global scope
var num1 = 20,
    num2 = 3;

// This function is defined
// in the global scope
function multiply() {
  return num1 * num2;
}

multiply(); // Returns 60
var name = "John";

// A nested function example
function getScore(num1) {
  var num2 = 5;

  function add() {
    return name + ' scored ' + (num1 + num2);
  }
  
  return add();
}

// Returns "John scored 6"
getScore(1);

Hoisting

More on MDN

// ReferenceError: variable is not defined
console.log(variable);

Accessing undeclared variables:

console.log(hoist); //-> undefined

var hoist = 'The variable has been hoisted.';

Accessing variables before var statement:

Variable Declaration

Why?

Hoisting

More on MDN

function add(a, b) {
  return a + b;
}

add(3, 4); //-> 7
add(3, 4); //-> ?

function add(a, b) {
  return a + b;
}

Function Declaration

Invoking function before function declaration:

Event Loop

An Intro to concurrency in JavaScript

More on MDN

Event Loop

Call stack

More on MDN

function multiply(x, y) {
  return x * y;
}

function printSquare(x) {
  var s = multiply(x, x);
  console.log(s);
}

printSquare(5);

Event Loop

Zero delays

More on MDN

(function() {

  console.log('this is the start');

  setTimeout(function cb() {
    console.log('this is a msg from call back');
  });

  console.log('this is just a message');

  setTimeout(function cb1() {
    console.log('this is a msg from call back1');
  }, 0);

  console.log('this is the end');

})();

Context

The this keyword

More on MDN

var test = {
  prop: 42,
  func: function() {
    return this.prop;
  },
};

console.log(test.func());
// expected output: 42

The value of this is (almost) determined by how a function is called.

Context

  • Global context

 

 

 

  • Function context

More on MDN

// In web browsers, the window object
// is also the global object:
console.log(this === window); // true
function f1() {
  return this;
}

f1() === window; // true

f1.call('my ctx');  //-> 'my ctx'
f1.apply('my ctx'); //-> 'my ctx'
// .bind() returns a new function
// that when called has its 'this'
// set to the provided value
f1.bind('my ctx');
  • Simple call ()
  • .call(), .apply(), .bind()
  • As an object method
  • with new keyword

"use strict";

  • Get rid of some JavaScript silent errors
  • Let JavaScript engines perform optimizations
  • ...

More on MDN

"use strict";
myFunction();

function myFunction() {
    y = 3.14; // Err: y is not declared
}
x = 3.14; // This will not cause an error. 
myFunction();

function myFunction() {
   "use strict";
    y = 3.14; // This will cause an error
    return this; // this === undefined
}
Made with Slides.com