Ressources

JavaScript Glossary

This is a glossary of terms and topics in JavaScript as covered in Codecademy courses. It does not attempt to completely define and explain terms, but rather provides a general overview that is appropriate for someone new to the language. For a more comprehensive treatment of these topics, we recommend the Mozilla Developer Network JavaScript documentation.

Variables

Programming languages use variables to store values. Variables may have global or local function scope. Variable names are case sensitive and must start with a letter, underscore (_), or a dollar sign ($).

Variable Assignment

Syntax

var name = value;
var
 : Is the keyword that defines a variable.
name
 : Is the name of the variable.
value
 : Is any JavaScript value or a reference to a value (another variable).

Example

var x = 1;  
var myName = "Bob";
var hisName = myName;

Numbers

*, /, -, + (Multiplication, Division, Addition, Subtraction)

Notes

These will work as you would expect.

% (Modulus)

Syntax

number1 % number2
number1,2 : Is two number variables or actual numbers.
% : Is the modulus operator. It returns the remainder of dividing number1 by number2.

Example

14 % 9 // returns 5

++ (Increment)

variable1++  
++variable2
postfix increment : variable1 is incremented (i.e. variable1 = variable1 + 1). When evaluated, the old value of variable1 is returned.
prefix increment : variable2 is incremented (i.e. variable1 = variable1 + 1) and its new value is returned.

-- (Decrement)

variable1--  
--variable2
postfix increment : variable1 is decremented (i.e. variable1 = variable1 - 1). When evaluated, the old value of variable1 is returned.
prefix increment : variable2 is decremented (i.e. variable2 = variable2 - 1) and its new value is returned.

Strings

String Literals

Syntax

"string of text"  
'string of text'

String Concatenation

Syntax

string1 + string2
string1,2 : Two string variables or literals to be concatenated.
+ : The concatenation operator concatenates string1 and string2 and returns a new string that is the union of both strings. Concatenate is just a fancy word which means to combine to the strings together.

Example

"some" + "text"; // returns "sometext"  
var first = "my";
var second = "string";
var union = first + second; // union variable has the string "mystring"

replace

Returns a string with the first match substring replaced with a new substring.

Example

"original string".replace("original", "replaced"); // returns "replaced string"  

toUpperCase, toLowerCase

Changes the cases of all the alphabetical letters in the string.

Example

"my name".toUpperCase(); // Returns "MY NAME"  
"MY NAME".toLowerCase(); // Returns "my name"

substring

Returns the sequence of characters between two indices within a string.

Example

"adventures".substring(2,9); // Returns "venture"

Booleans

Boolean literals

Syntax

true  
false
true is used to represent a true boolean value.falseis used to represent a false boolean value.

Boolean logical operators

Syntax

expression1 && expression2   expression3 || expression4  
!expression5
&& : Logical AND, returns true if both expression1 and expression2 are true. Otherwise it returns false.
|| : Logical OR, returns true if expression3 or expression4 are true, or both are true. Otherwise it returns false.
! : Logical negation, returns the boolean that is the opposite of expression5.

Comparison operators

Operator

Description

Examples returning true

=== (Equal) : Returns true if the operands are equal.
1 === 1;
!== (Not equal) : Returns true if the operands are not equal.
1 !== 2;
> (Greater than) : Returns true if the first operand is greater than the second operand.
2 > 1;
>= (Greater than or equal) : Returns true if the first operand is greater than or equal to the second operand.
2 > 1;  
1 >= 1;
< (Less than) : Returns true if the first operand is less than the second operand.
2 > 1;   
1 >= 1;
<= (Less than or equal) : Returns true if the first operand is less than or equal to the second operand.
1 < 2;  
1 <= 1;

Comments

A comment is generally used within code to explain how something works or to write necessary information about a section. Comments are very useful to make code more readable.

Single Line Comment

Syntax

// This is a single line comment.


Anything on the line following // will be a comment while anything before will still be code.

Multi-Line Comment

Syntax

/*Comment1    
Comment2
.
.
Comment3 */
Comment1-NEverything between /* and */ will be comments, which can span multiple lines.

Functions

Function definition

Syntax

var name = function (parameter1, parameter2, ..., parameterN) {
statement1; statement2;
.
.
.
statementN;
};
name : The function's name.
parameter : The variable name that will be given to an argument passed to the function.
statement : A single Javascript statement. For example, var x = 1; is a statement.

Example

var greeting = function (name) {
console.log("Hello " + name);
};

Function calling

Syntax

name(argument1, argument2, ..., argumentN);
name : The name of the function to be called.
argument : A value or a reference to a value passed to a function.

Example

greeting('Hello');

If statement

Single if

Syntax

if (condition) {   
statement1;
statement2;
.
.
.
statementN;
}
condition : A boolean condition
statement1...N : The set of statements to execute if the condition evaluates to true.

Example

if (answer === 42) {
console.log('Told you so!');
}

