Cookies help us deliver our services. By using our services, you agree to our use of cookies. More information

# JavaScript: Fundamentals

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

## Introduction to JavaScript

JavaScript is a high level interpretted scripting language originally created to enable interactivity in web pages.
Today, JavaScript has many other uses, one of which is powering the MongoDB interactive shell environment.
As such, to be able to query MongoDB effectively it is necessary to have a good knowledge of both JavaScript (js) and JavaScript Object Notation (JSON).

## The Basics

This tutorial will teach you the basic JavaScript skills you will need to tackle the harder MongoDB questions.
It is highly recommended that you are comfortable with JavaScript before attempting the MapReduce Tutorial.

### Operators

The following examples involve the use of operators.
Operators are symbols used to perform various data manipulations.
You can use this reference table to search any operator you are not familiar with already.

Arithmetic Operators
`+` addition
`-` subtraction
`*` multiplication
`/` division
`%` modulus (remainder)
Assignment Operators
`=` regular assignment
`+=` `a += b` is shorthand for `a = a + b`
`-=` `a -= b` is shorthand for `a = a - b`
`*=` `a *= b` is shorthand for `a = a * b`
`/=` `a /= b` is shorthand for `a = a / b`
`%=` `a %= b` is shorthand for `a = a % b`
`++` `a++` is shorthand for `a = a + 1`
`--` `a--` is shorthand for `a = a - 1`
Comparison Operators
`==` equal values
`===` equal values and equal types
`!=` different values
`!==` different values or different types
`>` greater than
`>=` greater than or equal to
`<` less than
`<=` less than or equal to
Logical Operators
`&&` and
`||` or
`!` not
The Ternary Operator
`a ? b : c` if a is true, then b, else c
Bitwise Operators
`&` and
`|` or
`~` not
`^` exclusive or (xor)
`<<` left shift
`>>` right shift

### Variables and Types

Variables are used to store values for later use. Each variable has a type which defines what kind of value can be stored, and what operations are allowed involving that variable. Javascript has seven types in total:

`Number`
Any number, such a `1`, `-3.4`, or `2E9`.
In JavaScript all numbers are stored in IEEE floating-point format.

```print(
1,
-2.3,
2E9,
1 - 2.3 + 2E9
);```

`String`
A string is a sequence of characters surrounded by quotation marks. e.g. "Bob", "Alice"
There are several methods availible to making working with strings easier that can be found here.

```print("string");
print("string with newline \n");
print("string".indexOf("n"));
print("string".replace("i", "o"));```

`Boolean`
A variable that can be either `true` or `false`.
Comparison and logical operators always return a boolean and can be used with an if statement to control program flow.

```print(true, false);

// or, and operators
print(true || false, true && false);

// not operator
print(!true, !false);

// if statements
if (3 > 2) {
print("Three is larger");
} else {
print("Two is larger");
}

// Simplifying if statements with ternary.
print((3 > 2 ? "Three" : "Two") + " is larger");```

`Symbol`
Symbols are used to create unique identifiers. You shouldn't have to use a symbol for any of the questions on this website.

`undefined`
A variable that has been declared, but that has had no value assigned to it.

`object`
Objects are collections of multiple variables (properties) and are used to represent complex data structures. For example, consider this object representing an employee:

```{
name: "Jill",
age: 22,
job: {
title: "Programmer",
location: "Edinburgh",
company: "Napier University"
}
}
```

Let's call this object x. By using either dot notation or bracket notation it is possible to get and set x's properties.

```print(x.name);                          // Returns: "Jill"
print(x.nam);                           // Returns: undefined
print(x['age']);                        // Returns: 22
x.job.title = "Database Administrator"; // Changes the title field of the job object inside the x object.
```

`null`
Technically not a separate type but a special kind of `object`that is used to represent assigned but 'empty' variables.

### Assignments, and scope

To define and assign variables either use the `var` or `let` keyword.

If declared outside of a function (discussed below) variables are global, i.e. they can can be accessed and edited from anywhere.
If used inside a function, `var` will use the scope of the entire function, whereas `let` variables will only affect the block in which they are defined.

To see this in action use the example below, which has been adapted from a Mozilla Developer Network example:

```var x = 1;   // declare a global variable, x
if (true) {
var x = 2; // same global variable, x
print(x);  // 2
}
print(x);    // 2

let y = 1;   // declare a global variable, y
if (true) {
let y = 2; // different local variable, y
print(y);  // 2
}
print(y);    // 1```

### Arrays

Arrays are used to store several objects in a list-like fashion and come with many useful helper functions, below are a few.

```let x = [1, 2, 3, 4, 5];
print(x);

// First Item (access by index)
print(x);

// Last Item
print(x.length);
print(x[x.length - 1]);

// Add an item to the end
x.push(6);
print(x);

// Remove an item from the end
x.pop();
print(x);

// Remove an item (or more).
print(x.splice(3, 1));

// More examples at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array```

This should be enough JavaScript to attempt the majority, if not all of the MongoDB questions on NoSQLZoo.
Some questions such as the harder MapReduce questions may be easier by reading up on Computed Properties beforehand.
Further tutorials can be found at the Mozilla Developer Network