Site icon Tutorial

JavaScript

JavaScript is a programming language that allows you to implement complex things on web pages — every time a web page does more than just sit there and display static information for you to look at — displaying timely content updates, or interactive maps, or animated 2D/3D graphics, or scrolling video jukeboxes, etc. — you can bet that JavaScript is probably involved. It is the third layer of the layer cake of standard web technologies, two of which (HTML and CSS).

Why use JavaScript

Data Types

In JavaScript there are two different kinds of data: primitives, and objects. A primitive is simply a data type that is not an object, and has no methods.

In JS, there are six primitive data types: Boolean, Number, String, Null, Undefined, Symbol.

Boolean – A boolean represents only one of two values: true, or false. Think of a boolean as an on/off or a yes/no switch.

var boo1 = true;

var boo2 = false;

Number – There is only one type of Number in JavaScript. Numbers can be written with or without a decimal point. A number can also be +Infinity, -Infinity, and NaN (not a number).

var num1 = 32;

var num2 = +Infinity;

String – Strings are used for storing text. Strings must be inside of either double or single quotes. In JS, Strings are immutable (they cannot be changed).

var str1 = ‘hello, it is me’;

var str2 = “hello, it’s me”;

Null – Null has one value: null. It is explicitly nothing.

var nothing = null;

Undefined – A variable that has no value is undefined.

var testVar;

console.log(testVar); // undefined

Symbol – Symbols are new in ES6. A Symbol is an immutable primitive value that is unique. For the sake of brevity, that is the extent that this article will cover Symbols.

const mySymbol = Symbol(‘mySymbol’);

Objects – Objects are not a primitive data Type.

An object is a collection of properties. These properties are stored in key/value pairs. Properties can reference any type of data, including objects and/or primitive values.

var obj = {

key1: ‘value’,

key2: ‘value’,

key3: true,

key4: 32,

key5: {}

}

Loosely Typed – JavaScript is a loosely typed language. This means you don’t have to declare a variable’s type. JavaScript automatically determines it for you. It also means that a variables type can change. Let’s look at an example:

We’ll create a variable named car and set it equal to a string value: var car = ‘ford’;

Later, we realize we want the value of car to be the year it was made, so we change car to a number:

car = 1998;

It works — and JavaScript could care less. Because JS is loosely typed, we are free to change variable types as we please.

Using Variables, Objects and Arrays

var str = “Hello”;                // local variable, when inside a function

str2 = “Hello World”;             // global variable in default context (window.str2)

str3 = ‘My quote char: ” ‘;       // single or double quote

str4 = “My really really really \

really long string broken into \

multiple lines”;

str = 19;                         // change to int

str = 0xfe + 2.343 + 2.5e3;       // hex, floats, exp

var newObject = new Object();     // constructor

newObject = {};           // shorthand for same

newObject.name = “bob”            // dynamic attributes

newObject.name = null         // it’s there (null item)

delete newObject.name         // it’s gone (undefined)

newObject[“real age”] = 33;       // array notation/hash table

var obj = {           // create object using JSON

name: “Bob”,          //   aka JavaScript Object Notation

details: {

age: 33,

“favorite color”: “green”

}

}

obj.name

obj.details[“favorite color”]

var newArray = [];                // no size

newArray[3] = “hi”;               // grows dynamically

newArray[2] = 13;                 // any type

newArray.push(newObject);         // add new item

newArray.pop();               // remove it

Comparisons and Manipulations

JavaScript has some funky types and comparisons.

/* javascript types */

typeof(“string”) == “string”

typeof(3) == typeof(3.4) == typeof(0x34) == “number”

typeof(myObject) == typeof(myArray) == “object” // arrays are objects

typeof(true) == typeof(1 == 2) == “boolean”

typeof(Math.sin) == “function”

typeof(notthere) == “undefined”

/* comparisons */

123 == “123”                     // true => converts type

123 === “123”                    // false => checks type

typeof(x) == “undefined”     // x isn’t there

x == null            // x is defined, but null

/* Numbers */

parseInt(“123”)          // base 10 => 123

parseInt(“123”, 16);         // base 16 => 291

parseFloat(“123.43”);        // 123.43

isNaN(0/0) == true       // illegal number

3/0 == Infinity          // legal…

-3/0 == -Infinity        //

isFinite(3/0) == false       // … but not finite

/* regular expression (regex) string comparisons */

matches = “hello”.match(/h../)   // returns array [“hel”] or null

re = new RegExp(“h..”, “ig”);    // construct regexp — no slashes

matches = “hello”.match(re);     // use it

“hello”.replace(/h/,”b”)     // => “bello”

Conditionals and Loops

if (str == “Hello”){    // if-else

alert(“Hi”);      // popup dialog

}

else{

alert(“something is wrong!”);

}

a = 3, b = 4;       // multi-assigment

c = a > b ? a : b;  // c gets bigger item (b)

switch (name){      // switch statement

case “Bob”:

alert(“Hi Bob!”)

break

case “Joe”:

alert(“Hey Joe.”)

break

default: alert(“Do I know you?”)

}

while (i < n){          // the basics

// do something

i++;

}

for (var i=0; i<n; i++){

// do something else

}

for (var key in obj){

// do something with obj[key]

}

Defining Functions

function foo(a,b){          // global function

return a + b;

}

var fn = function(a,b){     // save function as variable…

return foo(a,b);

}

obj.fn = function(a,b){     // …or as part of object

return a + b;

}

function bar(a,b){

var n = 1;                  // local var

function helper(x) {            // inner function…

return 1/Math.sqrt(x + n);  // .. can use local vars

}

return helper(input);           // avoid need for global function

}

foo(1,2) == fn(1,2) == 3;   // true

Browser Document Object Model (DOM), and GUI

Find and change HTML elements.

alert(“message”);  // messagebox with “OK”

var choice = confirm(“message”);  // OK/CANCEL true or false

var input = prompt(“message”, “default value”); // enter a value; null if cancelled

x = document.getElementById(“foo”);    // finds <div id=”foo”></div>

x.style.background = “#333”;           // set CSS style

x.style.borderLeft = “1px solid #ccc”; // border-left => borderLeft (camelCase)

x.className = “myclass”;           // set CSS class

x.innerHTML = “Hello”;             // set html inside div

y = document.getElementById(“myinput”); // input area/textarea

y.value = “Hi”;                 // get or set text

 

Exit mobile version