JavaScript is a high-level programming language that all modern web browsers support.
It is also one of the core technologies of the web, along with HTML and CSS.
This guide will cover basic JavaScript programming concepts, which range from variables and arithmetic to objects and loops.
There are two ways to write comments in JavaScript:
Using // will tell JavaScript to ignore the remainder of the text on the current line
// This is an in-line comment.
You can make a multi-line comment beginning with /* and ending with */
/* This is a multi-line comment,
This is a multi-line comment,
This is a multi-line comment,
This is a multi-line comment */
JavaScript provides seven different data types which are undefined, null, boolean, string, symbol, number, and object.
We tell JavaScript to create or declare a variable by putting the keyword var in front of it, like so:
var ourName;
This code creates a variable called ourName. In JavaScript we end statements with semicolons.
Variable names can be made up of numbers, letters, and $ or _, but may not contain spaces or start with a number.
In JavaScript, you can store a value in a variable with the assignment " = " operator.
myVariable = 5;
This assigns the Number value 5 to myVariable.
Assignment always goes from right to left. Everything to the right of the " = " operator is resolved before the value is assigned to the variable to the left of the operator.
myVar = 5;
myNum = myVar;
This assigns 5 to myVar and then resolves myVar to 5 again and assigns it to myNum.
It is common to initialize a variable to an initial value in the same line as it is declared.
var myVar = 0;
This code creates a new variable called myVar and assigns it an initial value of 0.
When JavaScript variables are declared, they have an initial value of undefined.
If you do a mathematical operation on an undefined variable your result will be NaN, which means "Not a Number".
If you concatenate a string with an undefined variable, you will get a literal string of "undefined".
Wrong usage:
var a;
var b;
var c;
a = a + 1; // a = NaN
b = b + 5; // b = NaN
c = c + " World!"; // c = "undefined"
Right usage:
var a = 1;
var b = 2;
var c = "Hello";
a = a + 1; // a = 2
b = b + 5; // b = 7
c = c + " World!"; // c = "Hello World!"
We can store decimal numbers in variables too. Decimal numbers are sometimes referred to as floating point numbers or floats.
Example
var myDecimal = 6.34;
Note
Not all real numbers can accurately be represented in floating point. This can lead to rounding errors. Details Here
In JavaScript all variables and function names are case sensitive. This means that capitalization matters.
MYVAR is not the same as MyVar nor myvar.
It is possible to have multiple distinct variables with the same name but different casing.
It is strongly recommended that for the sake of clarity, you do not use this language feature.
Best Practice
Write variable names in JavaScript in camelCase. In camelCase, multi-word variable names have the first word in lowercase
and the first letter of each subsequent word is capitalized.
Examples:
var someVariable;
var anotherVariableName;
var thisVariableNameIsSoLong;
Number is a data type in JavaScript which represents numeric data.
JavaScript uses the " + " symbol as increment operation when placed between two numbers.
Example
myVar = 5 + 10; // myVar now has an assigned value of 15
myVar = 5.2 + 10.6; // myVar now has an assigned value of 15.8
JavaScript uses the " - " symbol for subtraction.
Example
myVar = 12 - 6; // myVar now has an assigned value of 6
myVar = 10.4 - 5.3; // myVar now has an assigned value of 5.1
JavaScript uses the " * " symbol for multiplication of two numbers.
Example
myVar = 13 * 13; // myVar now has an assigned value of 169
myVar = 2.2 * 4; // myVar now has an assigned value of 4.4
JavaScript uses the " / " symbol for division.
Example
myVar = 16 / 2; // myVar now has an assigned value of 8
myVar = 14.5 / 2; // myVar now has an assigned value of 7.25
You can easily increment or add one to a variable with the " ++ " operator.
The equivalent of:
i = i + 1;
is
i++; // eliminating the need for the equal sign
You can easily decrement or subtract one to a variable with the " -- " operator.
The equivalent of:
i = i - 1;
is
i--; // eliminating the need for the equal sign
The remainder operator " % " gives the remainder of the division of two numbers.
Example
5 % 2 = 1 because
Math.floor(5 / 2) = 2 (Quotient)
2 * 2 = 4
5 - 4 = 1 (Remainder)
Usage
In mathematics, a number can be checked to be even or odd by checking the remainder of the division of the number by 2.
17 % 2 = 1 (17 is Odd)
48 % 2 = 0 (48 is Even)
Note
The remainder operator is sometimes incorrectly referred to as the "modulus" operator. It is very similar to modulus, but does not work properly with negative numbers.
In programming, it is common to use assignments to modify the contents of a variable.
Remember that everything to the right of the equals sign is evaluated first.
myVar = myVar + 5;
This code is to add 5 to myVar. Since this is such a common pattern, there are operators which do both a mathematical operation and assignment in one step.
One such operator is the " += " operator.
var myVar = 1;
myVar += 5; // same as myVar = myVar + 5;
console.log(myVar); // Returns myVar as 6
The " -= " operator subtracts a number from a variable.
var myVar = 1;
myVar -= 5; // same as myVar = myVar - 5;
console.log(myVar); // Returns myVar as -4
This code will subtract 5 from myVar.
The " *= " operator multiplies a variable by a number.
var myVar = 2;
myVar *= 5; // same as myVar = myVar * 5;
console.log(myVar); // Returns myVar as 10
This code will multiply myVar by 5.
The " /= " operator divides a variable by another number.
var myVar = 10;
myVar /= 5; // same as myVar = myVar / 5;
console.log(myVar); // Returns myVar as 2
This code will divide myVar by 5.
var myName = "your name";
"your name" is called a string literal.
It is a string because it is a series of zero or more characters enclosed in single or double quotes.
When you are defining a string you must start and end with a single or double quote.
What happens when you need a literal quote: " or ' inside of your string?
In JavaScript, you can escape a quote from considering it as an end of string quote by placing a backslash " \ " in front of the quote.
var sampleStr = "Peter said, \"Albert is learning JavaScript\".";
This signals to JavaScript that the following quote is not the end of the string, but should instead appear inside the string.
So if you were to print this to the console, you would get:
Alan said, "Peter is learning JavaScript".
String values in JavaScript may be written with single or double quotes, as long as you start and end with the same type of quote.
Unlike some other programming languages, single and double quotes work the same in JavaScript.
doubleQuoteStr = "This is a string";
singleQuoteStr = 'This is also a string';
The reason why you might want to use one type of quote over the other is if you want to use both in a string.
This might happen if you want to save a conversation in a string and have the conversation in quotes.
Another use for it would be saving an <a> tag with various attributes in quotes, all within a string.
conversation = 'Finn exclaims to Jake, "Algebraic!"';
However, this becomes a problem if you need to use the outermost quotes within it.
Remember, a string has the same kind of quote at the beginning and end.
But if you have that same quote somewhere in the middle, the string will stop early and throw an error.
goodStr = 'Jake asks Finn, "Hey, let\'s go on an adventure?"';
badStr = 'Finn responds, "Let's go!"'; // Throws an error
In the goodStr above, you can use both quotes safely by using the " backslash \ " as an escape character.
Note
The " backslash \ " should not be be confused with the " forward slash / ". They do not do the same thing.
Quotes are not the only characters that can be escaped inside a string. There are two reasons to use escaping characters:
First is to allow you to use characters you might not otherwise be able to type out, such as a backspace.
Second is to allow you to represent multiple quotes in a string without JavaScript misinterpreting what you mean. As shown in "Quoting Strings with Single Quotes [0][21]".
\' single quote
\" double quote
\\ backslash
\n newline
\r carriage return
\t tab
\b backspace
\f form feed
" is replaced with & quot; (without the space)
& is replaced with & amp; (without the space)
< is replaced with & lt; (without the space)
> is replaced with & gt; (without the space)
Note
The backslash itself must be escaped in order to display as a backslash.
In JavaScript, when the " + " operator is used with a String value, it is called the concatenation operator.
You can build a new string out of other strings by concatenating them together.
Example
var myVariable1 = 'My name is the plus Operator,';
var myVariable2 = ' I concatenate.';
var myVariable3 = myVariable1 + myVariable2;
console.log(myVariable3); // Returns 'My name is the plus Operator, I concatenate.'
or
var myVariable = 'My name is the plus Operator,' + ' I concatenate.';
console.log(myVariable); // Returns 'My name is the plus Operator, I concatenate.'
Note
Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself.
We can also use the " += " operator to concatenate a string onto the end of an existing string variable.
This can be very helpful to break a long string over several lines.
var myStr = "I come first. ";
myStr += "I come second.";
console.log(myStr); // Returns "I come first. I come second."
Sometimes you will need to build a string.
By using the concatenation operator " + ", you can insert one or more variables into a string you're building.
var myName = "Nephthys";
var myStr = "This site is build by " + myName + ", purely for learning Java.";
console.log(myStr); // Returns "This site is build by Nephthys, purely for learning Java."
Just as we can build a string over multiple lines out of string literals,
we can also append variables to a string using the plus equals " += " operator.
var myFirstStr = " Webdesign";
var mySecondStr = "Nephthys";
console.log(mySecondStr); // Returns "Nephthys"
mySecondStr += myFirstStr;
console.log(mySecondStr); // Returns "Nephthys Webdesign"
You can find the length of a String value by writing " .length " after the string variable or string literal.
var myVar = "A Variable";
console.log(myVar); // Returns "A Variable"
console.log(myVar.length); // Returns 10 (characters, including spaces!)
Bracket notation " [] " is a way to get a character at a specific index within a string.
Most modern programming languages, like JavaScript, don't start counting at 1 like humans do.
They start at 0. This is referred to as Zero-based indexing.
Example
var myVar = "Charles";
console.log(myVar); // Returns "Charles"
console.log(myVar[0]); // Returns "C", the first index
You can also use bracket notation to get the character at other positions within a string.
Remember that computers start counting at 0, so the first character is actually the zeroth character.
Example
var myVar = "Charles";
console.log(myVar); // Returns "Charles"
console.log(myVar[3]); /* Returns "r", the fourth index, as in
1st character: C = [0], 2nd: H = [1], 3th: A = [2], 4th: R = [3] */
In order to get the last letter of a string, you can subtract one from the string's length.
Example
var firstName = "Charles";
var lastLetter = firstName[firstName.length - 1];
console.log(lastLetter); // Returns "s"
You can use the same principle we just used to retrieve the last character in a string to retrieve the Nth-to-last character.
Example
var firstName = "Charles";
var nToLastLetter = firstName[firstName.length - 3];
console.log(nToLastLetter); // Returns "l"
In JavaScript, String values are immutable, which means that they cannot be altered once created.
Example
var myStr = "Bob";
myStr[0] = "J";
This code cannot change the value of myStr to "Job", because the contents of myStr cannot be altered.
Note that this does not mean that myStr cannot be changed, just that the individual characters of a string literal cannot be changed.
The only way to change myStr would be to assign it with a new string, like this:
var myStr = "Bob";
myStr = "Job";
In a "Mad Libs" game, you are provided sentences with some missing words, like nouns, verbs, adjectives and adverbs.
You then fill in the missing pieces with words of your choice in a way that the completed sentence makes sense.
Consider this sentence - "It was really ____, and we ____ ourselves ____".
This sentence has three missing pieces- an adjective, a verb and an adverb, and we can add words of our choice to complete it.
We can then assign the completed sentence to a variable.
var sentence = "It was really " + variable1 + ", and we " + variable2 + " ourselves " + variable3;
Example
function wordBlanks(myNoun, myAdjective, myVerb, myAdverb) {
var result = "My " + myAdjective + " " + myNoun + " " + myVerb + " very " + myAdverb + ".";
return result;
}
wordBlanks("dog", "big", "ran", "quickly"); // Calling function 'X' with input-variables
console.log(result); // Returns "My big dog ran very quickly."
With JavaScript array variables, we can store several pieces of data in one place.
You start an array declaration with an opening square bracket, end it with a closing square bracket,
and put a comma between each entry.
Example
var sandwich = ["peanut butter", "jelly", "bread"];
var telephoneNumber = ["NL", "+31", 10, 1234567];
You can also nest arrays within other arrays.
Example
var myArray = [["the universe", 42], ["everything", 101010]];
This is also called a Multi-dimensional Array.
We can access the data inside arrays using indexes.
Array indexes are written in the same bracket notation that strings use,
except that instead of specifying a character, they are specifying an entry in the array.
Like strings, arrays use zero-based indexing, so the first element in an array is element 0.
Example
var array = [50,60,70];
array[0]; // equals 50
var data = array[1]; // equals 60
Note
There shouldn't be any spaces between the array name and the square brackets, like
array [0]
Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.
Unlike strings -> Understanding String Immutability [0][32], the entries of arrays are mutable and can be changed freely.
Example
var ourArray = [50,40,30];
ourArray[0] = 15; // equals [15,40,30]
One way to think of a multi-dimensional array, is as an array of arrays.
When you use brackets to access your array, the first set of brackets refers to the entries in the outer-most (the first level) array,
and each additional pair of brackets refers to the next level of entries inside.
Example
var myArr = [
[1,2,3], // [0]
[4,5,6], // [1]
[7,8,9], // [2]
[[10,11,12], 13, 14] // [3]
];
myArr[3]; // equals [[10,11,12], 13, 14]
myArr[3][0]; // equals [10,11,12]
myArr[3][0][1]; // equals 11
Note
There shouldn't be any spaces between the array name and the square brackets.
Example
array [0][0];
array [0] [0];
Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.
An easy way to append data to the end of an array is via the .push() function.
.push() takes one or more parameters and adds the variables at the end of the array.
Example
var myArr = [1,2,3];
myArr.push(4); // myArr is now [1,2,3,4]
An easy way to append data to the start of an array is via the .unshift() function.
.unshift() takes one or more parameters and adds the variables at the beginning of the array.
Example
var myArr = [1,2,3];
myArr.unshift(4); // myArr is now [4,1,2,3]
.pop() is used to remove the last element of an array.
We can store this removed value by assigning it to a variable.
In other words, .pop() removes the last element from an array and returns that element.
Any type of entry can be removed off of an array - numbers, strings, even nested arrays.
Example
var threeArr = [1, 4, 6];
console.log(threeArr); // Returns [1, 4, 6]
var oneDown = threeArr.pop();
console.log(oneDown); // Returns 6
console.log(threeArr); // Returns [1, 4]
.shift() is used to remove the first element of an array.
We can store this removed value by assigning it to a variable.
In other words, .shift() removes the first element from an array and returns that element.
Any type of entry can be removed off of an array - numbers, strings, even nested arrays.
Example
var threeArr = [1, 4, 6];
console.log(threeArr); // Returns [1, 4, 6]
var oneDown = threeArr.shift();
console.log(oneDown); // Returns 1
console.log(threeArr); // Returns [4, 6]
In JavaScript, we can divide up our code into reusable parts called functions.
Example
function functionName() {
console.log("Hello World");
}
All of the code between the curly braces " { } " will be executed every time the function is called.
You can call or invoke this function by using its name followed by parentheses, like this:
functionName();
Each time the function is called it will print out the message "Hello World" on the dev console.
Parameters are variables that act as placeholders for the values that are to be input to a function when it is called.
When a function is defined, it is typically defined along with one or more parameters.
The actual values that are input (or "passed") into a function when it is called are known as arguments.
Here is a function with two parameters, param1 and param2:
function testFun(param1, param2) {
console.log(param1, param2);
}
Then we can call testFun:
testFun("Hello", "World"); // "Hello" = param1, "World" = param2, Returns "Hello,World"
We have passed two arguments, "Hello" and "World". Inside the function, param1 will equal "Hello" and param2 will equal "World".
Note that you could call testFun again with different arguments and the parameters would take on the value of the new arguments.
In JavaScript, scope refers to the visibility of variables. Variables which are defined outside of a function block have Global scope.
This means, they can be seen everywhere in your JavaScript code.
Variables which are used without the var keyword are automatically created in the global scope.
This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with var.
Variables which are declared within a function, as well as the function parameters have local scope.
That means, they are only visible within that function.
Here is a function myTest with a local variable called loc.
function myTest() {
var loc = "foo";
console.log(loc);
}
myTest(); // logs "foo"
console.log(loc); // loc is not defined
loc is not defined outside of the function.
It is possible to have both local and global variables with the same name.
When you do this, the local variable takes precedence over the global variable.
Example
var someVar = "Hat";
function myFun() {
var someVar = "Head";
return someVar;
}
console.log(someVar); // Returns "Hat"
myFun(); // Returns "Head"
The function myFun will return "Head" because the local version of the variable is present.
Else the function would have worked with the global version of the variable and returned "Hat."
It is possible to have multiple distinct variables with the same name both local as global. It is strongly recommended that for the sake of clarity, you do not use this language feature.
We can pass values into a function with arguments. You can use a return statement to send a value back out of a function.
Example
function plusThree(num) {
return num + 3;
}
var answer = plusThree(5); // the variable anwer is assigned the value 8
plusThree takes an argument for num (5) and returns a value equal to num + 3.
A function can include the return statement but it does not have to.
In the case that the function doesn't have a return statement, when you call it,
the function processes the inner code but the returned value is undefined.
Example
var sum = 0;
function addSum(num) {
sum = sum + num; // sum = 0 + 3, inside the function the value for sum is changed to 3.
// There is just no return to the variable that made "the call"
}
var returnedValue = addSum(3); // sum will be modified but returned value is undefined
console.log(sum); // will return a 3, from the changes made by adding 3;
addSum is a function without a return statement.
The function will change the global sum variable but the returned value of the function is undefined
Everything to the right of the equal sign is resolved before the value is assigned.
This means we can take the return value of a function and assign it to a variable.
Example
function sum(parameter1, parameter2) {
sum = parameter1 + parameter2;
return sum;
}
ourSum = sum(5, 12); // variable ourSum will be assigned 17
Another data type is the Boolean. Booleans may only be one of two values: true or false.
They are basically little on-off switches, where true is "on" and false is "off". These two states are mutually exclusive.
It is, or it is not
Note
Boolean values are never written with quotes. The strings "true" and "false" are not Boolean and have no special meaning in JavaScript.
Example
var num1 = 10;
var num2 = 20;
if (num1 < num2) { // Check if num1 is smaller than num2
return true; // if it is, return Boolean true.
return "yes, true"; // and return the string "yes, true". No Boolean.
}
else {
return false; // if it is not, return Boolean false.
return "no, false"; // and return the string "no, false". No Boolean.
};
if statements are used to make decisions in code.
The keyword if tells JavaScript to execute the code in the curly braces under certain conditions, defined in the parentheses.
These conditions are known as Boolean conditions and they may only be true or false.
When the condition evaluates to true, the program executes the statement inside the curly braces.
When the Boolean condition evaluates to false, the statement inside the curly braces will not execute.
Pseudocode
if (condition is true) {
statement is executed
}
Example
function test (myCondition) {
if (myCondition) {
return "It was true";
}
return "It was false";
}
test(true); // returns "It was true"
test(false); // returns "It was false"
When test is called with a value of true, the if statement evaluates myCondition to see if it is true or not.
Since it is true, the function returns "It was true".
When we call test with a value of false, myCondition is not true and the statement in the curly braces is not executed
and the function returns "It was false".
There are many Comparison Operators in JavaScript. All of these operators return a boolean true or false value.
The most basic operator is the equality operator " == ".
The equality operator compares two values and returns true if they're equivalent or false if they are not.
Note that equality is different from assignment (=), which assigns the value at the right of the operator to a variable in the left.
Example
function equalityTest(myVal) {
if (myVal == 10) {
return "Equal";
}
return "Not Equal";
}
If myVal is equal to 10, the equality operator returns true, so the code in the curly braces will execute, and the function will return "Equal".
Otherwise, the function will return "Not Equal".
In order for JavaScript to compare two different data types (for example, numbers and strings), it must convert one type to another.
This is known as "Type Coercion". Once it does, however, it can compare terms as follows:
1 == 1 // true
1 == 2 // false
1 == '1' // true
"3" == 3 // true
Strict equality " === " is the counterpart to the equality operator " == ".
Unlike the equality operator, which attempts to convert both values being compared to a common type,
the strict equality operator does not perform a type conversion and will compare both the data type and value as-is,
without converting one type to the other.
If the values being compared have different types, they are considered unequal, and the strict equality operator will return false.
Example
3 === 3 // true
3 === '3' // false
In the second example, 3 is a Number type and '3' is a String type.
Note
In JavaScript, you can determine the type of a variable or a value with the typeof operator.
typeof 3 // returns 'number'
typeof '3' // returns 'string'
3 == '3' // returns true because JavaScript performs type conversion from string to number
3 === '3' // returns false because the types are different and type conversion is not performed
The inequality operator " != " is the opposite of the equality operator.
It means "Not Equal" and returns false where equality would return true and vice versa.
Thus. [If Unequal return true] and [If Equal return false]
Like the equality operator, the inequality operator will convert data types of values while comparing.
Example
1 != 2 // true : number 1 is not number 2, thus unequal
1 != "1" // false : number 1 is string 1, thus equal
1 != '1' // false : number 1 is string 1, thus equal
1 != true // false : number 1 is true, thus equal
0 != false // false : number 0 is false, thus equal
The strict inequality operator " !== " is the logical opposite of the strict equality operator.
It means "Strictly Not Equal" and returns false where strict equality would return true and vice versa.
Strict inequality will not convert data types.
Example
3 !== 3 // false : 3 is 3, thus equal, so this is false.
3 !== '3' // true : number 3 is unequal to string "3", so this is true.
4 !== 3 // true : 4 is not 3, thus unequal, so this is true.
The greater than operator " > " compares the values of two numbers.
If the number to the left is greater than the number to the right, it returns true. Otherwise, it returns false.
Like the equality operator, greater than operator will convert data types of values while comparing.
Example
5 > 3 // true : 5 is greater than 3, return true
7 > '3' // true : 7 is greater than 3, return true
2 > 3 // false : 2 is NOT greater than 3, return false
'1' > 9 // false : 1 is NOT greater than 9, return false
The greater than or equal to operator " >= " compares the values of two numbers.
If the number to the left is greater than or equal to the number to the right, it returns true. Otherwise, it returns false.
Like the equality operator, greater than or equal to operator will convert data types while comparing.
Example
6 >= 6 // true : 6 is equal to 6, return true
7 >= '3' // true : 7 is greater than 3, return true
2 >= 3 // false : 2 is NOT greater or equal to 3, return false
'7' >= 9 // false : 7 is NOT greater or equal to 9, return false
The less than operator " < " compares the values of two numbers.
If the number to the left is less than the number to the right, it returns true. Otherwise, it returns false.
Like the equality operator, less than operator converts data types while comparing.
Example
2 < 5 // true : 2 is smaller than 5, return true
'3' < 7 // true : 3 is smaller than 7, return true
5 < 5 // false : 5 is NOT smaller than 5, return false
3 < 2 // false : 3 is NOT smaller than 2, return false
'8' < 4 // false : 8 is NOT smaller than 4, return false
The less than or equal to operator " <= " compares the values of two numbers.
If the number to the left is less than or equal to the number to the right, it returns true.
If the number on the left is greater than the number on the right, it returns false.
Like the equality operator, less than or equal to converts data types.
Example
4 <= 5 // true : 4 is smaller than 5, return true
'7' <= 7 // true : 7 is equal to 7, return true
5 <= 5 // true : 5 is equal to 5, return true
3 <= 2 // false : 3 is NOT smaller or equal to 2, return false
'8' <= 4 // false : 8 is NOT smaller or equal to 4, return false
Sometimes you will need to test more than one thing at a time.
The logical and operator " && " returns true if and only if the operands to the left and right of it are true.
The same effect could be achieved by nesting an if statement inside another if
Example
if (num > 5) {
if (num > 10) {
return "Yes";
}
}
return "No";
This code will only return "Yes" if num is greater than 5 and less than 10. The same logic can be written as:
if (num > 5 && num < 10) {
return "Yes";
}
return "No";
The logical or operator " || " returns true if either of the operands is true. Otherwise, it returns false.
The logical or operator is composed of two pipe " | " symbols. This can typically be found between your Backspace and Enter keys.
Example
if (num > 10) {
return "No";
}
if (num < 5) {
return "No";
}
return "Yes";
This code will return "Yes" only if num is between 5 and 10 (5 and 10 included). The same logic can be written as:
if (num > 10 || num < 5) {
return "No";
}
return "Yes";
When a condition for an if statement is true, the block of code following it is executed.
What about when that condition is false? Normally nothing would happen.
With an else statement, an alternate block of code can be executed.
Example
if (num > 10) {
return "Bigger than 10";
} else {
return "10 or Less";
}
If you have multiple conditions that need to be addressed, you can chain if statements together with else if statements.
Example
if (num > 15) {
return "Bigger than 15";
} else if (num < 5) {
return "Smaller than 5";
} else {
return "Between 5 and 15";
}
Order is important in if, else if statements.
The function is executed from top to bottom so you will want to be careful of what statement comes first.
Take these two functions as an example.
First
function foo(x) {
if (x < 1) {
return "Less than one";
} else if (x < 2) {
return "Less than two";
} else {
return "Greater than or equal to two";
}
}
Second
function bar(x) {
if (x < 2) {
return "Less than two";
} else if (x < 1) {
return "Less than one";
} else {
return "Greater than or equal to two";
}
}
While these two functions look nearly identical if we pass a number to both we get different outputs.
foo(0) // "Less than one"
bar(0) // "Less than two"
if/else statements can be chained together for complex logic.
Here is the code of multiple chained if / else if statements.
Pseudocode
if (condition1) {
statement1
} else if (condition2) {
statement2
} else if (condition3) {
statement3
. . .
} else {
statementN
}
If you have many options to choose from, use a switch statement.
A switch statement tests a value and can have many case statements which define various possible values.
Statements are executed from the first matched case value until a break is encountered.
Pseudocode
switch(num) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
case valueN:
statementN;
break;
}
case values are tested with strict equality " === ". The break tells JavaScript to stop executing statements.
If the break is omitted, the next statement will be executed.
In a switch statement you may not be able to specify all possible values as case statements.
Instead, you can add the default statement which will be executed if no matching case statements are found.
Think of it like the final else statement in an if/else chain.
A default statement should be the last case.
Pseudocode
switch (num) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
default:
defaultStatement;
break;
}
If the break statement is omitted from a switch statement's case, the following case statement(s) are executed until a break is encountered.
If you have multiple inputs with the same output, you can represent them in a switch statement.
Example
switch(val) {
case 1:
case 2:
case 3:
result = "1, 2, or 3";
break;
case 4:
result = "4 alone";
}
Cases for 1, 2, and 3 will all produce the same result.
If you have many options to choose from, a switch statement can be easier to write than many chained if/else if statements.
Example
if (val === 1) {
answer = "a";
} else if (val === 2) {
answer = "b";
} else {
answer = "c";
}
This code can be replaced with:
switch(val) {
case 1:
answer = "a";
break;
case 2:
answer = "b";
break;
default:
answer = "c";
}
All comparison operators return a boolean true or false value. Sometimes people use an if/else statement to do a comparison.
Example
function isEqual(a,b) {
if (a === b) {
return true; // returning true after checking if a === b
} else {
return false; // returning false after checking if a === b
}
}
But there's a better way to do this. Since " === " returns true or false, we can return the result of the comparison.
function isEqual(a,b) {
return a === b; // returning true or false after checking if a === b
}
When a return statement is reached, the execution of the current function stops and control returns to the calling location.
Example
function myFun() {
console.log("Hello");
return "World";
console.log("byebye")
}
myFun();
The above outputs "Hello" to the console, returns "World", but "byebye" is never output, because the function exits at the return statement.
Objects are similar to arrays, except that instead of using indexes to access and modify their data,
you access the data in objects through what are called properties.
Objects are useful for storing data in a structured way, and can represent real world objects, like a cat.
Example
var cat = {
"name": "Whiskers",
"legs": 4,
"tails": 1,
"enemies": ["Water", "Dogs"]
};
In this example, all the properties are stored as strings, such as - "name", "legs", and "tails".
However, you can also use numbers as properties. You can even omit the quotes for single-word string properties.
var anotherObject = {
make: "Ford",
5: "five",
"model": "focus"
};
However, if your object has any non-string properties, JavaScript will automatically typecast them as strings.
There are two ways to access the properties of an object: dot notation " . " and bracket notation " [] ", similar to an array.
Dot notation is what you use when you know the name of the property you're trying to access ahead of time.
dot notation " . " Example
var myObj = {
name1: "value1",
name2: "value2"
};
var prop1val = myObj.name1; // returns value1 to the variable
var prop2val = myObj.name2; // returns value2 to the variable
The second way to access the properties of an object is bracket notation " [] ".
If the property of the object you are trying to access has a space in its name, you will need to use bracket notation.
However, you can still use bracket notation on object properties without spaces.
bracket notation " [] " Example
var myObj = {
"Space Name": "Kirk",
"More Space": "Spock",
"NoSpace": "USS Enterprise"
};
myObj["Space Name"]; // Kirk
myObj['More Space']; // Spock
myObj["NoSpace"]; // USS Enterprise
Note that property names with spaces in them must be in quotes (single or double).
Another use of bracket notation on objects is to access a property which is stored as the value of a variable.
This can be very useful for iterating through an object's properties or when accessing a lookup table.
Example
var dogs = {
Fido: "Mutt", Hunter: "Doberman", Snoopie: "Beagle"
};
var myDog = "Hunter";
var myBreed = dogs[myDog];
console.log(myBreed); // "Doberman"
Another way you can use this concept is when the property's name is collected dynamically during the program execution.
var someObj = {
propName: "John"
};
function propPrefix(str) {
var s = "prop";
return s + str;
}
var someProp = propPrefix("Name"); // someProp now holds the value 'propName'
console.log(someObj[someProp]); // "John"
Note that we do not use quotes around the variable name when using it to access the property because we are using the value of the variable, not the name.
You can update an object's properties at any time, just like you would update any other variable.
You can use either dot or bracket notation to update.
Example
var ourDog = {
"name": "Apollo",
"legs": 4,
"tails": 1,
"friends": ["everyone!"]
};
Since he's a particularly happy dog, let's change his name to "Happy Apollo".
Here's how we update the object's name property.
ourDog.name = "Happy Apollo";
or
ourDog["name"] = "Happy Apollo";
Now when we evaluate ourDog.name, instead of getting "Apollo", we'll get his new name, "Happy Apollo".
You can add new properties to existing JavaScript objects the same way you would modify them.
var ourDog = {
"name": "Apollo",
"legs": 4,
"tails": 1,
"friends": ["everyone!"]
};
Here's how we would add a "bark" property to ourDog.
ourDog.bark = "woof-woof";
or
ourDog["bark"] = "woof-woof";
After this the variable will look like
var ourDog = {
"name": "Apollo",
"legs": 4,
"tails": 1,
"friends": ["everyone!"],
"bark": "woof-woof"
};
Now when we evaluate ourDog.bark, we'll get his bark, "woof-woof".
We can also delete properties from objects.
Example
var ourDog = {
"name": "Apollo",
"legs": 4,
"tails": 1,
"friends": ["everyone!"],
"bark": "woof-woof"
};
delete ourDog.bark;
or
delete ourDog["bark"];
Objects can be thought of as a key/value storage, like a dictionary.
If you have tabular data, you can use an object to "lookup" values rather than a switch statement or an if/else chain.
This is most useful when you know that your input data is limited to a certain range.
Example
var alpha = {
1:"Z",
2:"Y",
3:"X",
4:"W",
...
24:"C",
25:"B",
26:"A"
};
alpha[2]; // "Y"
alpha[24]; // "C"
var value = 2;
alpha[value]; // "Y"
Sometimes it is useful to check if the property of a given object exists or not.
We can use the .hasOwnProperty(propname) method of objects to determine if that object has the given property name.
.hasOwnProperty() returns true or false if the property is found or not.
Example
var myObj = {
top: "hat",
bottom: "pants"
};
myObj.hasOwnProperty("top"); // true
myObj.hasOwnProperty("middle"); // false
Sometimes you may want to store data in a flexible Data Structure.
A JavaScript object is one way to handle flexible data.
They allow for arbitrary combinations of strings, numbers, booleans, arrays, functions, and objects.
Example
var ourMusic = [
{
"artist": "Daft Punk",
"title": "Homework",
"release_year": 1997,
"formats": [
"CD",
"Cassette",
"LP"
],
"gold": true
}
];
This is an array which contains one object inside. The object has various pieces of metadata about an album.
It also has a nested "formats" array. If you want to add more album records, you can do this by adding records to the top level array.
Objects hold data in a property, which has a key-value format.
In the example above, "artist": "Daft Punk" is a property that has a key of "artist" and a value of "Daft Punk".
JavaScript Object Notation or JSON is a related data interchange format used to store data.
{
"artist": "Daft Punk",
"title": "Homework",
"release_year": 1997,
"formats": [
"CD",
"Cassette",
"LP"
],
"gold": true
}
Note
You will need to place a comma after every object in the array, unless it is the last object in the array.
The sub-properties of objects can be accessed by chaining together the dot or bracket notation.
Example
var ourStorage = {
"desk": {
"drawer": "stapler"
},
"cabinet": {
"top drawer": {
"folder1": "a file",
"folder2": "secrets"
},
"bottom drawer": "soda"
}
};
ourStorage.cabinet["top drawer"].folder2; // "secrets"
ourStorage["cabinet"]["top drawer"]["folder2"]; // "secrets"
ourStorage.desk.drawer; // "stapler"
ourStorage["desk"].drawer; // "stapler"
ourStorage.desk["drawer"]; // "stapler"
Objects can contain both nested objects and nested arrays.
Similar to accessing nested objects, Array bracket notation can be chained to access nested arrays.
Example
var ourPets = [
{ // [0]
animalType: "cat",
names: [
"Meowzer", // [0]
"Fluffy", // [1]
"Kit-Cat" // [2]
]
},
{ // [1]
animalType: "dog",
names: [
"Spot", // [0]
"Bowser", // [1]
"Frankie" // [2]
]
}
];
ourPets[0].names[1]; // "Fluffy"
ourPets[1].names[0]; // "Spot"
// other methods
ourPets[0]["names"][1] // "Fluffy"
ourPets[0].names; // "Meowzer,Fluffy,Kit-Cat"
ourPets[0]["names"]; // "Meowzer,Fluffy,Kit-Cat"
ourPets[0].animalType; // "cat"
ourPets[1].names; // "Spot,Bowser,Frankie"
ourPets[1].["names"]; // "Spot,Bowser,Frankie"
ourPets[1].animalType; // "dog"
You can run the same code multiple times by using a loop.
The first type of loop we will learn is called a " while " loop because it runs "while" a specified condition is true
and stops once that condition is no longer true.
Example
var ourArray = [];
var i = 0;
while(i < 5) {
ourArray.push(i);
i++;
}
ourArray will now contain [0,1,2,3,4].
The most common type of JavaScript loop is called a " for loop " because it runs "for" a specific number of times.
for loops are declared with three optional expressions separated by semicolons.
for ([initialization]; [condition]; [final-expression])
The initialization statement is executed one time only before the loop starts. It is typically used to define and setup your loop variable.
The condition statement is evaluated at the beginning of every loop iteration and will continue as long as it evaluates to true.
When condition is false at the start of the iteration, the loop will stop executing.
This means if condition starts as false, your loop will never execute.
The final-expression is executed at the end of each loop iteration, prior to the next condition check
and is usually used to increment or decrement your loop counter.
In the following example we initialize with i = 0 and iterate while our condition i < 5 is true.
We'll increment i by 1 in each loop iteration with i++ as our final-expression.
var ourArray = [];
for (var i = 0; i < 5; i++) {
ourArray.push(i);
}
ourArray will now contain [0,1,2,3,4].
for loops don't have to iterate one at a time.
By changing our final-expression, we can count by even numbers.
We'll start at i = 0 and loop while i < 10. We'll increment i by 2 each loop with i += 2.
var ourArray = [];
for (var i = 0; i < 10; i += 2) {
ourArray.push(i);
}
ourArray will now contain [0,2,4,6,8].
Let's change our initialization so we can count by odd numbers.
We'll start at i = 1 and loop while i < 10. We'll increment i by 2 each loop with i += 2.
var ourArray = [];
for (var i = 1; i < 10; i += 2) {
ourArray.push(i);
}
ourArray will now contain [1,3,5,7,9].
A for loop can also count backwards, so long as we can define the right conditions.
In order to count backwards by 2, we'll need to ,change our initialization, condition, and final-expression.
We'll start at i = 10 and loop while i > 0. We'll decrement i by 2 each loop with i -= 2.
var ourArray = [];
for (var i=10; i > 0; i-=2) {
ourArray.push(i);
}
ourArray will now contain [10,8,6,4,2].
A common task in JavaScript is to iterate through the contents of an array.
One way to do that is with a for loop. This code will output each element of the array arr to the console.
var arr = [10,9,8,7,6]; // .length = 5, indexes [0] - [4]
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
Remember that Arrays have zero-based numbering, which means the last index of the array is length - 1.
Our condition for this loop is i < arr.length, which stops when i is at length - 1.
If you have a multi-dimensional array, you can use the same logic as the prior waypoint to loop through both the array and any sub-arrays.
Example
var arr = [
[1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; j++) {
console.log(arr[i][j]);
}
}
This outputs each sub-element in arr one at a time.
Note that for the inner loop, we are checking the .length of arr[i], since arr[i] is itself an array.
The next type of loop is called a " do...while " loop because it first will "do" one pass of the code inside the loop no matter what,
and then it runs "while" a specified condition is true and stops once that condition is no longer true.
Example
var ourArray = [];
var i = 0;
do {
ourArray.push(i);
i++;
} while (i < 5);
This behaves just as you would expect with any other type of loop, and the resulting array will look like [0, 1, 2, 3, 4].
However, what makes the do...while different from other loops is how it behaves when the condition fails on the first check.
Here is a regular while loop that will run the code in the loop as long as i < 5.
var ourArray = [];
var i = 5;
while (i < 5) {
ourArray.push(i);
i++;
}
Notice that we initialize the value of i to be 5. When we execute the next line, we notice that i is not less than 5.
So we do not execute the code inside the loop. The result is that ourArray will end up with nothing added to it,
so it will still look like this [] when all the code in the example above finishes running.
Now, take a look at a do...while loop.
var ourArray = [];
var i = 5;
do {
ourArray.push(i);
i++;
} while (i < 5);
In this case, we initialize the value of i as 5, just like we did with the while loop.
When we get to the next line, there is no check for the value of i, so we go to the code inside the curly braces and execute it.
We will add one element to the array and increment i before we get to the condition check.
Then, when we get to checking if i < 5 see that i is now 6, which fails the conditional check.
So we exit the loop and are done. At the end of the above example, the value of ourArray is [5].
Essentially, a do...while loop ensures that the code inside the loop will run at least once.
Random numbers are useful for creating random behavior.
JavaScript has a Math.random() function that generates a random decimal number between 0 (inclusive) and not quite up to 1 (exclusive).
Thus Math.random() can return a 0 but never quite return a 1
Note
Like Storing Values with the Equal Operator, all function calls will be resolved before the return executes,
so we can return the value of the Math.random() function.
We can generate random decimal numbers, but it's even more useful if we use it to generate random whole numbers.
Use Math.random() to generate a random decimal.
Multiply that random decimal by 20.
Use another function, Math.floor() to round the number down to its nearest whole number.
Remember that Math.random() can never quite return a 1 and, because we're rounding down, it's impossible to actually get 20.
This technique will give us a whole number between 0 and 19.
Putting everything together, this is what our code looks like.
Math.floor(Math.random() * 20); // Returns 0 to 19 as whole numbers
We are calling Math.random(), multiplying the result by 20, then passing the value to Math.floor() function
to round the value down to the nearest whole number.
Instead of generating a random number between zero and a given number,
we can generate a random number that falls within a range of two specific numbers.
To do this, we'll define a minimum number min and a maximum number max.
Here's the formula we'll use.
Math.floor(Math.random() * (max - min + 1)) + min;
The + 1 is needed. We will see when we import some min/max numbers.
Example
var min = 6;
var max = 20;
Math.floor(Math.random() * (max - min + 1)) + min;
//if Math.Random = 0:
Math.floor(Math.random() * (20 - 6)) + 6;
// returns Math.floor(0 * 14) + 6; Math.floor(0) + 6 = 6;
Math.floor(Math.random() * (20 - 6 + 1)) + 6;
// returns Math.floor(0 * 15) + 6; Math.floor(0) + 6 = 6;
//if Math.Random = 0.07:
Math.floor(Math.random() * (20 - 6)) + 6;
// returns Math.floor(0.07 * 14) + 6; Math.floor(0.98) + 6 = 6;
Math.floor(Math.random() * (20 - 6 + 1)) + 6;
// returns Math.floor(0.07 * 15) + 6; Math.floor(1.05) + 6 = 7;
//if Math.Random = 0.99:
Math.floor(Math.random() * (20 - 6)) + 6;
// returns Math.floor(0.99 * 14) + 6; Math.floor(13.86) + 6 = 19;
Math.floor(Math.random() * (20 - 6 + 1)) + 6;
// returns Math.floor(0.99 * 15) + 6; Math.floor(14.85) + 6 = 20;
The " + 1 " looks confusing, but it needs to be there because we are always rounding down, so the top number would never actually be reached without it.
The parseInt() function parses a string and returns an integer.
Example
var a = parseInt("007");
The above function converts the string "007" to an integer 7.
If the first character in the string can't be converted into a number, then it returns NaN.
The parseInt() function parses a string and returns an integer.
It takes a second argument for the radix, which specifies the base of the number in the string.
The radix can be an integer between 2 and 36.
The function call looks like
parseInt(string, radix);
Example
var a = parseInt("11", 2);
The radix variable says that "11" is in the binary system, or base 2.
This example converts the string "11" to an integer 3.
Like
var a = parseInt("10011", 2);
Converts the string "10011" to an integer 25.
The conditional operator, also called the ternary operator, can be used as a one line if-else expression.
The syntax is:
condition ? statement-if-true : statement-if-false;
The following function uses an if-else statement to check a condition:
function findGreater(a, b) {
if(a > b) {
return "a is greater";
}
else {
return "b is greater";
}
}
This can be re-written using the conditional operator:
function findGreater(a, b) {
return a > b ? "a is greater" : "b is greater";
}
or
function findGreater(a, b) {
return a > b ? true : false;
}
Above [0][97] you used a single conditional operator.
You can also chain them together to check for multiple conditions.
The following function uses if, else if, and else statements to check multiple conditions:
function findGreaterOrEqual(a, b) {
if(a === b) {
return "a and b are equal";
}
else if(a > b) {
return "a is greater";
}
else {
return "b is greater";
}
}
The above function can be re-written using multiple conditional operators:
function findGreaterOrEqual(a, b) {
return (a === b) ? "a and b are equal" : (a > b) ? "a is greater" : "b is greater";
}