JavaScript Basics: Difference between revisions
(24 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
== References == | |||
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference | |||
* https://github.com/mbeaudru/modern-js-cheatsheet | |||
== Link to external Javscript file == | == Link to external Javscript file == | ||
<source lang="html4strict"> | <source lang="html4strict"> | ||
<head> | <head> | ||
<title>Test</title> | |||
<meta http-equiv="content-type" content="text/html;charset=utf-8" /> | |||
<script src="spectra.js" type="text/javascript" ></script> | |||
</head> | </head> | ||
</source> | </source> | ||
Line 14: | Line 18: | ||
The following are considered false: <code>false</code>, <code>0</code>, <code>""</code>, <code>null</code>, <code>undefined</code>, <code>NaN</code>. | The following are considered false: <code>false</code>, <code>0</code>, <code>""</code>, <code>null</code>, <code>undefined</code>, <code>NaN</code>. | ||
<source lang="javascript"> | |||
5 + 5 // 10 | |||
5 + "5" // "55" | |||
5 + String(5) // "55" | |||
5 + Number("5") // 10 | |||
</source> | |||
== Operators == | |||
Use <code>==</code> to check for same value; use <code>===</code> to check whether two things represent the same object. | |||
<source lang="javascript"> | |||
var firstVal = 5; | |||
var secondVal = "5"; | |||
(firstVal == secondVal && firstVal !== secondVal) // true | |||
</source> | |||
== Control == | |||
<source lang="javascript"> | |||
if (name == "Adam") { | |||
console.log("Name is Adam"); | |||
} else if (name == "Jacqui") { | |||
console.log("Name is Jacqui"); | |||
} else { | |||
console.log("Name is neither Adam or Jacqui"); | |||
} | |||
switch (name) { | |||
case "Adam": | |||
console.log("Name is Adam"); | |||
break; | |||
case "Jacqui": | |||
console.log("Name is Jacqui"); | |||
break; | |||
default: | |||
console.log("Name is neither Adam or Jacqui"); | |||
break; | |||
} | |||
</source> | |||
== Strings == | |||
<source lang="javascript"> | |||
" Hello ".trim() // "Hello" | |||
"How are you?".split(" ") // ["How", "are", "you?"] | |||
"A B C".replace(/\s/g, '') // "ABC" (\s matches white space, g means global) | |||
"Animal".toLowerCase() // "animal" | |||
"abcdefg".substr(0, 5) // "abcde" | |||
"abcdefg".substr(5) // "fg" | |||
"abcdefg".substr(2, 3) // "cde" | |||
"abcdefg".substring(0, 5) // "abcde" | |||
"abcdefg".substring(5) // "fg" | |||
"abcdefg".substring(2, 3) // "c" | |||
"abcdefg".slice(0, 5) // "abcde" | |||
"abcdefg".slice(5) // "fg" | |||
"abcdefg".slice(2, 3) // "c" | |||
</source> | |||
== Arrays == | == Arrays == | ||
Arrays are special objects. | Arrays are special objects that get their methods from <code>Array.prototype</code>. | ||
< | <source lang="javascript"> | ||
var my_array = []; // make a new empty array | var my_array = []; // make a new empty array | ||
var my_array = [1, 4, 2]; | var my_array = [1, 4, 2]; | ||
my_array.forEach( function(element){ | my_array.forEach( function(element){ | ||
// do something with element | // do something with element | ||
} | }) | ||
my_array.filter(function(i){return i % 2 == 0}); // [4, 2] only keeps even numbers | my_array.filter(function(i){return i % 2 == 0}); // [4, 2] only keeps even numbers | ||
my_array.map(function(i){return i*i}); // [1, 16, 4] | my_array.map(function(i){return i*i}); // [1, 16, 4] | ||
my_array.reduce(function(total, currentValue, index, array){ return total += currentValue;}) | my_array.reduce(function(total, currentValue, index, array){ return total += currentValue;}) | ||
// 7 | // 7 | ||
my_array.concat([2]); // [1, 4, 2, 2] | |||
my_array.join('-'); // "1-4-2" | |||
== | var x = my_array.pop(); // x is 2, my_array is [1, 4] | ||
< | my_array.push(x); // my_array is [1, 4, 2] | ||
" | my_array.reverse(); // my_array is [2, 4, 1] | ||
</ | x = my_array.shift(); // x is 2, my_array is [4, 1] | ||
my_array.unshift(x); // my_array is [2, 4, 1] | |||
my_array = [1,2,3,4,5,6,7]; | |||
my_array.slice(2); // [3, 4, 5, 6, 7] | |||
my_array.slice(2, 4) // [3, 4] | |||
my_array.slice(2, -1); // [3, 4, 5, 6] | |||
x = my_array.splice(2, 2); // x is [3, 4], my_array is [1, 2, 5, 6, 7] | |||
my_array = [4, 2, 3, 1] | |||
my_array.sort(); // my_array is [1, 2, 3, 4] | |||
my_array.length; // 4 | |||
</source> | |||
Delete specific element from array | |||
<source lang="javascript"> | |||
var index = myArray.indexOf(element); | |||
if (index > -1){ | |||
myArray.splice(index, 1); | |||
} | |||
</source> | |||
== Objects == | == Objects == | ||
< | <source lang="javascript"> | ||
var new_object = {}; | var new_object = {}; // make a new empty object | ||
new_object.name = "Bill"; | new_object.name = "Bill"; // create a property | ||
new_object["name"] = "Bill"; | new_object["name"] = "Bill"; // same thing | ||
for (var key in my_object){ | for (var key in my_object){ // iterate over an object | ||
// do something with key | // do something with key | ||
// value is my_object[key] | // value is my_object[key] | ||
} | } | ||
</ | var has_name = ("name" in new_object) // true | ||
delete new_object.name // now it's gone | |||
</source> | |||
== Functions == | |||
Functions are special objects that get their methods from <code>Function.prototype</code>. Javascript doesn't care about function signatures, so each name must be unique. | |||
<source lang="javascript"> | |||
var adder = { | |||
x: 1, y: 2, | |||
add: function(){return this.x + this.y;} | |||
} | |||
adder.add() // 3 | |||
adder.add.apply({x:2, y:4}) // 6 | |||
addx10 = adder.add.bind({x:10, y:20}) | |||
addx10() // 30 | |||
</source> | |||
== Constructors == | == Constructors == | ||
< | <source lang="javascript"> | ||
function Fruit (theColor, theSweetness, theFruitName, theNativeToLand) { | function Fruit (theColor, theSweetness, theFruitName, theNativeToLand) { | ||
this.color = theColor; | this.color = theColor; | ||
Line 65: | Line 156: | ||
var mango = new Fruit ("Yellow", 8, "Mango", ["South America", "Central America", "West Africa"]); | var mango = new Fruit ("Yellow", 8, "Mango", ["South America", "Central America", "West Africa"]); | ||
</ | </source> | ||
== Counter Example == | == Counter Example == | ||
< | <source lang="javascript"> | ||
function Counter() { | function Counter() { | ||
this.things = {}; // name -> count | this.things = {}; // name -> count | ||
Line 97: | Line 179: | ||
var myCounter = new Counter(); | var myCounter = new Counter(); | ||
</ | </source> | ||
== Prototypes == | |||
Every object has a <code>prototype</code> property. This can be used to add attributes or methods after the constructor has been defined: | |||
<source lang="javascript"> | |||
Fruit.prototype.peeled = false; | |||
Fruit.prototype.peel = function() { | |||
this.peeled = true; | |||
} | |||
</source> | |||
== Closures == | |||
Offers a way to hide data inside an object: | |||
<source lang="javascript"> | |||
function createIncrementer(){ | |||
var i = 0; // i is not accessible outside | |||
return { | |||
increment: function(){ | |||
return ++i; | |||
} | |||
}; | |||
} | |||
obj = createIncrementer(); | |||
obj.increment(); obj.increment(); obj.increment(); // 1, 2, 3 | |||
</source> | |||
This is a useful way to create a singleton page controller object. | |||
== Exceptions == | |||
<source lang="javascript"> | |||
function noEven(num){ | |||
if (num % 2 == 0){ | |||
throw { | |||
code: 'even_number', | |||
message: 'This function cannot be called with even numbers' | |||
}; | |||
} | |||
} | |||
function passNumber(num){ | |||
try { | |||
noEven(num); | |||
} catch (e){ | |||
console.log(e.code+':'+e.message); | |||
noEven(num+1); | |||
} | |||
} | |||
</source> | |||
== Timing == | |||
<source lang="javascript"> | |||
setTimeout(someFunction, 1000); // someFunction will execute after 1 second | |||
setInterval(someFunction, 1000); // someFunction will execute every 1 second | |||
</source> |
Latest revision as of 21:14, 22 November 2019
References
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
- https://github.com/mbeaudru/modern-js-cheatsheet
Link to external Javscript file
<head>
<title>Test</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<script src="spectra.js" type="text/javascript" ></script>
</head>
Types
The built-in types are string
, number
, boolean
, null
, undefined
, object
.
Use typeof some_var
to get the type.
The following are considered false: false
, 0
, ""
, null
, undefined
, NaN
.
5 + 5 // 10
5 + "5" // "55"
5 + String(5) // "55"
5 + Number("5") // 10
Operators
Use ==
to check for same value; use ===
to check whether two things represent the same object.
var firstVal = 5;
var secondVal = "5";
(firstVal == secondVal && firstVal !== secondVal) // true
Control
if (name == "Adam") {
console.log("Name is Adam");
} else if (name == "Jacqui") {
console.log("Name is Jacqui");
} else {
console.log("Name is neither Adam or Jacqui");
}
switch (name) {
case "Adam":
console.log("Name is Adam");
break;
case "Jacqui":
console.log("Name is Jacqui");
break;
default:
console.log("Name is neither Adam or Jacqui");
break;
}
Strings
" Hello ".trim() // "Hello"
"How are you?".split(" ") // ["How", "are", "you?"]
"A B C".replace(/\s/g, '') // "ABC" (\s matches white space, g means global)
"Animal".toLowerCase() // "animal"
"abcdefg".substr(0, 5) // "abcde"
"abcdefg".substr(5) // "fg"
"abcdefg".substr(2, 3) // "cde"
"abcdefg".substring(0, 5) // "abcde"
"abcdefg".substring(5) // "fg"
"abcdefg".substring(2, 3) // "c"
"abcdefg".slice(0, 5) // "abcde"
"abcdefg".slice(5) // "fg"
"abcdefg".slice(2, 3) // "c"
Arrays
Arrays are special objects that get their methods from Array.prototype
.
var my_array = []; // make a new empty array
var my_array = [1, 4, 2];
my_array.forEach( function(element){
// do something with element
})
my_array.filter(function(i){return i % 2 == 0}); // [4, 2] only keeps even numbers
my_array.map(function(i){return i*i}); // [1, 16, 4]
my_array.reduce(function(total, currentValue, index, array){ return total += currentValue;})
// 7
my_array.concat([2]); // [1, 4, 2, 2]
my_array.join('-'); // "1-4-2"
var x = my_array.pop(); // x is 2, my_array is [1, 4]
my_array.push(x); // my_array is [1, 4, 2]
my_array.reverse(); // my_array is [2, 4, 1]
x = my_array.shift(); // x is 2, my_array is [4, 1]
my_array.unshift(x); // my_array is [2, 4, 1]
my_array = [1,2,3,4,5,6,7];
my_array.slice(2); // [3, 4, 5, 6, 7]
my_array.slice(2, 4) // [3, 4]
my_array.slice(2, -1); // [3, 4, 5, 6]
x = my_array.splice(2, 2); // x is [3, 4], my_array is [1, 2, 5, 6, 7]
my_array = [4, 2, 3, 1]
my_array.sort(); // my_array is [1, 2, 3, 4]
my_array.length; // 4
Delete specific element from array
var index = myArray.indexOf(element);
if (index > -1){
myArray.splice(index, 1);
}
Objects
var new_object = {}; // make a new empty object
new_object.name = "Bill"; // create a property
new_object["name"] = "Bill"; // same thing
for (var key in my_object){ // iterate over an object
// do something with key
// value is my_object[key]
}
var has_name = ("name" in new_object) // true
delete new_object.name // now it's gone
Functions
Functions are special objects that get their methods from Function.prototype
. Javascript doesn't care about function signatures, so each name must be unique.
var adder = {
x: 1, y: 2,
add: function(){return this.x + this.y;}
}
adder.add() // 3
adder.add.apply({x:2, y:4}) // 6
addx10 = adder.add.bind({x:10, y:20})
addx10() // 30
Constructors
function Fruit (theColor, theSweetness, theFruitName, theNativeToLand) {
this.color = theColor;
this.sweetness = theSweetness;
this.fruitName = theFruitName;
this.nativeToLand = theNativeToLand;
this.showName = function () {
console.log("This is a " + this.fruitName);
}
this.nativeTo = function () {
this.nativeToLand.forEach(function (eachCountry) {
console.log("Grown in:" + eachCountry);
});
}
}
var mango = new Fruit ("Yellow", 8, "Mango", ["South America", "Central America", "West Africa"]);
Counter Example
function Counter() {
this.things = {}; // name -> count
this.add = function (name){
if (name in this.things){
this.things[name]++;
} else {
this.things[name] = 1;
};
};
this.getCount = function(name){
if (name in this.things){
return this.things[name];
} else {
return 0;
};
};
};
var myCounter = new Counter();
Prototypes
Every object has a prototype
property. This can be used to add attributes or methods after the constructor has been defined:
Fruit.prototype.peeled = false;
Fruit.prototype.peel = function() {
this.peeled = true;
}
Closures
Offers a way to hide data inside an object:
function createIncrementer(){
var i = 0; // i is not accessible outside
return {
increment: function(){
return ++i;
}
};
}
obj = createIncrementer();
obj.increment(); obj.increment(); obj.increment(); // 1, 2, 3
This is a useful way to create a singleton page controller object.
Exceptions
function noEven(num){
if (num % 2 == 0){
throw {
code: 'even_number',
message: 'This function cannot be called with even numbers'
};
}
}
function passNumber(num){
try {
noEven(num);
} catch (e){
console.log(e.code+':'+e.message);
noEven(num+1);
}
}
Timing
setTimeout(someFunction, 1000); // someFunction will execute after 1 second
setInterval(someFunction, 1000); // someFunction will execute every 1 second