What is JavaScript?

JavaScript is used for programming the client-side of web pages. It is an object-oriented programming language, which means that it has class and inheritance structures. JavaScript is what controls forms and submit buttons on web features, along with all other interactive features.


Variables

JavaScript variables are containers for storing data values. In this example, x, y, and z, are variables:

var x = 5;
var y = 6;
var z = x + y;

From the example above, you can expect: x stores the value 5; y stores the value 6; z stores the value 11. In programming, just like in algebra, we use variables (like x) to hold values. In programming, just like in algebra, we use variables in expressions (z = x + y). From the example above, you can calculate the total to be 11.

All JavaScript variables must be identified with unique names. These unique names are called identifiers. Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

In JavaScript, the equal sign (=) is an "assignment" operator, not an "equal to" operator. This is different from algebra. The following does not make sense in algebra:

x = x + 5

In JavaScript, however, it makes perfect sense: it assigns the value of x + 5 to x. It calculates the value of x + 5 and puts the result into x. The value of x is incremented by 5.

JavaScript variables can hold numbers like 100 and text values like "John Doe". In programming, text values are called text strings. JavaScript can handle many types of data, but for now, just think of numbers and strings. Strings are written inside double or single quotes. Numbers are written without quotes. If you put a number in quotes, it will be treated as a text string.

var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';

Creating a variable in JavaScript is called "declaring" a variable. You declare a JavaScript variable with the var keyword:

var carName;

After the declaration, the variable has no value. To assign a value to the variable, use the equal sign:

carName = "Volvo";

You can also assign a value to the variable when you declare it:

var carName = "Volvo";

In the example below, we create a variable called carName and assign the value "Volvo" to it. Then we "output" the value inside an HTML paragraph with id="demo":

<p id="demo"></p>
<script>
  var carName = "Volvo";
  document.getElementById("demo").innerHTML = carName;
</script>


Data Types

JavaScript variables can hold many data types: numbers, strings, objects and more:

var length = 16; // Number
var lastName = "Johnson"; // String
var x = {firstName:"John", lastName:"Doe"}; // Object

In programming, data types is an important concept. To be able to operate on variables, it is important to know something about the type. Without data types, a computer cannot safely solve this:

var x = 16 + "Volvo";

Does it make any sense to add "Volvo" to sixteen? Will it produce an error or will it produce a result? JavaScript will treat the example above as:

var x = "16" + "Volvo";

A string (or a text string) is a series of characters like "John Doe". Strings are written with quotes. You can use single or double quotes:

var carName = "Volvo XC60"; // Using double quotes
var carName = 'Volvo XC60'; // Using single quotes

JavaScript has only one type of numbers. Numbers can be written with, or without decimals:

var x1 = 34.00; // Written with decimals
var x2 = 34; // Written without decimals

Booleans can only have two values: true or false.

var x = 5;
var y = 5;
var z = 6;
(x == y) // Returns true
(x == z) // Returns false

JavaScript arrays are written with square brackets. Array items are separated by commas. Array indexes are zero-based, which means the first item is [0], second is [1], and so on. The following code declares (creates) an array called cars, containing three items (car names):

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

JavaScript objects are written with curly braces. Object properties are written as name:value pairs, separated by commas. The object (person) in the example below has 4 properties: firstName, lastName, age, and eyeColor.

var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};


Methods

JavaScript methods are the actions that can be performed on objects. A JavaScript method is a property containing a function definition. In JavaScript, the thing called this, is the object that "owns" the JavaScript code. The value of this, when used in a function, is the object that "owns" the function.

You access an object method with the following syntax:

objectName.fmethodName()

This example uses the toUpperCase() method of the String object, to convert a text to uppercase:

var message = "Hello world!";
var x = message.toUpperCase();

Adding a new method to an object is easy:

person.name = function () {
  return this.firstName + " " + this.lastName;
};

The length property returns the length of a string:

var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length; // will return 26

The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string. The lastIndexOf() method returns the index of the last occurrence of a specified text in a string. Both methods accept a second parameter as the starting position for the search:

var str = "Please locate where 'locate' occurs!";
var foo = str.indexOf("locate");
var bar = str.lastIndexOf("locate", 15);

The search() method searches a string for a specified value and returns the position of the match:

var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate");

slice() extracts a part of a string and returns the extracted part in a new string. The method takes 2 parameters: the starting index (position), and the ending index (position). This example slices out a portion of a string from position 7 to position 13:

var str = "Apple, Banana, Kiwi";
var res = str.slice(7, 13);

The replace() method replaces a specified value with another value in a string. By default, the replace() function replaces only the first match. To replace all matches, use a regular expression with a /g flag (global match). By default, the replace() function is case sensitive. To replace case insensitive, use a regular expression with an /i flag (insensitive):

str = "Please visit Microsoft!";
var n = str.replace("Microsoft", "W3Schools");

A string is converted to upper case with toUpperCase(). A string is converted to lower case with toLowerCase().

var text1 = "Hello World!";
var text2 = text1.toUpperCase();
var text3 = text1.toLowerCase();

concat() joins two or more strings. The concat() method can be used instead of the plus operator.

var text1 = "Hello";
var text2 = "World";
var text3 = text1.concat(" ", text2);

