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

Difference between revisions of "JavaScript: Fundamentals"

From NoSQLZoo
Jump to: navigation, search
Line 224: Line 224:
 
print(y);    // 1</nowiki></pre>
 
print(y);    // 1</nowiki></pre>
 
</div>
 
</div>
 
 
===Functions===
 
===Functions===
 
Functions are groups of statements that can be called by name to perform a certain task.<br/><br/>
 
Functions are groups of statements that can be called by name to perform a certain task.<br/><br/>
Line 261: Line 260:
 
});</nowiki></pre>
 
});</nowiki></pre>
 
</div>
 
</div>
 +
===Arrays===
 +
Arrays are used to store several objects in a list-like fashion and come with many useful helper functions, below are a few.<br/>
 +
<div class="q nonum" data-lang="mongo">
 +
<pre class="def"><nowiki>
 +
let x = [1, 2, 3, 4, 5];
 +
print(x);
 +
 +
// First Item (access by index)
 +
print(x[0]); 
 +
 +
// 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</nowiki></pre>
 +
</div>
 +
 +
 +
This should be enough JavaScript to attempt the majority, if not all of the MongoDB questions on NoSQLZoo. <br/>
 +
Further tutorials can be found at the [https://developer.mozilla.org/en-US/docs/Web/JavaScript Mozilla Developer Network]

Revision as of 15:47, 20 July 2018

Introduction to JavaScript

JavaScript is a high level interpretted scripting language originally created to enable interactivity in web pages.
Today, JavaScript has many additional applications, and in particular is used by MongoDB to provide an 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. Javascript has seven types in total:

Number
Any number, such a 1, -3.4, or 2E9.
In JavaScript all numbers are stored in 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

Functions

Functions are groups of statements that can be called by name to perform a certain task.

They can be either named, e.g. function exampleFunction(), or anonymous, e.g. function (). Typically anonymous functions in MongoDB are used as arguments to another function, such as mapReduce.
Functions can optionally take variables as parameters, also known arguments, e.g. function (1, 2) and have the ability to return values too.
If a function does not explicitly return a value or lacks a return statement entirely then the behavior is the same as return undefined

To refer to a function as a variable simply use it's name, e.g. myFunc.
To run a function you must call it by including parenthesis after the name, e.g. myFunc()

/* This function outputs "Hello World!" to screen.
 */
function helloWorld() {
    print("Hello World!");
}

/* This function reverses a string.
 */
function reverseString(s) {
    return s.split("").reverse().join("");
}

/* This function runs any function you pass to it.
 */
function functionRunner(x) {
    x();
}

helloWorld();
print(reverseString("backwards"));

functionRunner(helloWorld); // Pass the helloWorld function as an argument.

functionRunner(function () { // Pass an anonymous function as an argument.
    print(2 * 3 * 5 * 7);
});

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[0]);  

// 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.
Further tutorials can be found at the Mozilla Developer Network