JavaScript Fundamentals – A brief glance at the basics of JavaScript – Variables



JavaScript Fundamentals – A brief glance at the basics of JavaScript – Variables

0 1


presentation-javascript-fundamentals

A presentation on javascript fundamentals.

On Github crazyjaco / presentation-javascript-fundamentals

JavaScript Fundamentals

A brief glance at the basics of JavaScript

Created by Bradley Jacobs / @crazyjacoBased on a presentation given by Ben Alman / @cowboy

JavaScript is quirky.

Variables

Case Sensitive

foo != FOO javascript != JavaScript

Initializing Variables

Variables are undefined by default
var foo;
// undefined
Values can be assigned at time of declaration
var foo = 1; // Good.
bar = 1; // Bad. Works, but don't do this. Creates global var
var foo; console.log(foo);

Variable Scope

  • Vars are local to the function they are declared in.
  • If created outside of any functions, var becomes global.
var foo = 1;
function scope() {
	var bar = 2;
	return bar;
}
console.log(foo); // 1
console.log( scope() ); // 2
console.log(bar); // undefined
Time to connect some dots var foo = 1; function scope2() {   bar = 2;   return bar; } console.log(foo); console.log( scope() ); console.log(bar); //???

Variable Scope (Cont.)

Watch your syntax

var a = 1, b = 2, c = 3;

// tempting to write like this:
var a = 1,
	b = 2,
	c = 3;

// Mistakes will be costly
var a = 1,
	b = 2   // Missing comma. JS will insert a semi-colon here.
	c = 3;

// Will interpret like this:
var a = 1,
	b = 2;
	c = 3;  // c is now in the global scope. :(

Variable Scope (Cont.)

The Global Object for a web page can be accessed by 'window'. This refers specifically to the browser. Globally scoped variables can be accessed by:
window.varname
The Document Object refers specifically to the DOM (the html tag and all its children)
document.body

Data Types (Primitives)

Primitives

  • undefined
  • null
  • boolean
  • string
  • number

Everything else is an object (even Dates moment.js) Using new with constructor function will always return an object

typeof(true);			// boolean
typeof( new Boolean(true) );	// object

typeof(42);			// number
typeof( new Number(42) );	// object

typeof("oomph");		// string
typeof( new String("oomph") ); 	// object

Skipping constants

Booleans

Strings

Some helpful properties and methods
  • varname.length (property)
  • varname.indexOf()
  • varname.toLowerCase()
  • varname.split()
  • varname.charAt()
  • varname.substring()
"Hello World".length 	// 11
"Hello World".indexOf("W")  // 6
"Hello World".toLowerCase() // "hello world"
"Hello World".split(" ")    // ["Hello", "World"]
"Hello World".charAt(0)     // "H"
"Hello World".substring(6)  // "World"

Numbers (are quirky)

All numbers are 64-bit float. Rounding issues
0.1 + 0.2
0.01 + 0.02
0.001 + 0.002
Infinity is a thing and you can test it!
1/0				// Infinity
isFinite(1/0);			// false
isFinite(Infinity);		// false (global function)
NaN has to be tested
"six" - "four";			// NaN
"NaN" == "six" - "four";	// false
typeof(NaN);			// number  what? 
typeof("NaN");			// string
isNaN("six" - "four");		// true (global function)
Strings parsed to numbers with parseInt & parseFloat

undefined & nulls

Everything essentially defaults to undefined. Variable declaration
var foo;		// undefined
Object Properties
var obj = {};
obj.fool; 		// undefined
Functions
function doNothing() {}
doNothing();	 	// undefined
The void operator
void(0);		// undefined
null can be explicitly assigned to a variable

Big Takeaways so far

Variables can be:
  • undefined
  • set to null
  • references to objects
  • or contain values

Functions

What are functions?

  • Groups of code designated to be run at a later time.
  • Represented by a variable
  • Must explicitly be called using ()'s
  • Return "undefined" by default
  • Local to the function, inside which, it is created
Functional Declaration
function sayHi(toWho) {
	return "Hello " + toWho;
}
Better Functional Declaration?
var sayHi = function(toWho) {
	return "Hello " + toWho;
}

Immediately Invoked Functional Expression (IIFE)

(function(toWho) {
	return "Hello " + toWho;
})("World!");
Used in jQuery to safely use the $
(function($) {
	return $("#myselector");
})(jQuery);
Drawbacks?
  • DOM may not have loaded yet. Surround with jQuery(document).ready() or put in footer

