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
 
(8 intermediate revisions by the same user not shown)
Line 2: Line 2:
 
==Introduction to JavaScript==
 
==Introduction to JavaScript==
 
JavaScript is a high level interpretted scripting language originally created to enable interactivity in web pages.<br/>
 
JavaScript is a high level interpretted scripting language originally created to enable interactivity in web pages.<br/>
Today, JavaScript has many additional applications, and in particular is used by MongoDB to provide an interactive shell environment.<br/>
+
Today, JavaScript has many other uses, one of which is powering the MongoDB interactive shell environment.<br/>
 
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)'''.
 
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)'''.
  
Line 122: Line 122:
  
 
===Variables and Types===
 
===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:  
+
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:  
 
<br/><br/>
 
<br/><br/>
<code>Number</code><br/>
+
<syntaxhighlight lang="JavaScript" inline>Number</syntaxhighlight><br/>
 
Any number, such a <code>1</code>, <code>-3.4</code>, or <code>2E9</code>.<br/>
 
Any number, such a <code>1</code>, <code>-3.4</code>, or <code>2E9</code>.<br/>
In JavaScript all numbers are stored in floating point format.
+
In JavaScript all numbers are stored in [https://ieeexplore.ieee.org/document/4610935 IEEE floating-point format.]
 
<div class="q nonum" data-lang="mongo">
 
<div class="q nonum" data-lang="mongo">
 
<pre class="def"><nowiki>
 
<pre class="def"><nowiki>
Line 136: Line 136:
 
);</nowiki></pre>
 
);</nowiki></pre>
 
</div>
 
</div>
<code>String</code><br/>
+
<syntaxhighlight lang="JavaScript" inline>String</syntaxhighlight><br/>
A string is a sequence of characters surrounded by quotation marks. e.g. <code>"Bob"</code>, <code>"Alice"</code><br/>
+
A string is a sequence of characters surrounded by quotation marks. e.g. '''"Bob"''', '''"Alice"'''<br/>
There are several methods availible to making working with strings easier that can be found [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String Here].
+
There are several methods availible to making working with strings easier that can be found [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String here].
 
<div class="q nonum" data-lang="mongo">
 
<div class="q nonum" data-lang="mongo">
 
<pre class="def"><nowiki>
 
<pre class="def"><nowiki>
Line 148: Line 148:
 
<br/>
 
<br/>
  
<code>Boolean</code><br/>
+
<syntaxhighlight lang="JavaScript" inline>Boolean</syntaxhighlight><br/>
A variable that can be either '''true''' or '''false'''.<br/>
+
A variable that can be either <syntaxhighlight lang="JavaScript" inline>true</syntaxhighlight> or <syntaxhighlight lang="JavaScript" inline>false</syntaxhighlight>.<br/>
 
Comparison and logical operators always return a boolean and can be used with an '''if''' statement to control program flow.
 
Comparison and logical operators always return a boolean and can be used with an '''if''' statement to control program flow.
 
<div class="q nonum" data-lang="mongo">
 
<div class="q nonum" data-lang="mongo">
Line 171: Line 171:
 
print((3 > 2 ? "Three" : "Two") + " is larger");</nowiki></pre>
 
print((3 > 2 ? "Three" : "Two") + " is larger");</nowiki></pre>
 
</div>
 
</div>
<code>Symbol</code><br/>
+
<syntaxhighlight lang="JavaScript" inline>Symbol</syntaxhighlight><br/>
 
Symbols are used to create unique identifiers. You shouldn't have to use a symbol for any of the questions on this website.
 
Symbols are used to create unique identifiers. You shouldn't have to use a symbol for any of the questions on this website.
  
 
<br/>
 
<br/>
<code>undefined</code><br/>
+
<syntaxhighlight lang="JavaScript" inline>undefined</syntaxhighlight><br/>
 
A variable that has been '''declared''', but that has had no value assigned to it.
 
A variable that has been '''declared''', but that has had no value assigned to it.
  
 
<br/>
 
<br/>
<code>object</code><br/>
+
<syntaxhighlight lang="JavaScript" inline>object</syntaxhighlight><br/>
 
Objects are collections of multiple variables (properties) and are used to represent complex data structures. For example, consider this object representing an employee:
 
Objects are collections of multiple variables (properties) and are used to represent complex data structures. For example, consider this object representing an employee:
<pre>
+
<syntaxhighlight lang="JavaScript">
 