if ... else

Syntax

if (condition) {   
statement1;
} else {
statement2;
}

Notes

If the condition is true, statement1 will be executed. Otherwise, statement2 will be executed.

Example

if (name.length > 0) {
console.log("Please enter your name.");
} else {
console.log("Hello " + name);
}

else if

Syntax

if (condition1) {
statement1;
} else if (condition2) {
statement2;
} else {
statement3;
}

Notes

If condition1 is true, then statement1 will be executed.
If condition1 is false, and condition2 is true, then statement2 will be executed.
If condition1 and condition2 are both false, then statement3 will be executed.

Example

if (someNumber > 10) {
console.log("Numbers larger than 10 are not allowed.");
} else if (someNumber < 0) {
console.log("Negative numbers are not allowed.");
} else {
console.log("Nice number!");
}

Switch statement

Syntax

switch (expression) {
case label1:
statements1;
break;
case label2:
statements2;
break;
.
.
.
case labelN:
statementsN;
break;
default:
statementsX;
break;
}
statements : One or more Javascript statement.
expression : A statement that yields a value - for example, 1 + 1 or x, where x is a predefined variable.
label : A value or an expression to match against the expression

Notes

Switch statements are used to check for different values of a variable (or an expression) to control the flow of the program.

Example

switch (GPA){   
case 90:
letterGrade = "A+";
break;
case 80:
letterGrade = "A";
break;
case 70:
letterGrade = "C";
break;
case 60:
letterGrade = "D";
break;
case 50:
letterGrade = "E";
break;
default:
letterGrade = "F";
break;
}

Ternary operator

Syntax

condition ? expression1 : expression2;  
condition : A boolean expression.
expression : A statement that yields a value.

Notes

The ternary operator is usually used as a shortcut for the if statement.

Example

// Using an if statement.  
var msg = "You ";
if (grade > 50) {
msg = msg + "Passed!";
} else {
msg = msg + "Failed!";
}
console.log(msg);

// Using a ternary operator.
console.log("You " + (grade > 50 ? "Passed!" : "Failed!"));

Objects

An object is a list-like construct that has properties which corresponds to JavaScript values, variables, or other objects.

Object Literals

Syntax

{   
"property 1": value1,
property2: value2,
number: value3
}
property1 : A string property of the object. This can be any valid JavaScript string. This is used when the property contains a space or a character not suitable for an identifier.
property2 : An identifier (Any valid JavaScript variable name, see Variables) property.
number : A valid integer.
value1,2,3 : This can be any valid JavaScript value (number, string, boolean, object, function, etc.).

Example

var obj = {
name: "Bob",
married: true,
"mother's name": "Alice",
"year of birth": 1987,
getAge: function () {
return 2012 - obj["year of birth"];
},
1: 'one'
};

Property Access

Syntax

name1[string]   name2.identifier
name1,2 : The object variable name.
string : Any valid string or a variable referencing a string value.
identifier : An identifier (Any valid JavaScript variable name, see Variables).

Example

obj['name'];  // 'Bob'  
obj.name; // 'Bob'
obj.getAge(); // 24

For loops

Syntax

for ([initialization]; [condition]; [increment]) {
statement1;
statement2;
.
.
.
statementN;
}
initialization : An expression that is executed before the loop starts. Used to initialize a counter variable such as i.
condition : An expression that is executed before each loop iteration. If the result is true the loop will continue otherwise it will stop.
increment : An expression used to change the counter variable at the end of each loop (often a postfix increment).
statement1...N : Javascript statements to be executed while the condition is true.

Example

for (var time = 10; time > 10; time--) {
console.log("Launching rocket in T minus " + time);
console.log("DON'T PANIC");
}

While loops

Syntax

while (condition) {   
statement1;
statement2;
.
.
.
statementN;
}
condition : An expression that is executed before each loop iteration. If the result is true, the loop will continue. Otherwise it will stop.
statement1...N : Javascript statements to be executed in the body of the loop while the condition is true.

Example

while (isDoorOpen()) {
console.log("Please close the door");
}

Do While loops

A Do-While loop is very similar to a regular while loop. A Do-While loop guarantees that the code block will at least be run once regardless of the condition.

Syntax

Syntax

do {   
statement1;
statement2;
.
.
.
statementN;
} while (condition);
statement1...N : Javascript statements to be executed while the condition is true.
condition : An expression that is executed during each loop iteration. If the result is true, the loop will continue. Otherwise, it will stop. The condition is only checked after the first run loop.

Example

do {   
console.log("Runs at least once");
} while (false)

Arrays

An array is a special type of object and is an ordered list of JavaScript values like numbers, strings or even objects.

Array Literals

Syntax

[value1, value2, ..., valueN]
value1...N : A list of Javascript values or variables.

Example

var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37];  

Accessing Array Elements

Syntax