Arguments object

  • Part of every function
  • Object that acts like an array
  • can use arguments.length to get number of args at invokation
var myfunction = function(a, b){
	console.log(arguments.length);
}
myfunction(1, 2, 3, 4, 5, 6);

Variable and Functional Hoisting

Variable Hoisting

  • All declarations will be hoisted to the top of the local scope
  • Assignments are not hoisted
  • Can refer to a variable, not yet declared, but with no value, it will be undefined
var myvar = "my value";
(function() {
  console.log(myvar); // undefined
  var myvar = "local value";
})();
Interpreted as:
var myvar = "my value";
(function() {
  var myvar;
  console.log(myvar); // undefined
  myvar = "local value";
})();

Functional Hoisting

function hoistme(state) {
  if (state) {
    function getValue() { return "you expect this"; }
  } else {
    function getValue() { return "you get this, no matter what"; }
  }
  return getValue();
}
Interpretting as:
function hoistme(state) {
    function getValue() { return "you expect this"; }
    function getValue() { return "you get this, no matter what"; }
  if (state) {

  } else {

  }
  return getValue();
}
do var getValue; at top of function instead

Literals

Fixed values you are literally/explicitly specifying

  • Array Literals
  • Boolean Literals
  • Floating-Point Literals
  • Integers
  • Object Literals
  • String Literals

Array Literal

var siteops = ['jim', 'alex', 'john', 'nick', 'bradley'];

Object Literal

var beer = { type: "IPA", packaging: "bottled", microbrew: false };
console.log(beer.type);
This is JSON (JavaScript Object Notation)

Objects

Objects

Everything that is not a primitive is an object

var obj = new Object();	// new keyword w/ a constructor creates an object
var obj = {};		// Less verbose

Objects are compared by reference. Primitives are compared by value

var obj1 = {foo: 42};
var obj2 = {foo: 42};

obj1 === obj2		// false
obj1.foo === obj2.foo 	// true
Property names are always strings. Values can be anything
var rps = {
	values: ["rock", "paper", "scissors"];
	attempts: 5;
	winsNeeded: 3;
	chant: "Rock! Paper! Scissors! Shoot!";
	getWinner: function(player1, player2){
		var winner;
		switch(player1) {
			case "rock":
				winner = (player2 === "scissors") ? "player1"  :
						(player2 === "paper") ? "player2" : 
						"tie";
				break;
			case "paper":
				winner = (player2 === "rock") ? "player1"  :
						(player2 === "scissors") ? "player2" : 
						"tie";
				break;
			case "scissors":
				winner = (player2 === "paper") ? "player1"  :
						(player2 === "rock") ? "player2" : 
						"tie";
				break;
		}
		return winner;
	}
}
Object Prototypes
Coersion and Comparison

== vs ===

=== ("Strict Equality Comparison")

// Type(x)          Values                                Result
// Type(x) different from Type(y)...                      false
// Undefined or Null                                      true
// Number           x same value as y (but not NaN)       true
// String           x and y are identical characters      true
// Boolean          x and y are both true or both false   true
// Object           x and y reference same object         true
// Otherwise...                                           false
(Copied from Ben Alman's JS notes)

== ("Abstract Equality Comparison")

Measure of Truthy vs Falsy
// Type(x)              Type(y)               Result
// If x and y are the same type...            Follow === operator rules.
// Null                 Undefined             true
// Undefined            Null                  true
// Number               String                x == toNumber(y)
// String               Number                toNumber(y) == x
// Boolean              (any)                 toNumber(x) == y
// (any)                Boolean               x == toNumber(y)
// String or Number     Object                x == toPrimitive(y)
// Object               String or Number      toPrimitive(x) == y
// Otherwise...                               false
(Copied from Ben Alman's JS notes)

5 falsy values (that are not actually false)

  • 0
  • ""
  • null
  • undefined
  • NaN

falsy values coerce to false

Everything that is not falsy is truthy

if(null) { This will not execute }			
if(!null) { This will execute }

Falsy Quirks

"", 0 and false are all equivalent

null and undefined are equivalent

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

NaN never does what you expect

NaN == NaN  // false
NaN === NaN // false
...And lots more

Takeaways

  • When checking for falsy/truthy, pass directly into if(), negating if necessary
  • Always use === or !== when comparing for truth or fallacy
  • Use == or != when comparing to null or undefined

Resources: