To use this website fully, you first need to accept the use of cookies. By agreeing to the use of cookies you consent to the use of functional cookies. For more information read this page.

JavaScript refresher

This article in this tutorial will discuss the basics of JavaScript. For a more in-depth understanding of JavaScript, check out the JavaScript tutorial on this website.

Console output

This tutorial will rely on the command console for certain tasks. To do this, the console.log function is used:

JavaScript
console.log("Output");

Declaring a variable

One of the key concepts of any programming language is that of variables.

Variables are instantiated with an initial value or instantiated without a value. They can then be assigned a value at a later stage or the value stored can be retrieved.

JavaScript
var number = 50;
console.log(number);

Functions

JavaScript allows the declaration of functions. Functions are a way of writing code that can be used over and over again in a small block. This means that the file is smaller (as opposed to writing it over and over again) thus keeping down the download size.

Functions also support returning a value. This makes it more like a mathematical function where it takes an input, processes it and returns an output.

JavaScript
function writeNumber (number){
  console.log(number);
}

The above function named writeNumber takes a single parameter called number and calls the console.log function to output the content to the log.

This function does not return anything, so it returns undefined.

If a function is set to return something, it's value comes back:

JavaScript
function writeStringToUpper (str){
  return str.toUpperCase();
}
var x = writeStringToUpper("hello world");
console.log(x);

Chaining

Chaining is a method of combining multiple outputs to make one output. It is achieved with functions.

Assume the above code is used again:

JavaScript
function writeStringToUpper (str){
  return str.toUpperCase();
}
var x = writeStringToUpper("hello world").replace("O", "S");
console.log(x);

Notice at the end of the 4th line the replace function is chained to the end of the output. This means that the output from writeStringToUpper is then put through as the input to the replace function before x being set to the output.

Chaining is important in jQuery because almost all jQuery functions return a jQuery object.

Anonymous functions

Anonymous functions are functions without a name.

JavaScript
var f = function (x, y) {
  return 5 + x * y;
}
console.log(f(function(){ return 10; }, 2));
		

This example will use an anonymous function to return the value 10 as a parameter to another function. There is more on this in the JavaScript tutorial on this website.

Feedback
Comments are sent via email to me.