Javascript Reference

Contents


Types:

Primitives numbers, strings, booleans, undefined, null
Truthy/Falsy All the following values are evaluated as false :
  • false
  • undefined
  • null
  • 0
  • NaN
  • the empty string ''
Everything else is evaluated as true
null 
undefined
null (no object) v undefined value (absence of value)
Objects (not primitive) e.g       {name:'John', age: 34}       [1,2,3,4]   

   Stuff to do on types:

Properties e.g. 'john'.length
Built-in Methods console.log('Hello'.toUpperCase()); // 'HELLO'
console.log('Hey'.startsWith('H')); // true
---String Methods


Libararies e.g Math
console.log(Math.random()); // random number between 0 and 1
Math.floor(Math.random() * 50);
----Math

 

    Operators:

Arithmetic +    -    *    /    %    --   ++
Assignment =    +=    -+    *=    /=     %=


var x = 5;
var y = 5;
var z = 5;
console.log(x++);
console.log(x)
console.log(++y);
console.log(z+=1);
Comparison ==   ===   !=  !==   >   <    >=   <=     ? (ternary)
Logical
&&      ||        !
Type
  • instanceof  (works for objects, but not primitives)
  • typeof (works for primitives)      

   String methods:

length
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
index str.indexOf("locate");
str.lastIndexOf("locate");
str.indexOf("locate",15);   //starting position
str.search("locate") //search can take regex values
interpolation (ES6 +)  let myPet = 'armadillo'
console.log(`I own a pet ${myPet}.`)
 //note quotes in this case aren't ' ', but ` ` (backticks)
Slicing/replacing str.slice(7, 13);  str.slice(-12);
str.substring(7, 13);
str.substr(7, 6);         //2nd parameter is length of extraction

str.replace ("old", "new")

str.replace(/MICROSOFT/i, "W3Schools");  //regular expression with i for making case-insensitive

str.replace(/Microsoft/g, "W3Schools"); //To replace all matches, use a regular expression with a /g flag (global match)

Case txt.toUpperCase()
txt.toLowerCase()
Concat text1.concat(" ", text2);
"Hello" + " " + "World!"
str.charAt(0);
str.charCodeAt(0); 
Split
var txt = "a,b,c,d,e";   // String
txt.split(",");          // Split on commas
txt.split(" ");          // Split on spaces
txt.split("|");          // Split on pipe
Converting String to number

Converting number to string

"1"*1


1 + ""

    Variables:

Syntax
  • The first letter of a variable can only be "$", "_", "a" to "z", or "A" to "Z".
  • Use "camel" convention (e.g. carName)
  • For constants use caps (e.g. HEIGHT)
var x = 2, y = 5;
constant height = 100

Scope
  • 'Local' (within function), and 'Global' (anywhere in program) [E6 added 'block' scope]
  • 'let' can be used to limit scope to block of code in a function
  • Javascript doesn't require declaration, but best practice is to declare variables as intended
  • Scope examples can be found here




Conditionals, loops, and iterators:

Conditional if (expression) { ... }
else if (expression) { ... }
else { ... };

Ternary operator (if shorthand) (expression)? ... : ...;

isNightTime ? console.log('turn on') : console.log('Turn off ');

//inside a function
function f (n,m) {
return (n>m? true:false)
}
Cases
with no 'break(s)', code will continue executing in sequence
switch(expression) {
    case VALUE1 : ...;
        break;  
    case VALUE2 : ...;
        break;
    default: ...;}
While loop
[initialization]
while([condition]) {...}
e.g.
var n = 1;
while (n < 4) {
    console.log("n = " + n)
    n += 1; }
console.log ("done")


let cards = ['Diamond', 'Spade', 'Heart', 'Club'];
let currentCard = 'Heart';
while (currentCard !== 'Spade') {
  console.log(currentCard);
  currentCard = cards[Math.floor(Math.random() * 4)];
}

while loop with prompt entry

Do... while loop

The do-while statement executes the content of the loop once before checking the condition of the while, whereas a while statement will check the condition first before executing the content.

[initialization]
do {...} while([condition]);
e.g.
var i = 0;
do {
    console.log(i);
    i++;
    }
while(i < 5);
console.log('Done');
For Loops
for ([initialization]; [condition]; [step]) {...}
e.g.
for(var i=0; i < 5; i+=2)
  {console.log(i)}
 
//Double loop
var a = [
 [1,2], // line 1
 [3,4], // line 2
 [5,6]]  // line 3;