{
 
{
 
   name: "Jill",
 
   name: "Jill",
Line 191: Line 191:
 
   }
 
   }
 
}
 
}
</pre>
+
</syntaxhighlight>
 
Let's call this object '''x'''. By using either dot notation or bracket notation it is possible to get and set x's properties.
 
Let's call this object '''x'''. By using either dot notation or bracket notation it is possible to get and set x's properties.
<pre>
+
<syntaxhighlight lang="JavaScript">
 
print(x.name);                          // Returns: "Jill"
 
print(x.name);                          // Returns: "Jill"
 
print(x.nam);                          // Returns: undefined
 
print(x.nam);                          // Returns: undefined
 
print(x['age']);                        // Returns: 22
 
print(x['age']);                        // Returns: 22
 
x.job.title = "Database Administrator"; // Changes the title field of the job object inside the x object.
 
x.job.title = "Database Administrator"; // Changes the title field of the job object inside the x object.
</pre>
+
</syntaxhighlight>
  
 
<br/>
 
<br/>
<code>null</code><br/>
+
<syntaxhighlight lang="JavaScript" inline>null</syntaxhighlight><br/>
Technically not a separate type but a special kind of <code>object</code> that is used to represent assigned but 'empty' variables.
+
Technically not a separate type but a special kind of <syntaxhighlight lang="JavaScript" inline>object</syntaxhighlight>that is used to represent assigned but 'empty' variables.
 
 
 
===Assignments, and scope===
 
===Assignments, and scope===
To define and assign variables either use the <code>var</code> or <code>let</code> keyword.<br/><br/>
+
To define and assign variables either use the <syntaxhighlight lang="JavaScript" inline>var</syntaxhighlight> or <syntaxhighlight lang="JavaScript" inline>let</syntaxhighlight> keyword.<br/><br/>
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, <code>var</code> will use the scope of the entire function, whereas <code>let</code> variables will only affect the block in which they are defined.<br/><br/> To see this in action use the example below, which has been adapted from a Mozilla Developer Network example:
+
If declared outside of a function (discussed below) variables are '''global''', i.e. they can can be accessed and edited from anywhere.<br/>
 +
If used inside a function, <syntaxhighlight lang="JavaScript" inline>var</syntaxhighlight> will use the scope of the entire function, whereas <syntaxhighlight lang="JavaScript" inline>let</syntaxhighlight> variables will only affect the block in which they are defined.<br/><br/> To see this in action use the example below, which has been adapted from a Mozilla Developer Network example:
 
<div class="q nonum" data-lang="mongo">
 
<div class="q nonum" data-lang="mongo">
 
<pre class="def"><nowiki>
 
<pre class="def"><nowiki>
var x = 1;
+
var x = 1;   // declare a global variable, x
 
if (true) {
 
if (true) {
   var x = 2; // same variable!
+
   var x = 2; // same global variable, x
 
   print(x);  // 2
 
   print(x);  // 2
 
}
 
}
 
print(x);    // 2
 
print(x);    // 2
  
let y = 1;
+
let y = 1;   // declare a global variable, y
 
if (true) {
 
if (true) {
   let y = 2; // different variable
+
   let y = 2; // different local variable, y
 
   print(y);  // 2
 
   print(y);  // 2
 
}
 
}
 
print(y);    // 1</nowiki></pre>
 
print(y);    // 1</nowiki></pre>
 +
</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>
 
</div>
  
===Function===
+
This should be enough JavaScript to attempt the majority, if not all of the MongoDB questions on NoSQLZoo. <br/>
Functions, also known as methods or proceedures, are sets of statements that perform a certain task. They can be either named, e.g. <code>function exampleFunction()</code>, or '''anonymous''', e.g. <code>function ()</code>. Typically anonymous functions in MongoDB are used as arguments to another function, such as <code>mapReduce</code>.<br/>
+
Some questions such as the harder MapReduce questions may be easier by reading up on [[JavaScript:_Computed_Properties | Computed Properties]] beforehand. <br />
Functions can optionally take variables as '''parameters''', also known '''arguments''', e.g. <code>function (1, 2)</code> and have the ability to '''return''' values too. If a function does not explicity return a value the behaviour is the same as <code>return undefined</code>
+
Further tutorials can be found at the [https://developer.mozilla.org/en-US/docs/Web/JavaScript Mozilla Developer Network]

Latest revision as of 14:34, 17 October 2018

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 objectthat 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[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.
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