James Sherry PRO
Web Development Tutor and Co-Founder of { The Jump } Digital School
var str = new String('Hello');
typeof
'typeof someThing' might give you 'string', or 'number' gets you the basic type
But what is an object:
In the C layer below data is often held in [hash] TABLES. The whole DOM API (the way we interact with a web page) is run off a table which is re-analysed every time something changes. OBJECTS are a fast way to access those tables.
We'll deal with creating our own objects later on, but for now just understand that they can hold values and methods (functions) and in the primitives you can use these to manipulate and format the data.
Properties:
Methods (selected examples):
// Can be enclosed in double or single quotes.
var greeting = "hello";
var valediction = 'goodbye';
// BEWARE: var do = 'don't'; <- will not work because it thinks the
// string is 'don', then it finds the t and the next ' and doesn't understand
// Ways to fix:
var do = "don't";
//or
var do = 'don\'t'; //Here, the backslash 'escapes' the second single quote (see link below)
// You can declare a 'String Literal' (a string made 'on the fly'), like:
'test'
// so that you can 'concatenate' (join) strings (using the + operator) like
console.log('Hi, my name is ' + rapper); //if the value of rapper is a string
// it will concatenate instantly before console.log is called; else it will be coerced
// into a string and then concatenated: 'Hi my name is undefined'
2 + 2 //4
"2" + "2" // "22"
2 + 4 +"6" // "66"
3 + 6 +"9" + 4 // "994"
As soon as a string gets involved it becomes (or coerces the number into) a string.
(the reverse type coercion happens if you do any maths/logic operation (other than +, obvs) )
"664" * 1 + 3 // 667
Unlike other programming language, JavaScript only has one number type.
Java: byte, short, int, long, float, double
JavaScript: number (which, just FYI, is a double precision floating point number the same as the Java double above)
This is good as it takes a lot of worry away from you: You just declare the number and JavaScript will take care of the rest.
You can specify a number anywhere between:
(Number.MAX_VALUE) 1.7976931348623157e+308 AND (Number.MIN_VALUE) 5e-324
Anything greater than Number.MAX_VALUE is represented by the keyword Infinity (Same for Number.MIN_VALUE & -Infinity)
If maths is done and you get something that is not a computable result the system object NaN is produced. This is not your grandmother, this is Not a Number
You can find out whether this has happened by using the inbuilt method isNaN() on the number, which will return true if the value is Not a Number (i.e. an errored maths operation result)
Numbers can be exponentiated like so: 10e4, 10e-5
Raising numbers to the power of n is done using Math.pow(number, power) or 5**4
Properties:
(You don't need any. To measure length, cast to string then measure.)
Methods:
Side note: Most objects, built in or otherwise have a toString method. This is what is returned when you console.log something - it activates its toString method. What you get back depends on how well that method has been written by the object's author. See arguments keyword in functions, for example
Two public built-in objects that help you with numbers:
Number
contains: .isNaN(<value>), .parseInt(<value>, <radix>), .parseFloat(<value>)
use like: Number.parseInt(5.62, 10); // returns 5
Math
Contains many helper methods, including:
sin, cos, tan, pow, round, ceil, floor, random
use like: Math.pow(2, 3); // returns 8
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math
Comments are NOT processed by the interpreter. They are for humans only!!
// This is a line comment
/*
This is a
multi-line comment
*/
/*****************************************
*
* So is this; the stars make no difference
*
*******************************************/
Whenever you DO something in javascript you need to add a `;` (semi-colon) character as a line terminator.
Javascript will 'intelligently' add its own if you don't - you don't want to give it that option!!! (#contentious)
function add(a, b){
return a + b; //*
}
add(2,4); //*
var test = 4; //*
// Everywhere with a * requires
// a line terminator because
// you did something.
// NOTE that you don't need them
// after you declared a function.
function respond(){
return true;
}
// ISSUES
function thing(n) {
return //;
{
score: n
};
}
// JavaScript will insert a semicolon
// after the return keyword
Variables are used to store data. They are when we save something we want to use later.
The var keyword means 'reserve me some memory'
(let is like var, but block scoped)
The const keyword means 'reserve me some memory and don't allow changes once set'.
Only declare a var once!
/*
* Variables - things that we expect to change
* Use the 'var' keyword (or 'let' in ES6)
*/
var age = 32;
var a = 1, b = 2, c = 3; // chain creation
/*
* LET (ES6) - same as 'var' but scoped to a block
*/
let name = "James";
/*
* CONSTANTS (ES6) - things that we do not expect
* to change use the 'const' keyword
*/
const PI = 3.14;
// Using the 'var' keyword more than once will
// 'redeclare' the variable, wiping its
// original value, so to simply update it:
var num = 1; // soon to be pointless
var num = 2; //<-- wiped ^^
let num = 1;
let num = 2; //<-- Error. Can't redefine let
// USE LIKE THIS
var num;
num = 1;
num = 2;
const PI = 3.14;
const PI = 6; //<- this will error.
//Cannot redeclare constants
You use variables as symbolic names for values in your application. The names of variables, called identifiers, conform to certain rules.
A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).
The objects that you can make form a family:
side-note: object family quirk
{
name: 'James',
age: 39
}
var player = {
name: 'Ryan Giggs',
age: Math.MAX
};
$element.carousel({
noOfSlides: 4
});
var player = {
name: 'Ryan Giggs',
age: Math.MAX
};
var name = player.name;
var age = player['age'];
var player = {
name: 'Ryan Giggs',
age: Math.MAX
};
player.name = 'fred bloggs';
// player is now: { name: 'fred bloggs', age: Math.MAX }
player['age'] = 42;
// player is now: { name: 'fred bloggs', age: 42 }
Use square brackets syntax when:
A construct for:
var friends = ['Moe', 'Larry', 'Curly']; // Prefer this way
// OR
var friends = new Array('Moe', 'Larry', 'Curly');
Arrays are symbolised and declared using [ ]
var friends = ['Moe', 'Larry', 'Curly'];
console.log(friends.length); // outputs 3 as there are 3 members in the array
friends.length = 5;
Now the array will contain two 'undefined's at the end of the array
var myArray = ['str', 2, null, [1,2,4], function(){}];
//to access a member we do it by it's index in this notation:
myArray[0] // returns 'str'
myArray[1] // returns 2
// Nested arrays
myArray[3][1] // returns 2
// Accessing beyond the length
myArray[96] // undefined
myArray[-2] // undefined
myArray[myArray.length-1] // function(){}
myArray[myArray.length-2] // [1,2,4]
var myArray = ['str', 2, null, [1,2,4], function(){}];
myArray[2] = true;
console.log(myArray); // ['str', 2, true, [1,2,4], function(){}];
var myArray2 = [1, 2, 3];
myArray2.push(4);
console.log(myArray2); // [1, 2, 3, 4]
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
myFish.splice(2, 0, 'drum');
// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]
myFish.splice(2, 1);
// myFish is ["angel", "clown", "mandarin", "sturgeon"]
var myArray5 = ['a', 2, 3, 19];
// return last element
myArray5.pop(); // 19
// remove first element of array and return it
myArray5.shift(); // 'a'
// add a new element to the front of the array and return array length
myArray5.unshift(2); // 5 (the new length) [2, 'a', 2, 3, 19]
Very Basic Intro
Allow you to set values
Name Shorthand operator Meaning
Assignment x = y x = y
Addition assignment x += y x = x + y
Subtraction assignment x -= y x = x - y
Multiplication assign. x *= y x = x * y
Division assignment x /= y x = x / y
Remainder assignment x %= y x = x % y
Exponentiation assign. x **= y x = x ** y
Whatever happens on the right side of the assignment equation is put into the memory space of the
variable on the left.
So x = y+7, whatever y+7 turns out to be, it replaces whatever value x used to be.
Allow you to compare values
// These return a boolean of true or false IF the things being compared are equal.
2 == 2 // equality comparison (don't use). This results in true.
'2' == 2 // but so is this
4 === 4 // strict equality comparison. Does value AND type. ALWAYS USE!!
// What if we want to ask if something is NOT EQUAL?
2 != 5 // Not equal - again don't use
3 !== 'fish' // Strict Not equal - do use.
// Greater Than
age > 18
// Greater than or equal to
age >= 16
// Less Than
yearsDriving < 3
// Greater than or equal to
age <= 2
#dodgy
#dodgy
Allow you to do maths
Operator Description Example
Remainder (%) Binary operator. (needs 2 numbers to work)
Returns the integer remainder of dividing
the two operands. 12 % 5 returns 2.
Increment (++) Unary operator. Adds one to its operand. If
used as a prefix operator (++x), returns the
value of its operand after adding one; if used
as a postfix operator (x++), returns the value
of its operand before adding one.
If x is 3, then ++x
sets x to 4 and returns
4, whereas x++ returns
3 and, only then,
sets x to 4.
Decrement (--) Opposite of ++
Unary negation (-) Unary operator. Returns the negation of its operand.
If x is 3, then -x returns -3.
Unary plus (+) Unary operator. Attempts to convert the operand to a number,
if it is not already.
+"3" returns 3.
Prefer +=1 to ++. (Same for --)
Allow you to compare values
Operator Usage Description
Logical AND (&&) expr1 && expr2 Returns expr1 if it can be converted
to false; otherwise, returns expr2. Thus,
when used with Boolean values, && returns
true if both operands are true;
otherwise, returns false.
Logical OR (||) expr1 || expr2 Returns expr1 if it can be converted to true;
otherwise, returns expr2. Thus, when used with
Boolean values, || returns true if either
operand is true; if both are false, returns false.
Logical NOT (!) !expr Returns false if its single operand can be converted
to true; otherwise, returns true.
var a = ['one', 'two', 'three'];
a.reverse();
console.log(a); // ['three', 'two', 'one']
var arr1 = ['a', 'b', 'c'];
var arr2 = ['d', 'e', 'f'];
var arr3 = arr1.concat(arr2);
// results in a new array [ "a", "b", "c", "d", "e", "f" ]
var a = ['Wind', 'Rain', 'Fire'];
a.join(); // 'Wind,Rain,Fire'
a.join('-'); // 'Wind-Rain-Fire'
var a = ['a', 'b', 'c'];
a.forEach(function(element) {
console.log(element);
});
// a
// b
// c
var evens = [2,4,6,8,10];
evens.every(function(num){
return num % 2 === 0;
});
// ^^ returns true
evens.every(function(num){
return num % 4 === 0;
});
// ^^ returns false
var evens = [2,4,6,8,10];
evens.every(function(num){
return num % 4 === 0;
});
// ^^ returns true
var evens = [2,4,6,8,10];
var bigNumbers = evens.filter(function (num) {
return num > 5;
});
// bigNumbers [6, 8, 10]
var evens = [2,4,6,8,10];
var bigNumbers = evens.find(function (num) {
return num > 5;
});
// bigNumbers 6
var evens = [2,4,6,8,10];
var bigNumbers = evens.filter(function(num) {
return num > 5;
});
// bigNumbers 2
var fruit = ['cherries', 'apples', 'bananas'];
fruit.sort(); // ['apples', 'bananas', 'cherries']
var scores = [1, 10, 21, 2];
scores.sort(); // [1, 10, 2, 21]
// Note that 10 comes before 2,
// because '10' comes before '2' in Unicode code point order.
A custom sort method is passed the current and next items:
var nums = [3,1,2];
nums.sort(function compareNumbers(current, next) {
return current - next;
});
// [1,2,3]
var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt); // Math.sqrt is an existing function
// roots is now [1, 2, 3]
// numbers is still [1, 4, 9]
Just a quick point about the second line: You have to pass map() (and other functions we've discussed) a function to run against each item to create the new array. What I've done there is pass the sqrt function from the Math object. As we'll see later, if you give the name of a function and don't execute it with () then it just passes the function.
By James Sherry
Datatypes, Variables & Operators in JavaScript