More JavaScript
Foundationals
Andrew Krawchyk
3/14/15
General Assembly
Agenda
- Intros
- Variables
- Data Types
- Enumeration
- Conditionals
General Assembly
ISL
JavaScript
it's great for devs!
Easy to develop
- Dynamic Typing
- Quick and dirty
- Fast success
Variables
Not much to do without 'em
- Save values
- Dynamic programs
- Data storage
Constant
Values that are restricted from change; immutable.
Private
Or "voyeur" in this case. No truly private vars until ES7.
Different Kinds
Variables
Convention is for camelCasing in JS
Constants
- Strings, objects, numbers
- Anything immutable in your program's universe
- ES6 introduces them with 'const' keyword
- Convention from C programming to use all caps for naming and recognizing them easily
Useful when:
- Defining a discrete value throughout your application:
- MAX_UPLOAD_SIZE = 1024;
- APP_NAME = 'mania';
Private
- Variables can be created such that they are restricted from outside access
- But they can still be manipulated internally
- Only good way to do so in ES5 is memory inefficient:
function Person(name) {
this.getName = function() { // each Person instance carries own getName func
return name;
};
} - Convention is to prefix variable with "_"
- Indicate to developers that it is private:
var _minVal = 0;
this._maxVal = 20;
Advanced
var Person = (function() {
var sharedName;
function Person(name) {
sharedName = name;
}
Person.prototype.getName = function() {
return sharedName;
};
return Person;
}());
Shared values across all instances:
s = new Person('steve');
s.getName(); // 'steve'
a = new Person('art');
s.getName(); // 'art'
Data Types
Dynamic Typing
read: Look Mom, no hands!
Makes JS easier
- No mental overhead for defining types
- Forgiving, JS won't error when types mismatch
- JS massages types to try and work together
Makes JS harder
- When types mismatch, it can be hard to debug
var str = '55';
var num = 55;
console.log(str + num);
// '5555'
var pop = 'a long time';
function setPop(person) {
person.populraity = pop;
}
When I say:
var dynamicVariable = 3;
You say:
Number
dynamicVariable = '3';
String
dynamicVariable = true;
Boolean
dynamicVariable = null;
dynamicVariable
undefined
Null
When I say:
var dynamicVariable = 3;
You say:
"number"
dynamicVariable = '3';
"string"
dynamicVariable = true;
"boolean"
dynamicVariable = null;
dynamicVariable
"undefined"
"object"
typeof:
Number
JavaScript has a data type, NaN, which represents everything "not a number."
Null
There is an important but subtle difference between null and undefined.
Edge Cases
Do not test for NaN, use the built-in function isNaN(val).
Also feel free to use typeof.
First, typeof null is "object."
Second, when comparing:
null == undefined; // true
but...
null === undefined: // false
undefined
the JavaScript error 404
undefined is the value automatically assigned to all variables that are not declared or are declared without a value assignment.
undefined is kind of funny
Curiously it's not a reserved word:
(function(undefined) {
console.log(undefined);
})('why?');
You cannot change the value of undefined - it is a built-in called a primitive.
var favorites;
console.log(abc);
// ReferenceError abc is not defined
typeof abc === 'undefined'
// true
Boolean
Not a lot to say
Truthy
true
1
'true'
'false'
[]
{}
function() {}
Falsy
false
0
undefined
NaN
'' // that's the empty string
null
Strings
Strings are easy to use to represent complex data. This can often be helpful in the short term, for example adding a separator between values to store names. Works until you come across a name with a comma (for whatever reason).
Useful things
- .length
- .substr(start[, length])
- .match(regexp)
- .trim()
What are they good for?
- Storing text related data
What are they bad for?
- Storing complex data
- Math
"37" - 7 // 30
"37" + 7 // "377"
How do I get there?
.toString('asdf');
val + 'asdf';
What about from there?
parseInt('5', 10);
parseFloat('3.14');
Objects & Arrays
Objects: Keyed Storage
- Collection of properties
- Everything except primitives
are objects in JS - Incredibly flexible
- Can store any data-type
Arrays: Indexed Storage
- Collection of values
- Best practice to store a
single data-type - Great for looping & iteration
Convert to object/array
- JSON.parse(string)
- Object.keys(array)
Convert from object/array
- JSON.stringify(object)
- array.join(', ')
Conditionals
Ternary
var jobsCountRemaining = 2;
// ternary
var completed = jobsCountRemaining === 0 ? true : false;
return completed;
// if-else
if (jobsCountRemaining === 0) {
completed = true;
} else {
completed = false;
}
return completed;
Equality vs. Identity
or why you always use ===
Equality tests the coerced value:
0 == '0' // true
1 == 2 // false
Identity tests equality as well as type of the value:
0 === '0' // false
1 === 2 // false
Enumeration
Useful when:
- Storing related values
- Creating complex data-types
- Representing human objects
- Always the same predictable type
- Use objects and capitalize the
last identifying key (example on
next slide)
Best practices:
Objects:
Easy way to enumerate collections in JS
var statusesEnum = {
LIKED: 'liked',
DISLIKED: 'disliked',
BLOCKED: 'blocked',
REPORTED: 'reported'
};
var alertColorsEnum = {
INFO: '#00FF2F',
WARNING: '#FFFB00',
ERROR: '#FF8800',
CRITICAL: '#FF0000'
}
Can be repetitive, however it defines a commonly used thing in an application
Worth the small amount of repetition to have a single source of truth for these values
Flexibility:
var statusesEnum = {
LIKED: 'liked',
DISLIKED: 'disliked',
INVISIBLE: 'invisible',
PRIVATE: 'private',
BLOCKED: 'blocked',
REPORTED: 'reported'
};
Can easily add new statuses
Can easily recognize previously added statuses
var statusesEnum = {
LIKED: 'liked',
UPVOTED: 'upvoted',
DISLIKED: 'disliked',
DOWNVOTED: 'downvoted',
BLOCKED: 'blocked',
REPORTED: 'reported'
};
Practice
JavaScript
By Andrew Krawchyk
JavaScript
- 1,059