-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
JavaScript basics
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.
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. (Uncyclopedia: JavaScript)
JavaScript can be placed anywhere within an HTML document, although it is typically included in the "head" section of the HTML, and is specified by the use of <script>
tags:
<html>
<head>
<script type="text/javascript">
//JavaScript goes here
</script>
</head>
</html>
You can also write JavaScript in file external to the HTML and point to that file in a script tag.
<script type="text/javascript" src="myscript.js"></script>
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");
In order to see the console on Chrome, select "View" > "Developer" > "JavaScript Console". Use it often!
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. The type will get determined automatically while the program is being processed. Other languages such as Java are strictly typed and each variable must declare the type of the data it will contain. 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);
}
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 blah and inside blah 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 return it's 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);
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");
}
}
If you would like to edit this wiki and don't already have edit access, please open an issue or comment on an existing one noting the wiki page you'd like to edit. You will then be added as a repository contributor with edit access.