ckportfolio.com - Element of Programming with JavaScript

Element of Programming with JavaScript

Common Denominators in Programming Languages

Whether one decides to develop a web application or an iOS mobile app, one uses a programming language to do so. These languages, regardless of differences in their syntaxes or use cases, have many attributes in common:

  • Variables
  • Functions
  • Operators
  • Conditional Statements
  • Loops
  • Try and Catch

Originated from mathematical concepts, the above items are indispensable in today's programming projects.

General Notes

It should be noted that inefficient jQuery or JavaScript code can dramatically slow down the website, and that they should only be used to enhance the user experience. Also, jQuery is not a replacement for JavaScript, but a framework designed to make one's life easier with easily recognizable syntax. Finaly a couple of additional notes:

  • Semicolon separates JS statements
  • JS is case-sensitive
    • “slideUp” does not equal to “slideup”
  • JS ignores extra spaces
  • One can comment by using “//” or using “/” and “/”
    • For references or disabling JS statements

Variables

Variables allow the programmer to define a symbol to mean a specific number or alphanumeric phrase (also known as string). In short, it is just like defining xs and ys in algebra.

var x = 2;
var y = 5;
var z = x + y;
// z is 7

var m = 20;
var n = "5";
var o = m * n;
// o is 100

As the above, a variable can also be defined as a mathematical combination of other variables. Note that JavaScript intelligently parses a variable and determines whether it should be treated as a number or a string.

var a = "Welcome, ";
var b = "John Doe!";
var c = a + b;
// c is "Welcome, John Doe!"

One can also "add" two or more string variables together to concatenate text strings. Finally, note that variables can contain more than just numbers and strings:

  • Boolean: true or false
var x = true
  • Array: list of strings or numbers
var x = ['BMW', 'Volvo', 'Hyundai']
  • Objects: one objects with properties
var person = {name: 'John Doe', email: 'john@doe.com', phone: '6471234567'}
  • Undefined or null: no value assigned

Functions

When developing a more complex application, one can define a specific code block that can be called any time. Often called a function, this code block can be given a parameter ("input") to change its behaviour, and can also return a value ("output") at the end of its operation.

var greeting = "Welcome to my website";

function welcome() {
    alert(greeting);
}

$("#home").click(welcome);

Each function can use a predefined (global) variable that sits outside of its scope, as illustrated above. Variables created within the function (local variables), however, are not accessible anywhere else.

function sum(a, b) {
    var answer = a + b;
    alert("The result is "+ answer);
}

sum(5,7);

alert(answer);
// The above will fail, as "answer" is a local variable

Anonymous Functions

When creating jQuery events, JavaScript allows the programmer to directly define a function without assigning a name. Dubbed anonymous function, this method is a lightweight way to creating a function, but can be confusing due to excessive nesting.

$("#item2").click(
    function(){
        alert("clicked!");
    }
)

$("#item2").hover(
    function(){
        $("#hover").fadeIn();
    },
    function(){
        $("#hover").fadeOut();
    }    
)

When one notices redundancy in the code, it is best to define a proper, reusable function with a name.

$("#item1").click(
    function(){
        alert("clicked!");
    }
)

$("#item2").click(
    function(){
        alert("clicked!");
    }
)

$("#item3").click(
    function(){
        alert("clicked!");
    }
)

This can be optimized as the below:

function prompt(){
    alert("clicked!");
}

$("#item1, #item2, #item3").click();

Operators and Conditional Statements

As illustrated above, operators are designed to manipulate two or more numbers and strings. Using specialized operators such as ==, !=, < or >=, we can also compare variables in conditional statements. Using conditional statements, we can have the code behave differently under different circumstances.

var response = prompt("What’s 7 times 2?");
// prompt the user to answer a question

if (response == 14) { // if the response equals to 14
    alert("You are correct!");
} else if (response == 5) { // if the response equals to 5
    alert("Wrong. Perhaps you were trying to subtract 2 from 7?");
} else { // otherwise...
    alert("Wrong!");
}

Loops

Programming languages allow us to automate manual tasks, and creating a loop is the very first step in this process. The programmer can have a certain set of tasks to run for a finite number of times. This number is defined by a single number, or the array size.

var cars = ["BMW", "Volvo", "Saab"];
var text = "";

for (i = 0; i < cars.length; i++) {
    text += cars[i];
}

Try and Catch

In order to prevent the application from failing permanently without any visible feedback, the programmer can implement a try-and-catch in order to have the applcation "try" a piece of code and "catch" any potential errors without breaking the application.

try {
    alerttt("Hello world");
    // intentionally made spelling mistake
} catch(err) {
    alert("Your code has some issues: " + err);
    // code above will launch upon detecting issues
}
Fin