for (var i=0; i < a.length; i++) {
 // a[i] = line i The next loop iterates on the elements
 // of the array a[i]: on the elements of the ith line
 for (var j=0; j < a[i].length; j++) {
   console.log(a[i][j]);
 }
}

//Loop in an array
var daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
for(var i=0; i < daysOfWeek.length; i++) {
  console.log(daysOfWeek[i]);
}
for in 
for ( var V in expression ) {... V}
var michel = {             
    familyName:'Buffa',
    givenName: 'Michel',
    age: 51}
for(var property in michel) {
    console.log(property);
console.log(michel[property]);}


var fruits =      ['apple','banana','grape']
for(var i in fruits)    {console.log (fruits[i])}

forEach
[..array..].forEach(function(i){...})
OR
[..array..].forEach(i => ..i)
e.g
[1,2,3].forEach(function(i){console.log(i);})
shortform:
groceries
.forEach(groceryItem => console.log(' - ' + groceryItem));

Note: returns undefined; original array won't change

map
let [...new Array]  = [..array..].map(function(i){return..i})
OR
let [...new Array]  =
[..array..].map(i => ..i )

e.g
let numbers = [1, 2, 3, 4, 5]; 
let bigNumbers = numbers.map(function(number) {
return number * 10;});

shortform:
let numbers = [1, 2, 3, 4, 5];
let bigNumbers = numbers.map(numbers => numbers * 10);


Note: returns new array

filter let [...new Array]  = [..array..].filter(function(i)
  {
return...condition...i })
OR
let [...new Array]  =
[..array..].filter (i => condition...i )
let shortWords = words.filter(function(word) {
return word.length < 6;
});


let shortWords = words.filter(word => word.length < 6);
More on Additional iterator methods such as .some(), .every(), .reduce() ... There are many additional built-in array methods, a complete list of which is on the Mozilla Developer Network.
A list of iterator methods can be found here. 

Functions:

Function arguments
               
                              function f() {...}  //basic form
                              e.g.  
                              function f(s) { 
                              return s*2; 
                            } 


                            const square = function (number) { //function expression syntax 
                            return number * number; 
                          }; 
                          var today = function today() {return new Date()}  // Named function expression (NFE)


                          const f = () => { ... }  // arrow function syntax 
                          e.g.
                          const getSubTotal = (itemCount, PRICE) => { 
                          return (itemCount*PRICE) 
                        } 

                        const f = .. => ..  // concise arrow function syntax (one paramater only)
                        const f = () =>     // arrow function syntax with implied return
                        e.g.
                        const f = x => x*7
                        const h = (x,y) =>  x*y
                      } 


                      Functions can also take default arguments 

                      There are important differences between function expressions and declarations (e.g. expressions don't get hoisted; functions can't be defined within non-function blocks)
                    
Function with variable number of arguments function newSum() {
    var i, res = 0;
    var numberOfParameters = arguments.length;
    for (i = 0; i < numberOfParameters; i++) {
       res += arguments[i];
    }
    return res;
}
newSum(1, 2, 3, 4);  ->  10
Comparison ==   ===   !=  !==   >   <    >=   <=     ? (ternary)
Logical
&&      ||        !
Type
  • instanceof  (works for objects, but not primitives)
  • typeof (works for primitives)      
  • {}.toString
Filter function function isOdd (n){
  return (n % 2 !== 0)
}
function upToNF (n, filter) {
  for (var i=0; i <= n; i++)
    if (filter(i)) {console.log(i)}
}
upToNF (15,isOdd)
Nested Functions function hypotenuse(a,b) {
  function square(x){return x*x;}
  return (Math.sqrt(square(a)+square(b)))
}
console.log(hypotenuse(3,4))


function outer(n){
  return function inner(m){
    return n*m;
  }
}

function main(n,m){
  return (outer(n)(m))*3
}

function outside(x,y,z) {
  return (main(x,y)*z)
}

    Objects:

Objects
can hold any kind of data type, like strings, numbers, booleans, arrays, and even functions

objects are mutable
        var person = {
        firstName:"John",
        lastName:"Doe",
        age:50,
        eyeColor:"blue"
      };

      person['firstName']; //differences in the notations
      person.firstName

      Namespacing
      e.g. two different methods with same name in different object (or 'namespace')
    
Manipulate Objects how to create object (three ways)
      car = {};
      car = new Object();
      car = Object.create(null);
how to add/change/delete property
      book.title = 'Shane'  //add or change
      delete book.title    //delete
looping
      for (var p in book) {}
Methods (functions) in objects