The charAt() method returns the character at a specified index (position) in a string:

var str = "HELLO WORLD";
str.charAt(0); // returns H

toString() returns a number as a string. All number methods can be used on any type of numbers (literals, variables, or expressions):

var x = 123;
x.toString(); // returns 123 from variable x
(123).toString(); // returns 123 from literal 123
(100 + 23).toString(); // returns 123 from expression 100 + 23

toExponential() returns a string, with a number rounded and written using exponential notation. A parameter defines the number of characters behind the decimal point:

var x = 9.656;
x.toExponential(2); // returns 9.66e+0
x.toExponential(4); // returns 9.6560e+0
x.toExponential(6); // returns 9.656000e+0

Number() can be used to convert JavaScript variables to numbers:

x = true;
Number(x); // returns 1
x = false;
Number(x); // returns 0
x = new Date();
Number(x); // returns 1404568027739
x = "10"
Number(x); // returns 10
x = "10 20"
Number(x); // returns NaN

parseInt() parses a string and returns a whole number. Spaces are allowed. Only the first number is returned:

parseInt("10"); // returns 10
parseInt("10.33"); // returns 10
parseInt("10 20 30"); // returns 10
parseInt("10 years"); // returns 10
parseInt("years 10"); // returns NaN

parseFloat() parses a string and returns a number. Spaces are allowed. Only the first number is returned:

parseFloat("10"); // returns 10
parseFloat("10.33"); // returns 10.33
parseFloat("10 20 30"); // returns 10
parseFloat("10 years"); // returns 10
parseFloat("years 10"); // returns NaN

Date methods let you get and set date values (years, months, days, hours, minutes, seconds, milliseconds). setDate() lets you set the day as a number (1-31). setFullYear() lets you set the year (optionally month and day). setHours() lets you set the hour (0-23). setMilliseconds() lets you set the milliseconds (0-999). setMinutes() lets you set the minutes (0-59). setMonth() lets you set the month (0-11). setSeconds() lets you set the seconds (0-59). setTime() lets you set the time (milliseconds since January 1, 1970).

getDate() lets you get the day as a number (1-31). getDay() lets you get the weekday as a number (0-6). getFullYear() lets you get the four digit year (yyyy). getHours() lets you get the hour (0-23). getMilliseconds() lets you get the milliseconds (0-999). getMinutes() lets you get the minutes (0-59). getMonth() lets you get the month (0-11). getSeconds() lets you get the seconds (0-59). getTime() lets you get the time (milliseconds since January 1, 1970).

getTime() returns the number of milliseconds since January 1, 1970:

<script>
  var d = new Date();
  document.getElementById("demo").innerHTML = d.getTime();
</script>

getFullYear() returns the year of a date as a four digit number:

<script>
  var d = new Date();
  document.getElementById("demo").innerHTML = d.getFullYear();
</script>

The pop() method removes the last element from an array:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();

The push() method adds a new element to an array (at the end):

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push();

Shifting is equivalent to popping, working on the first element instead of the last. The shift() method removes the first array element and "shifts" all other elements to a lower index. The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements.

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift(); // Removes the first element "Banana" from fruits
fruits.unshift("Lemon"); // Adds a new element "Lemon" to fruits

Array elements are accessed using their index number. Array indexes start with 0. [0] is the first array element, [1] is the second, [2] is the third, etc. Since JavaScript arrays are objects, elements can be deleted by using the JavaScript operator delete:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0]; // Changes the first element in fruits to undefined

The splice() method can be used to add new items to an array:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");

The first parameter (2) defines the position where new elements should be added (spliced in). The second parameter (0) defines how many elements should be removed. The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added.

The concat() method creates a new array by merging (concatenating) existing arrays:

var myGirls = ["Cecilie", "Lone"];
var myBoys = ["Emil", "Tobias", "Linus"];
var myChildren = myGirls.concat(myBoys); // Concatenates myGirls and myBoys


Functions

A JavaScript function is a block of code designed to perform a particular task. A JavaScript function is executed when "something" invokes it (calls it).

function myFunction(p1, p2) {
  return p1 * p2; // The function returns the product of p1 and p2
}

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). Function names can contain letters, digits, underscores, and dollar signs (same rules as variables). The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...). The code to be executed, by the function, is placed inside curly brackets: {}. Accessing a function without () will return the function definition instead of the function result:

function name(parameter1, parameter2, parameter3) {
  code to be executed
}

Function parameters are listed inside the brackets () of the function definition. Function arguments are the values received by the function when it is invoked. Inside the function, the arguments (the parameters) behave as local variables.

When JavaScript reaches a return statement, the function will stop executing. If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement. Functions often compute a return value. The return value is "returned" back to the "caller":

var x = myFunction(4, 3); // Function is called, return value will end up in x
function myFunction(a, b) {
  return a * b; // Function returns the product of a and b
}

Functions can be used the same way as you use variables, in all types of formulas, assignments, and calculations.

var text = "The temperature is " + toCelsius(77) + " Celsius";


FAQ

Why is a semicolon necessary at the end of every line in JavaScript?

View the answer on StackOverflow.


Sources

Information for this documentation was sourced from W3Schools, StackOverflow, and the Mozilla MDN.