-
Notifications
You must be signed in to change notification settings - Fork 18
Javascript Basics
This text is adapted from the Javascript Basics by Lauren McCarthy from the p5.js documentation.
JavaScript is a scripting language that is typically used on web pages where it runs client-side (within the web browser). It is a general purpose language with a lot of built-in functionality for interacting with elements on a webpage and responding to actions initiated by the user.
In the past few years, a version of Javascript has been developed that can run on the server side. The frontrunner in this movement to server-side javascript so far has been a technology called Node.js.
Although the JavaScript has "Java" in it's name, it isn't related other than by the fact that it looks something like Java. JavaScript's official name is ECMAScript (ECMA is the European Computer Manufacturers Association, a standards body). It was initially created by Netscape Communications. (Wikipedia: JavaScript)
One of the first things we probably want to learn is how to get debugging output. You can write to the console by using the built-in console.log method:
console.log("hello");
When working in Node, the console output appears in the terminal window where you are running your node script.
A variable stores a value in memory so that it can be used later in a program. The variable can be used many times within a single program, and the value is easily changed while the program is running.
The primary reason we use variables is to avoid repeating ourselves in the code. If you are typing the same number more than once, consider making it into a variable to make your code more general and easier to update.
JavaScript is a "loosely typed" or "dynamic" language, meaning you don't have to declare the types of variables ahead of time. ** This is different from Processing, where you always have to decide if a variable will be a string, int, etc. the moment you create it. ** Javascript is much more forgiving: the type will get determined automatically while the program is being processed. Even though you don't have to declare types, JavaScript does have different data types.
A number with a decimal point. In other languages this is typically called a float. It can be written with or without the decimal point, the processor will interpret it as a floating point number.
var x = 5;
var y = 1.223;
var z = -300;
A series of characters. These can be defined with either single or double quotes.
var x = 'hello';
var y = "maybe tomorrow";
There are a number of built-in JavaScript properties and methods that let you manipulate strings. You can see them all here, a few of the most common follow.
length
Gives the length of the string.
var str = "I like to eat pickles."
console.log(str.length); // 22
indexOf(str)
Returns the index of (the position of) the first occurrence of a specified text in a string. Returns -1 if the search string is not found.
var str = "I like to eat apples.";
var pos = str.indexOf("eat");
console.log(pos); // 10
pos = str.indexOf("pears");
console.log(pos); // -1
substring(start, end)
Extracts a part of a string and returns the extracted part in a new string. The method takes 2 parameters: the starting index, and the ending index.
var str = "I like to eat apples.";
var newStr = str.substring(2, 6);
console.log(newStr); // "like"
toLowerCase(), toUpperCase()
These functions convert the string to all lower or all upper case.
var str = "I like to eat apples.";
var lowerStr = str.toLowerCase();
console.log(lowerStr); // "i like to eat apples."
var upperStr = str.toUpperCase();
console.log(upperStr); // "I LIKE TO EAT APPLES."
A "true" or "false" value. Boolean variables are often used for conditional testing and keeping track of state.
var n = false;
var m = true;
An object can be thought of as a collection of properties. These properties can be values of any type, including other objects, which enables building complex data structures. Arrays are a special type of object, more on this later.
The value of a variable with no value is undefined. Variables can be emptied by setting the value to null.
var cars; // value is undefined
var person = null; // value is null
Once variables are declared, you are free to assign values to them and subsequently use them in operations.
var x = 5;
x = 5 + 5;
x = "cat";
var y = 5.5;
y = x;
=
-
+
addition -
-
subtraction -
*
multiplication -
/
division -
%
modulo -
++
add one shorthand -
--
subtract one shorthand
-
>=
greater than or equal to -
<=
less than or equal to -
==
equality -
!=
inequality -
===
equality with type checking -
!==
inequality with type checking
-
||
logical OR -
&&
logical AND -
!
logical NOT
Conditionals allow your program to execute a block of code based on the result of an expression that utilizes relational or logical (boolean) operators.
if
var x = 1;
if (x > 0) {
// execute some code
}
if, else
var x = 1;
if (x > 0) {
// execute some code
} else {
// execute some other code
}
if, else if, else
var x = 1;
if (x > 5) {
// execute some code
} else if (x < -5) {
// execute some other code
} else {
// execute some other other code
}
multiple conditions
var x = 1;
if (x > -5 && x < 5) {
// execute some code!
}
var x = "puddings";
if (x.length === 8 || x.indexOf("ding") === -1) {
// execute some code!
}
Just as with our conditional (if / else) statements a while loop employs boolean test that must evaluate to true in order for the instructions enclosed in the curly brackets to be executed. The difference is that the instructions continue to be executed until the test condition becomes false.
var x = 0;
while (x < 10) {
console.log(x);
x++;
}
Since this is a common use of a loop (creating a variable, checking it's value and incrementing by a certain amount) there exists an even quicker way to do the above, all in one step. You can read this as, create variable x and set it to 0, while x is less than 10, do the following. Increment x by 1 at the end.
for (var x = 0; x < 10; x++) {
console.log(x);
}
A function is a block of reusable code. It is useful because you can reuse it, executing it many times. Functions also help structure and organize your code.
To create a function, you write the word function
followed by the function name, a set of parentheses, and a set of curly braces. Within the curly braces is the code that will be executed when the function is run.
function sayHello() {
console.log("hello");
}
sayHello(); // call the function
A function can also accept values as input, known as arguments or parameters. In this case, the parameters (names representing the values) are listed inside the parentheses of the function, separated by commas. Note that these parameters are not the names of actual variables in your program, but are variables limited to the scope of the function. When a function is run, the values passed in are temporarily assigned to the parameter defined in the function, until the function completes its execution.
function sayHello(person) {
console.log("hello "+person);
}
sayHello("jenny");
function addNumbers(a, b) {
var c = a + b;
console.log(c);
}
addNumbers(3, -10);
The functions above take some action or change the state of the program, but they don't return any value. If you want your function return a value, include a line starting with return
followed by the value to return as the last line in your function.
function addNumbers(a, b) {
var c = a + b;
return c;
}
var result = addNumbers(3, -10);
console.log(result); // -7
var name = "jenny";
function makeSuper(person) {
return "super "+person;
}
var name = makeSuper(name);
console.log(name); // "super jenny"
Variables that you declare inside a function are local to that function. Variables declared outside of any function are known as "global variables" and can be accessed from anywhere in the program.
If I have a function called countThings and inside countThings I declare a variable called "counter", I can not refer to counter outside of the function. In the case that I want to use the value of counter outside of the function, I either have to declare it outside of the function or have the function return its value.
var xGlobal = "global";
function globalLocalTest() {
var xLocal = "local";
console.log("inside function global: " + xGlobal);
console.log("inside function local: " + xLocal);
}
globalLocalTest();
console.log("outside function global: " + xGlobal);
console.log("outside function local: " + xLocal);
Be careful about reinitializing an existing global variable. You will not see any error, but it could end up confusing things.
var a = 10;
function doStuff() {
var a = "cats"; // ok, but don't!
console.log(a);
}
console.log(a);
Arrays are used to store multiple objects or values in one variable. To create an array, use square brackets, and place any number of items separated by commas in between.
var arr = []; // empty array
var fruits = ["apple", "dragonfruit", "banana", "starfruit"];
var ages = [10, 21, 89, 3, 68];
var misc = ["pumpkin", 10.4, "dog", false, -1]; // arrays can have items of different datatypes
var more_misc = ["dustpan", "k", fruits, misc]; // arrays can contain other arrays
You can place or access items in the array by index, the first item in an array has index 0.
var arr = [];
arr[0] = "moss";
arr[1] = "sludge";
arr[2] = "mold";
console.log(arr); // ["moss", "sludge", "mold"]
console.log(arr[1]); // "sludge"
You can use a for loop to iterate over an array.
var arr = ["mushrooms", "cheerios", "sparkling water"];
for (var i=0; i<3; i++) {
arr[i] = "I love "+arr[i];
}
console.log(arr); // ["I love mushrooms", "I love cheerios", "I love sparking water"]
Like strings, arrays have some built-in convenience properties and methods. You can see them all in the MDN array reference, a few of the common ones follow.
length
Gives the length (number of items) of the array. This can be useful for iterating over arrays.
var arr = [3, 5, 19];
for (var i=0; i<arr.length; i++) {
arr[i] *= 2;
}
console.log(arr.length); // 3
console.log(arr); // [6, 10, 38]
push()
Adds (pushes) a new element to the end of the array, increasing the length of the array by 1.
var arr = [30, 10, 0];
arr.push(true);
console.log(arr.length); // 4
console.log(arr); // [30, 10, 0, true]
indexOf(elt)
Returns the index of given element, or returns -1 if it's not found.
var array = [2, 5, 9];
var index = array.indexOf(2); // 0
index = array.indexOf(7); // -1
index = array.indexOf(9, 2); // 2
index = array.indexOf(2, -1); // -1
index = array.indexOf(2, -3); // 0
Objects in Javascript can get rather complex -- there are many different ways they can be used. To start, let's look at them as a data structure, like a more sophisticated version of an array.
Like an array, an object can hold multiple pieces of data, but whereas an array uses index numbers to identify the the pieces of data, an object can use strings as names, called properties.
An object is often indicated by curly brackets. An empty object assigned to a variable would look like:
var myCat = {};
An object with some properties would look like:
var myCat = {
name: 'Hildegarde',
age: 10,
color: 'black'
};
You can then add or change properties of the object once it is defined:
myCat.mood = 'grumpy';
myCat.age = 11;
You can also access the properties, if for instance you wanted to display the name in the console:
console.log(myCat.name);
Using console.log, you can also see the whole object at once:
console.log(myCat); // outputs {name: "Hildegarde", age: 11, color: "black", mood: "grumpy"}
While properties are like variables within an object, methods are like functions within an object. They are set and accessed in much the same way.
var myCat = {
name: 'Hildegarde',
age: 10,
color: 'black',
noise: function(){
console.log("MEOW!!!");
}
};
Notice that instead of a number or string, the property noise
is a function. It looks a lot like a regular function definition you may be used to seeing. Something like:
function doSomething() {
console.log("I'm doing something!");
}
However, it's important to know that in general (whether within an object or not) a function can also be assigned to a variable. So the function above could be rewritten like this:
var doSomething = function() {
console.log("I'm doing something!");
};
Within the context of an Object, a function (technically called a method when it's inside an object), can be called like so:
myCat.noise(); //outputs "MEOW!!!"
It is a good idea to add comments to your code so you can remember what you're doing and debug when things go wrong. Commenting can also be useful for quickly removing or adding back in chunks of code (safer than deleting the chunk). Comments in JavaScript are similar to comments in Java or C.
// single line comment
/*
multiple
line
comment
*/
Whenever you introduce curly braces, you should indent everything inside. You can use two spaces or four, but be consistent. This will help you make sense of your code later.
function doStuff(x) {
if (x > 0) {
console.log("x is greater than 0");
} else {
console.log("x is not greater than 0");
}
}
A code statement generally ends with a semicolon.
var x = 10;
However, you may hear that semicolons are optional in JavaScript. This is sort of true. You can read more here, but my general recommendation is to use semicolons to avoid confusion.