name[index]
name : The array variable name.
index : The 0-based index of the element in the array. Note that the position of an element in an array is determined by the number of elements to the left of it. As a result, the first element in an array is at index 0.

Example

var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37];  
primes[0]; // 2
primes[3]; // 7

Multi-dimensional Arrays

Syntax

var 1D = [];    

Visual:
[ | | | | | ]


var 2D = [ [], [], [],...];
Visual:
[ | | | | | ]
[ | | | | | ]
[ | | | | | ]
[ | | | | | ]

Math

Math is an object that contains a library of math functions.

random

Syntax

Math.random()

Returns a random number between 0 and 1.

Example

Math.random(); // A random number between 0 and 1.

floor

Syntax

Math.floor(expression)

Returns the largest integer less than or equal to a number.

expression : An expression returning a number.

Example

Math.floor(9.99); // 9  
Math.floor(1 + 0.5); // 1
Math.floor(Math.random() * X + 1); // Returns a random number between 1 and X

Errors

Error message

Description

Examples causing error

Syntax Error: Unexpected Token : A valid Javascript keyword/character is found in a place in your code where a different keyword/character is expected.
var x - 1;   
SyntaxError: Unexpected
token -
Syntax Error: Unexpected identifier : A non-keyword was found in a place in your code where a certain keyword/character is expected.
var x a 1  
SyntaxError: Unexpected
identifier a
ReferenceError: Invalid left-hand side in assignment : This happens when we try to assign a value to a non-variable.
1 = x  
ReferenceError: Invalid
left-hand side in
assignment
ReferenceError: {word} is not defined : This happens when we try to use a variable which has not been defined.
a++;   
ReferenceError: a is not
defined

alert

Syntax

alert(message);
messsage : A string of text to be displayed in the alert dialog.

Example

alert("Hello World");

prompt

Syntax

prompt(message);
message : A string of text to be displayed in the prompt dialog.

Example

var name = prompt("Enter your name:");  

confirm

Syntax

confirm(message);
message : A string of text to be displayed in the confirm dialog.
if ( confirm("Are you sure you want to delete this post?") ) {
deletePost();
}

OOP

Classes

A class can be thought of as a template to create many objects with similar qualities. Classes are a fundamental component of object-oriented programming (OOP).

Class constructor

Syntax

var ClassName = function (parameter1, parameter2, ..., parameterN) {   
this.property1 = parameter1;
this.property2 = expression;
};
ClassName : The name of the new class. By convention, class names are always uppercase.
parameter1..N : Parameters passed in when the class is created. This is generally used to assign a property value. Parameters are optional.
this : Refers to the class instance object being created.
property1 : A property or "attribute" of the class. This can be either an simple value or a function. Can be initialized with default values or values passed in through a parameter.
property2 : An example of a property that has a default value (in this case its the result of an expression) that is not the value of a parameter.

Example

var Vegetable = function (color) {     
this.color = color;
this.delicious = true;
this.eat = function() {
console.log("nom");
};
};

Class Instances and Usage

Syntax

var objName = new ClassName(argument1, argument2, ..., argumentN);  
objName : New instances of the ClassName class. These are objects.
ClassName : The class we are creating an instance of.
argument1...N : Arguments we are passing into the class.

Example

var broccoli = new Vegetable("green");  
console.log("Broccoli is " + broccoli.color + "!"); // will print "Broccoli is green!"

Notes

In the example above, we are accessing the color property on the object "broccoli" that is an instance of the class "Vegetable". See object property access.

Class methods

Syntax

ClassName.prototype.methodName = function (paramater1, paramater2, ... paramaterN) {
statement1
.
.
statmentN
};
ClassName : The class which the method is being added to.
methodName : The name of the method we're adding.
paramater1...N : The method parameters.

Example

var Person = function () {   
this.job = "Unemployed";
};

Person.prototype.getJob = function() {
return this.job;
};

var Bob = new Person();
Bob.getJob(); // 'Unemployed'

Inheritance

Inheritance allows one class to gain properties from another class.

Syntax

SubClass.prototype = new SuperClass();  
SubClass : The class that receives the inheritance, the child.
SuperClass : The class that gives the inheritance, the parent.

Example

var PoliceOfficer = function (age) {
this.job = "Police Officer";
this.age = age;
};

PoliceOfficer.prototype = new Person();

PoliceOfficer.prototype.retire = function () {
if (this.age > 66) {
this.retired = true;
} else {
this.retired = false;
}

return this.retired;
};

var Alice = new PoliceOfficer(43);
Alice.getJob(); // 'Police Officer' Alice.retire(); // false

Example

var Lieutenant = function (age) {
this.rank = "Lieutenant";
this.age = age;
};

Lieutenant.prototype = new PoliceOfficer();

Lieutenant.prototype.getRank = function () {
return this.rank;
};

var John = new Lieutenant(67);
John.getJob(); // 'Police Officer'
John.getRank(); // 'Lieutenant'
John.retire(); // true