note on 'this':
'this helps us with scope inside of object methods. this is a dynamic variable that can change depending on the object that is calling the method.'
var person = {
    firstName: "John",
    lastName : "Doe",
    id       : 5566,
    fullName : function() {
       return this.firstName + " " + this.lastName;  // Method
    },
    sayHello: function() {
    return `Hello, my name is ${this.name}`;
             },        //with 'this'keyword

    sayGoodbye() {  // new E6 syntax, removes : and 'function' kw
    return "Goodbye!"}
   };


objects with functions (JP Django course)
Another object can access methods from an object friend.sayHello = person.sayHello  // from the method in object example above
Accessing person.lastName;  or person["lastName"];    //bracket notation required to use variables to look up keys

To view entire object in a browser: console.dir(OBJECT)
Setters and Getters let person = {
  _name: 'Lu Xun',
  _age: 137,
  set age(n){
    if (typeof n === 'number') {this._age = n }    
        else { return 'Invalid input' };  
//setter
  }
};

person.age = 3  //this is way to reset age with 'setter', as opposed to directly like person._age=3

get age() {
    return this._age;
}   //getter
console.log(person.age) //uses getter to print age, as opposed to directly like console.log (person._age)

Built-in objects window
navigator
document
..others
Arrays var gradesInMaths = [12, 7, 14, 18, 9, 11];
var daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
daysOfWeek[2]  ->  "Wednesday"
daysOfWeek[daysOfWeek.length-1])   -> "Sunday"
var gradesInMaths = [12, 7, , undefined, 14, 18, 9, 11];   //sparse

To add an element:   daysOfWeek[daysOfWeek.length] = "extra";
Push method to add:   daysOfWeek.push('Sunday');


Array Methods
      var myarray = [];  // will create empty array
      a[20] = 'x' //will create 19 'undefined' slots
      a.length = 1 // will only leave item at spot 0.
      for (var i=0; i<myarray.length; i++) { ... }
      for (var i in myarray) { ... }  // not recommended
      for (var i in myarray) {if(myarray.hasOwnProperty(i)) { ... } }
      delete myarray[1] // deletes item at index 1, but length doesn't shrink

      a.concat(b,c) //leaves original arrays unchanged
      a.push (7)  //add at end; can be more than one
      a.unshift(9)  // add at beginning
      a.pop();  //remove at end, and returns
      a.shift(); //remove at beginning, and returns
      a.join(SEPARATOR)   //get string
      a.slice(1,4)  // start and end; doesn't affect original array; can be used to duplicate e.g. a.slice()

      var array = [1, 2, 3, 4, 5, 8, 6, 7, 8, 9, 0];  //filter
      let newArray = array.filter(function(item) {
      return item !==8;}); 

      var array = [1, 2, 3, 4, 7, 7, 5, 8, 6, 7, 8, 9, 0];  //concise form of filter
      let newArray = array.filter(item => item !==7); 

      a.indexOf('item') // returns -1 if not in array

      a.splice(2,5, 'a','ab')  //start, how many to delete, and what to replace; changes the original array; returns items; can be used to delete element without creating undefined slot

      a.sort()
      function comparator (a,b) {return (a-b)}  // need this sort of comparator function for numerical sorting
      a.sort(num_comparator)  // function object passed

      a instanceof  object;

    


Classes:

Constructor class C..  {
  constructor (X,...) {
     this._X = X;
     this.... = ...;
     this.attribute = ...;
    }}

const c = new C..(x,...)

class Dog {
constructor(name) {
this.name = name;
this.behavior = 0;
}
}

const halley = new Dog('Halley')
Getter get x() {return this._...}




to call getters, don't need ()
see example  ->
get behavior() {
return this._behavior;
}



console.log(bryceCat.behavior);
nurseOlynyk.addCertification('Genetics');
Method ...(...) {...}





to call methods need ()
see example  ->
incrementBehavior() {
this._behavior++;
}

takeVacationDays (daysOff){
this._remainingVacationDays -= daysOff
}

bryceCat.incrementBehavior()
Inheritance class D.. extends C.. {
  constructor (X,Y,..) {
     super(X);
     this._Y = Y
     this.attribute = ...; }} //super automatically inherited
const d = new D..(x,y...)

// When we call extends in a class declaration, all of the parent methods are available to the child class.


Class Nurse extends HospitalEmployee {
constructor (name,certifications) {
super(name);
this._certifications = certifications;
}

}

const nurseOlynyk = new Nurse ('Olynyk', ['Trauma', 'Pediatrics'])

Static Methods (available to class but not instances) static ...(...) {return ...}  static generatePassword()
  {
     return Math.floor(Math.random()*10000);
  }


Two ways to place script code:

Place in body or head <p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
Place in external file <p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<script src="https://www.w3schools.com/js/myScript.js"></script>


   Ways to output:

Use innerHTML //Example 1  (note that HTML element has to be above script, if used this way)
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>


//Example 2 
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =Date();
</script>
Docwrite

Notes:
1. Using document.write() after an HTML document is fully loaded, will delete all existing HTML
2.
The document.write() method should only be used for testing.
<script>
document.write(5 + 6);
</script>
Alert (and window.prompt) <script>
window.alert(5 + 6);
</script>
Console

Note: Console log is a good way to test code
<script>
console.log(5 + 6);
</script>
Text-formatting and String Substitution e.g.
console.log(`JavaScript first appeared ${a+b} years ago. Crazy!`);

Exporting/Importing:

exporting
let Menu = {};
Menu.specialty = "Roasted Beet Burger with Mint Sauce";
module.exports = Menu;


let Menu = {};
module.exports = {
specialty: "Roasted Beet Burger with Mint Sauce",
getSpecialty: function() {
return this.specialty;
}
};

Export default (ES6)


The default export syntax works similarly to the module.exports syntax, allowing us to export one module per file.


Can also do 'named export'
let Menu = {};
export default Menu;


let Airplane = {}
Airplane.availableAirplanes = [
{
name: 'AeroJet',
fuelCapacity: 800
},
{
name: "SkyJet",
fuelCapacity: 500
}
];
export default Airplane;
importing const Menu = require('./menu.js');
function placeOrder() {
  console.log('My order is: ' + Menu.specialty);
}
placeOrder();

const Menu = require('./menu.js');
console.log(Menu.getSpecialty());
import (ES6)
import Menu from './menu';


import Airplane from './airplane';
function displayFuelCapacity() {
Airplane.availableAirplanes.forEach(function(element){
console.log(
`Fuel Capacity of ${element['name']} : ${element.fuelCapacity}`
)
})
}
displayFuelCapacity()




 DOM (document object model):

Getting Elements when there is 1
var myElement = document.getElementById("A1");



Getting elements when more than 1 or combination var x = document.getElementsByTagName("p");
document.getElementById("D2").innerHTML = x[0].innerHTML;

var x = document.getElementsByClassName("intro");

var x = document.querySelectorAll("p.intro");

var x = document.getElementById ("main");
var y = x.getElementsByTagName ("p");    
document.getElementById("D3").innerHTML = y[0].innerHTML;

Navigation tutorial

var myTitle = document.getElementById("demo").firstChild.nodeValue;
var myTitle = document.getElementById("demo").childNodes[0].nodeValue;
alert(document.body.innerHTML);
alert(document.documentElement.innerHTML);
document.getElementById("id01").nodeName

appendChild()
insertBefore()       reference

document.getElementById("div1").parent.removeChild(child);


Links Collection document.links.length;
document.links[0].href

//display all links in a document
Text = '';
for(var i=0; i < document.links.length; i+=1)
  {Text = Text + document.links[i].href +'<br />'};
document.getElementById('demo1').innerHTML=Text;


    Events:

Examples
onchange An HTML element has been changed   example
onclick The user clicks an HTML element

e.g.
<h1 onclick="changeText(this)">Click on this text!</h1>

<script>function changeText(id) {id.innerHTML = "Ooops!";}</script>
onmouseover The user moves the mouse over an HTML element
(e.g. <h1 onmouseover="this.innerHTML='Ooops!'">Click on this text!</h1>)
onmouseout The user moves the mouse away from an HTML element
<h1 onmouseout="this.innerHTML='Ooops!'"  >Click on this text!</h1>
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page  example
onmouseup
onmousedown
can be used together example   
How to use <!--changes button itself with 'this'-->
<button onclick="this.innerHTML=Date()">The time is?</button>  
  



//changes paragraph with id=demo with function (example 1)

<script>
function displayDate() {
    document.getElementById("demo").innerHTML = Date();
}
</script>
<button onclick="displayDate()">The time is?</button>
<p id="demo"></p>  

//changes paragraph with id=demo with function (example 2)
<p id="demo"></p>
<script>
function displayDate() {
    return Date();
}
</script>
<button onclick="document.getElementById('demo').innerHTML = displayDate()">The time is?</button>


Event Listeners Syntax: element.addEventListener(event, function, useCapture);

Reference


Browser Compatibility:

caniuse

Check to see backward compatibility
Transpilation With Babel

node package manager (npm)
in Bash:
npm install babel-cli
npm install babel-preset-env
npm run build
npm init

npm install babel-cli -D
npm install babel-preset-env -D

summary



Other topics:

TOP; HOME